sqlite3.c 4.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.7.17. 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 sqliteInt.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. ** Internal interface definitions for SQLite.
  41. **
  42. */
  43. #ifndef _SQLITEINT_H_
  44. #define _SQLITEINT_H_
  45. /*
  46. ** These #defines should enable >2GB file support on POSIX if the
  47. ** underlying operating system supports it. If the OS lacks
  48. ** large file support, or if the OS is windows, these should be no-ops.
  49. **
  50. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  51. ** system #includes. Hence, this block of code must be the very first
  52. ** code in all source files.
  53. **
  54. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  55. ** on the compiler command line. This is necessary if you are compiling
  56. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  57. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  58. ** without this option, LFS is enable. But LFS does not exist in the kernel
  59. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  60. ** portability you should omit LFS.
  61. **
  62. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  63. */
  64. #ifndef SQLITE_DISABLE_LFS
  65. # define _LARGE_FILE 1
  66. # ifndef _FILE_OFFSET_BITS
  67. # define _FILE_OFFSET_BITS 64
  68. # endif
  69. # define _LARGEFILE_SOURCE 1
  70. #endif
  71. /*
  72. ** Include the configuration header output by 'configure' if we're using the
  73. ** autoconf-based build
  74. */
  75. #ifdef _HAVE_SQLITE_CONFIG_H
  76. #include "config.h"
  77. #endif
  78. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  79. /************** Begin file sqliteLimit.h *************************************/
  80. /*
  81. ** 2007 May 7
  82. **
  83. ** The author disclaims copyright to this source code. In place of
  84. ** a legal notice, here is a blessing:
  85. **
  86. ** May you do good and not evil.
  87. ** May you find forgiveness for yourself and forgive others.
  88. ** May you share freely, never taking more than you give.
  89. **
  90. *************************************************************************
  91. **
  92. ** This file defines various limits of what SQLite can process.
  93. */
  94. /*
  95. ** The maximum length of a TEXT or BLOB in bytes. This also
  96. ** limits the size of a row in a table or index.
  97. **
  98. ** The hard limit is the ability of a 32-bit signed integer
  99. ** to count the size: 2^31-1 or 2147483647.
  100. */
  101. #ifndef SQLITE_MAX_LENGTH
  102. # define SQLITE_MAX_LENGTH 1000000000
  103. #endif
  104. /*
  105. ** This is the maximum number of
  106. **
  107. ** * Columns in a table
  108. ** * Columns in an index
  109. ** * Columns in a view
  110. ** * Terms in the SET clause of an UPDATE statement
  111. ** * Terms in the result set of a SELECT statement
  112. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  113. ** * Terms in the VALUES clause of an INSERT statement
  114. **
  115. ** The hard upper limit here is 32676. Most database people will
  116. ** tell you that in a well-normalized database, you usually should
  117. ** not have more than a dozen or so columns in any table. And if
  118. ** that is the case, there is no point in having more than a few
  119. ** dozen values in any of the other situations described above.
  120. */
  121. #ifndef SQLITE_MAX_COLUMN
  122. # define SQLITE_MAX_COLUMN 2000
  123. #endif
  124. /*
  125. ** The maximum length of a single SQL statement in bytes.
  126. **
  127. ** It used to be the case that setting this value to zero would
  128. ** turn the limit off. That is no longer true. It is not possible
  129. ** to turn this limit off.
  130. */
  131. #ifndef SQLITE_MAX_SQL_LENGTH
  132. # define SQLITE_MAX_SQL_LENGTH 1000000000
  133. #endif
  134. /*
  135. ** The maximum depth of an expression tree. This is limited to
  136. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  137. ** want to place more severe limits on the complexity of an
  138. ** expression.
  139. **
  140. ** A value of 0 used to mean that the limit was not enforced.
  141. ** But that is no longer true. The limit is now strictly enforced
  142. ** at all times.
  143. */
  144. #ifndef SQLITE_MAX_EXPR_DEPTH
  145. # define SQLITE_MAX_EXPR_DEPTH 1000
  146. #endif
  147. /*
  148. ** The maximum number of terms in a compound SELECT statement.
  149. ** The code generator for compound SELECT statements does one
  150. ** level of recursion for each term. A stack overflow can result
  151. ** if the number of terms is too large. In practice, most SQL
  152. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  153. ** any limit on the number of terms in a compount SELECT.
  154. */
  155. #ifndef SQLITE_MAX_COMPOUND_SELECT
  156. # define SQLITE_MAX_COMPOUND_SELECT 500
  157. #endif
  158. /*
  159. ** The maximum number of opcodes in a VDBE program.
  160. ** Not currently enforced.
  161. */
  162. #ifndef SQLITE_MAX_VDBE_OP
  163. # define SQLITE_MAX_VDBE_OP 25000
  164. #endif
  165. /*
  166. ** The maximum number of arguments to an SQL function.
  167. */
  168. #ifndef SQLITE_MAX_FUNCTION_ARG
  169. # define SQLITE_MAX_FUNCTION_ARG 127
  170. #endif
  171. /*
  172. ** The maximum number of in-memory pages to use for the main database
  173. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  174. */
  175. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  176. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  177. #endif
  178. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  179. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  180. #endif
  181. /*
  182. ** The default number of frames to accumulate in the log file before
  183. ** checkpointing the database in WAL mode.
  184. */
  185. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  186. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  187. #endif
  188. /*
  189. ** The maximum number of attached databases. This must be between 0
  190. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  191. ** is used internally to track attached databases.
  192. */
  193. #ifndef SQLITE_MAX_ATTACHED
  194. # define SQLITE_MAX_ATTACHED 10
  195. #endif
  196. /*
  197. ** The maximum value of a ?nnn wildcard that the parser will accept.
  198. */
  199. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  200. # define SQLITE_MAX_VARIABLE_NUMBER 999
  201. #endif
  202. /* Maximum page size. The upper bound on this value is 65536. This a limit
  203. ** imposed by the use of 16-bit offsets within each page.
  204. **
  205. ** Earlier versions of SQLite allowed the user to change this value at
  206. ** compile time. This is no longer permitted, on the grounds that it creates
  207. ** a library that is technically incompatible with an SQLite library
  208. ** compiled with a different limit. If a process operating on a database
  209. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  210. ** compiled with the default page-size limit will not be able to rollback
  211. ** the aborted transaction. This could lead to database corruption.
  212. */
  213. #ifdef SQLITE_MAX_PAGE_SIZE
  214. # undef SQLITE_MAX_PAGE_SIZE
  215. #endif
  216. #define SQLITE_MAX_PAGE_SIZE 65536
  217. /*
  218. ** The default size of a database page.
  219. */
  220. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  221. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  222. #endif
  223. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  224. # undef SQLITE_DEFAULT_PAGE_SIZE
  225. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  226. #endif
  227. /*
  228. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  229. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  230. ** device characteristics (sector-size and atomic write() support),
  231. ** SQLite may choose a larger value. This constant is the maximum value
  232. ** SQLite will choose on its own.
  233. */
  234. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  235. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  236. #endif
  237. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  238. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  239. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  240. #endif
  241. /*
  242. ** Maximum number of pages in one database file.
  243. **
  244. ** This is really just the default value for the max_page_count pragma.
  245. ** This value can be lowered (or raised) at run-time using that the
  246. ** max_page_count macro.
  247. */
  248. #ifndef SQLITE_MAX_PAGE_COUNT
  249. # define SQLITE_MAX_PAGE_COUNT 1073741823
  250. #endif
  251. /*
  252. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  253. ** operator.
  254. */
  255. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  256. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  257. #endif
  258. /*
  259. ** Maximum depth of recursion for triggers.
  260. **
  261. ** A value of 1 means that a trigger program will not be able to itself
  262. ** fire any triggers. A value of 0 means that no trigger programs at all
  263. ** may be executed.
  264. */
  265. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  266. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  267. #endif
  268. /************** End of sqliteLimit.h *****************************************/
  269. /************** Continuing where we left off in sqliteInt.h ******************/
  270. /* Disable nuisance warnings on Borland compilers */
  271. #if defined(__BORLANDC__)
  272. #pragma warn -rch /* unreachable code */
  273. #pragma warn -ccc /* Condition is always true or false */
  274. #pragma warn -aus /* Assigned value is never used */
  275. #pragma warn -csu /* Comparing signed and unsigned */
  276. #pragma warn -spa /* Suspicious pointer arithmetic */
  277. #endif
  278. /* Needed for various definitions... */
  279. #ifndef _GNU_SOURCE
  280. # define _GNU_SOURCE
  281. #endif
  282. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  283. # define _BSD_SOURCE
  284. #endif
  285. /*
  286. ** Include standard header files as necessary
  287. */
  288. #ifdef HAVE_STDINT_H
  289. #include <stdint.h>
  290. #endif
  291. #ifdef HAVE_INTTYPES_H
  292. #include <inttypes.h>
  293. #endif
  294. /*
  295. ** The following macros are used to cast pointers to integers and
  296. ** integers to pointers. The way you do this varies from one compiler
  297. ** to the next, so we have developed the following set of #if statements
  298. ** to generate appropriate macros for a wide range of compilers.
  299. **
  300. ** The correct "ANSI" way to do this is to use the intptr_t type.
  301. ** Unfortunately, that typedef is not available on all compilers, or
  302. ** if it is available, it requires an #include of specific headers
  303. ** that vary from one machine to the next.
  304. **
  305. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  306. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  307. ** So we have to define the macros in different ways depending on the
  308. ** compiler.
  309. */
  310. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  311. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  312. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  313. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  314. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  315. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  316. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  317. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  318. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  319. #else /* Generates a warning - but it always works */
  320. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  321. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  322. #endif
  323. /*
  324. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  325. ** 0 means mutexes are permanently disable and the library is never
  326. ** threadsafe. 1 means the library is serialized which is the highest
  327. ** level of threadsafety. 2 means the libary is multithreaded - multiple
  328. ** threads can use SQLite as long as no two threads try to use the same
  329. ** database connection at the same time.
  330. **
  331. ** Older versions of SQLite used an optional THREADSAFE macro.
  332. ** We support that for legacy.
  333. */
  334. #if !defined(SQLITE_THREADSAFE)
  335. # if defined(THREADSAFE)
  336. # define SQLITE_THREADSAFE THREADSAFE
  337. # else
  338. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  339. # endif
  340. #endif
  341. /*
  342. ** Powersafe overwrite is on by default. But can be turned off using
  343. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  344. */
  345. #ifndef SQLITE_POWERSAFE_OVERWRITE
  346. # define SQLITE_POWERSAFE_OVERWRITE 1
  347. #endif
  348. /*
  349. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  350. ** It determines whether or not the features related to
  351. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  352. ** be overridden at runtime using the sqlite3_config() API.
  353. */
  354. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  355. # define SQLITE_DEFAULT_MEMSTATUS 1
  356. #endif
  357. /*
  358. ** Exactly one of the following macros must be defined in order to
  359. ** specify which memory allocation subsystem to use.
  360. **
  361. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  362. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  363. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  364. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  365. **
  366. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  367. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  368. ** will cause HeapValidate to be called. If heap validation should fail, an
  369. ** assertion will be triggered.
  370. **
  371. ** (Historical note: There used to be several other options, but we've
  372. ** pared it down to just these three.)
  373. **
  374. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  375. ** the default.
  376. */
  377. #if defined(SQLITE_SYSTEM_MALLOC) \
  378. + defined(SQLITE_WIN32_MALLOC) \
  379. + defined(SQLITE_ZERO_MALLOC) \
  380. + defined(SQLITE_MEMDEBUG)>1
  381. # error "Two or more of the following compile-time configuration options\
  382. are defined but at most one is allowed:\
  383. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  384. SQLITE_ZERO_MALLOC"
  385. #endif
  386. #if defined(SQLITE_SYSTEM_MALLOC) \
  387. + defined(SQLITE_WIN32_MALLOC) \
  388. + defined(SQLITE_ZERO_MALLOC) \
  389. + defined(SQLITE_MEMDEBUG)==0
  390. # define SQLITE_SYSTEM_MALLOC 1
  391. #endif
  392. /*
  393. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  394. ** sizes of memory allocations below this value where possible.
  395. */
  396. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  397. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  398. #endif
  399. /*
  400. ** We need to define _XOPEN_SOURCE as follows in order to enable
  401. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  402. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  403. ** so it is omitted there. See ticket #2673.
  404. **
  405. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  406. ** implemented on some systems. So we avoid defining it at all
  407. ** if it is already defined or if it is unneeded because we are
  408. ** not doing a threadsafe build. Ticket #2681.
  409. **
  410. ** See also ticket #2741.
  411. */
  412. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
  413. && !defined(__APPLE__) && SQLITE_THREADSAFE
  414. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  415. #endif
  416. /*
  417. ** The TCL headers are only needed when compiling the TCL bindings.
  418. */
  419. #if defined(SQLITE_TCL) || defined(TCLSH)
  420. # include <tcl.h>
  421. #endif
  422. /*
  423. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  424. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  425. ** make it true by defining or undefining NDEBUG.
  426. **
  427. ** Setting NDEBUG makes the code smaller and run faster by disabling the
  428. ** number assert() statements in the code. So we want the default action
  429. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  430. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  431. ** feature.
  432. */
  433. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  434. # define NDEBUG 1
  435. #endif
  436. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  437. # undef NDEBUG
  438. #endif
  439. /*
  440. ** The testcase() macro is used to aid in coverage testing. When
  441. ** doing coverage testing, the condition inside the argument to
  442. ** testcase() must be evaluated both true and false in order to
  443. ** get full branch coverage. The testcase() macro is inserted
  444. ** to help ensure adequate test coverage in places where simple
  445. ** condition/decision coverage is inadequate. For example, testcase()
  446. ** can be used to make sure boundary values are tested. For
  447. ** bitmask tests, testcase() can be used to make sure each bit
  448. ** is significant and used at least once. On switch statements
  449. ** where multiple cases go to the same block of code, testcase()
  450. ** can insure that all cases are evaluated.
  451. **
  452. */
  453. #ifdef SQLITE_COVERAGE_TEST
  454. SQLITE_PRIVATE void sqlite3Coverage(int);
  455. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  456. #else
  457. # define testcase(X)
  458. #endif
  459. /*
  460. ** The TESTONLY macro is used to enclose variable declarations or
  461. ** other bits of code that are needed to support the arguments
  462. ** within testcase() and assert() macros.
  463. */
  464. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  465. # define TESTONLY(X) X
  466. #else
  467. # define TESTONLY(X)
  468. #endif
  469. /*
  470. ** Sometimes we need a small amount of code such as a variable initialization
  471. ** to setup for a later assert() statement. We do not want this code to
  472. ** appear when assert() is disabled. The following macro is therefore
  473. ** used to contain that setup code. The "VVA" acronym stands for
  474. ** "Verification, Validation, and Accreditation". In other words, the
  475. ** code within VVA_ONLY() will only run during verification processes.
  476. */
  477. #ifndef NDEBUG
  478. # define VVA_ONLY(X) X
  479. #else
  480. # define VVA_ONLY(X)
  481. #endif
  482. /*
  483. ** The ALWAYS and NEVER macros surround boolean expressions which
  484. ** are intended to always be true or false, respectively. Such
  485. ** expressions could be omitted from the code completely. But they
  486. ** are included in a few cases in order to enhance the resilience
  487. ** of SQLite to unexpected behavior - to make the code "self-healing"
  488. ** or "ductile" rather than being "brittle" and crashing at the first
  489. ** hint of unplanned behavior.
  490. **
  491. ** In other words, ALWAYS and NEVER are added for defensive code.
  492. **
  493. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  494. ** be true and false so that the unreachable code then specify will
  495. ** not be counted as untested code.
  496. */
  497. #if defined(SQLITE_COVERAGE_TEST)
  498. # define ALWAYS(X) (1)
  499. # define NEVER(X) (0)
  500. #elif !defined(NDEBUG)
  501. # define ALWAYS(X) ((X)?1:(assert(0),0))
  502. # define NEVER(X) ((X)?(assert(0),1):0)
  503. #else
  504. # define ALWAYS(X) (X)
  505. # define NEVER(X) (X)
  506. #endif
  507. /*
  508. ** Return true (non-zero) if the input is a integer that is too large
  509. ** to fit in 32-bits. This macro is used inside of various testcase()
  510. ** macros to verify that we have tested SQLite for large-file support.
  511. */
  512. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  513. /*
  514. ** The macro unlikely() is a hint that surrounds a boolean
  515. ** expression that is usually false. Macro likely() surrounds
  516. ** a boolean expression that is usually true. GCC is able to
  517. ** use these hints to generate better code, sometimes.
  518. */
  519. #if defined(__GNUC__) && 0
  520. # define likely(X) __builtin_expect((X),1)
  521. # define unlikely(X) __builtin_expect((X),0)
  522. #else
  523. # define likely(X) !!(X)
  524. # define unlikely(X) !!(X)
  525. #endif
  526. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  527. /************** Begin file sqlite3.h *****************************************/
  528. /*
  529. ** 2001 September 15
  530. **
  531. ** The author disclaims copyright to this source code. In place of
  532. ** a legal notice, here is a blessing:
  533. **
  534. ** May you do good and not evil.
  535. ** May you find forgiveness for yourself and forgive others.
  536. ** May you share freely, never taking more than you give.
  537. **
  538. *************************************************************************
  539. ** This header file defines the interface that the SQLite library
  540. ** presents to client programs. If a C-function, structure, datatype,
  541. ** or constant definition does not appear in this file, then it is
  542. ** not a published API of SQLite, is subject to change without
  543. ** notice, and should not be referenced by programs that use SQLite.
  544. **
  545. ** Some of the definitions that are in this file are marked as
  546. ** "experimental". Experimental interfaces are normally new
  547. ** features recently added to SQLite. We do not anticipate changes
  548. ** to experimental interfaces but reserve the right to make minor changes
  549. ** if experience from use "in the wild" suggest such changes are prudent.
  550. **
  551. ** The official C-language API documentation for SQLite is derived
  552. ** from comments in this file. This file is the authoritative source
  553. ** on how SQLite interfaces are suppose to operate.
  554. **
  555. ** The name of this file under configuration management is "sqlite.h.in".
  556. ** The makefile makes some minor changes to this file (such as inserting
  557. ** the version number) and changes its name to "sqlite3.h" as
  558. ** part of the build process.
  559. */
  560. #ifndef _SQLITE3_H_
  561. #define _SQLITE3_H_
  562. #include <stdarg.h> /* Needed for the definition of va_list */
  563. /*
  564. ** Make sure we can call this stuff from C++.
  565. */
  566. #if 0
  567. extern "C" {
  568. #endif
  569. /*
  570. ** Add the ability to override 'extern'
  571. */
  572. #ifndef SQLITE_EXTERN
  573. # define SQLITE_EXTERN extern
  574. #endif
  575. #ifndef SQLITE_API
  576. # define SQLITE_API
  577. #endif
  578. /*
  579. ** These no-op macros are used in front of interfaces to mark those
  580. ** interfaces as either deprecated or experimental. New applications
  581. ** should not use deprecated interfaces - they are support for backwards
  582. ** compatibility only. Application writers should be aware that
  583. ** experimental interfaces are subject to change in point releases.
  584. **
  585. ** These macros used to resolve to various kinds of compiler magic that
  586. ** would generate warning messages when they were used. But that
  587. ** compiler magic ended up generating such a flurry of bug reports
  588. ** that we have taken it all out and gone back to using simple
  589. ** noop macros.
  590. */
  591. #define SQLITE_DEPRECATED
  592. #define SQLITE_EXPERIMENTAL
  593. /*
  594. ** Ensure these symbols were not defined by some previous header file.
  595. */
  596. #ifdef SQLITE_VERSION
  597. # undef SQLITE_VERSION
  598. #endif
  599. #ifdef SQLITE_VERSION_NUMBER
  600. # undef SQLITE_VERSION_NUMBER
  601. #endif
  602. /*
  603. ** CAPI3REF: Compile-Time Library Version Numbers
  604. **
  605. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  606. ** evaluates to a string literal that is the SQLite version in the
  607. ** format "X.Y.Z" where X is the major version number (always 3 for
  608. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  609. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  610. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  611. ** numbers used in [SQLITE_VERSION].)^
  612. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  613. ** be larger than the release from which it is derived. Either Y will
  614. ** be held constant and Z will be incremented or else Y will be incremented
  615. ** and Z will be reset to zero.
  616. **
  617. ** Since version 3.6.18, SQLite source code has been stored in the
  618. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  619. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  620. ** a string which identifies a particular check-in of SQLite
  621. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  622. ** string contains the date and time of the check-in (UTC) and an SHA1
  623. ** hash of the entire source tree.
  624. **
  625. ** See also: [sqlite3_libversion()],
  626. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  627. ** [sqlite_version()] and [sqlite_source_id()].
  628. */
  629. #define SQLITE_VERSION "3.7.17"
  630. #define SQLITE_VERSION_NUMBER 3007017
  631. #define SQLITE_SOURCE_ID "2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668"
  632. /*
  633. ** CAPI3REF: Run-Time Library Version Numbers
  634. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  635. **
  636. ** These interfaces provide the same information as the [SQLITE_VERSION],
  637. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  638. ** but are associated with the library instead of the header file. ^(Cautious
  639. ** programmers might include assert() statements in their application to
  640. ** verify that values returned by these interfaces match the macros in
  641. ** the header, and thus insure that the application is
  642. ** compiled with matching library and header files.
  643. **
  644. ** <blockquote><pre>
  645. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  646. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  647. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  648. ** </pre></blockquote>)^
  649. **
  650. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  651. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  652. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  653. ** function is provided for use in DLLs since DLL users usually do not have
  654. ** direct access to string constants within the DLL. ^The
  655. ** sqlite3_libversion_number() function returns an integer equal to
  656. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  657. ** a pointer to a string constant whose value is the same as the
  658. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  659. **
  660. ** See also: [sqlite_version()] and [sqlite_source_id()].
  661. */
  662. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  663. SQLITE_API const char *sqlite3_libversion(void);
  664. SQLITE_API const char *sqlite3_sourceid(void);
  665. SQLITE_API int sqlite3_libversion_number(void);
  666. /*
  667. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  668. **
  669. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  670. ** indicating whether the specified option was defined at
  671. ** compile time. ^The SQLITE_ prefix may be omitted from the
  672. ** option name passed to sqlite3_compileoption_used().
  673. **
  674. ** ^The sqlite3_compileoption_get() function allows iterating
  675. ** over the list of options that were defined at compile time by
  676. ** returning the N-th compile time option string. ^If N is out of range,
  677. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  678. ** prefix is omitted from any strings returned by
  679. ** sqlite3_compileoption_get().
  680. **
  681. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  682. ** and sqlite3_compileoption_get() may be omitted by specifying the
  683. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  684. **
  685. ** See also: SQL functions [sqlite_compileoption_used()] and
  686. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  687. */
  688. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  689. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  690. SQLITE_API const char *sqlite3_compileoption_get(int N);
  691. #endif
  692. /*
  693. ** CAPI3REF: Test To See If The Library Is Threadsafe
  694. **
  695. ** ^The sqlite3_threadsafe() function returns zero if and only if
  696. ** SQLite was compiled with mutexing code omitted due to the
  697. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  698. **
  699. ** SQLite can be compiled with or without mutexes. When
  700. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  701. ** are enabled and SQLite is threadsafe. When the
  702. ** [SQLITE_THREADSAFE] macro is 0,
  703. ** the mutexes are omitted. Without the mutexes, it is not safe
  704. ** to use SQLite concurrently from more than one thread.
  705. **
  706. ** Enabling mutexes incurs a measurable performance penalty.
  707. ** So if speed is of utmost importance, it makes sense to disable
  708. ** the mutexes. But for maximum safety, mutexes should be enabled.
  709. ** ^The default behavior is for mutexes to be enabled.
  710. **
  711. ** This interface can be used by an application to make sure that the
  712. ** version of SQLite that it is linking against was compiled with
  713. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  714. **
  715. ** This interface only reports on the compile-time mutex setting
  716. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  717. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  718. ** can be fully or partially disabled using a call to [sqlite3_config()]
  719. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  720. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  721. ** sqlite3_threadsafe() function shows only the compile-time setting of
  722. ** thread safety, not any run-time changes to that setting made by
  723. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  724. ** is unchanged by calls to sqlite3_config().)^
  725. **
  726. ** See the [threading mode] documentation for additional information.
  727. */
  728. SQLITE_API int sqlite3_threadsafe(void);
  729. /*
  730. ** CAPI3REF: Database Connection Handle
  731. ** KEYWORDS: {database connection} {database connections}
  732. **
  733. ** Each open SQLite database is represented by a pointer to an instance of
  734. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  735. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  736. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  737. ** and [sqlite3_close_v2()] are its destructors. There are many other
  738. ** interfaces (such as
  739. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  740. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  741. ** sqlite3 object.
  742. */
  743. typedef struct sqlite3 sqlite3;
  744. /*
  745. ** CAPI3REF: 64-Bit Integer Types
  746. ** KEYWORDS: sqlite_int64 sqlite_uint64
  747. **
  748. ** Because there is no cross-platform way to specify 64-bit integer types
  749. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  750. **
  751. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  752. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  753. ** compatibility only.
  754. **
  755. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  756. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  757. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  758. ** between 0 and +18446744073709551615 inclusive.
  759. */
  760. #ifdef SQLITE_INT64_TYPE
  761. typedef SQLITE_INT64_TYPE sqlite_int64;
  762. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  763. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  764. typedef __int64 sqlite_int64;
  765. typedef unsigned __int64 sqlite_uint64;
  766. #else
  767. typedef long long int sqlite_int64;
  768. typedef unsigned long long int sqlite_uint64;
  769. #endif
  770. typedef sqlite_int64 sqlite3_int64;
  771. typedef sqlite_uint64 sqlite3_uint64;
  772. /*
  773. ** If compiling for a processor that lacks floating point support,
  774. ** substitute integer for floating-point.
  775. */
  776. #ifdef SQLITE_OMIT_FLOATING_POINT
  777. # define double sqlite3_int64
  778. #endif
  779. /*
  780. ** CAPI3REF: Closing A Database Connection
  781. **
  782. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  783. ** for the [sqlite3] object.
  784. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  785. ** the [sqlite3] object is successfully destroyed and all associated
  786. ** resources are deallocated.
  787. **
  788. ** ^If the database connection is associated with unfinalized prepared
  789. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  790. ** will leave the database connection open and return [SQLITE_BUSY].
  791. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  792. ** and unfinished sqlite3_backups, then the database connection becomes
  793. ** an unusable "zombie" which will automatically be deallocated when the
  794. ** last prepared statement is finalized or the last sqlite3_backup is
  795. ** finished. The sqlite3_close_v2() interface is intended for use with
  796. ** host languages that are garbage collected, and where the order in which
  797. ** destructors are called is arbitrary.
  798. **
  799. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  800. ** [sqlite3_blob_close | close] all [BLOB handles], and
  801. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  802. ** with the [sqlite3] object prior to attempting to close the object. ^If
  803. ** sqlite3_close_v2() is called on a [database connection] that still has
  804. ** outstanding [prepared statements], [BLOB handles], and/or
  805. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  806. ** of resources is deferred until all [prepared statements], [BLOB handles],
  807. ** and [sqlite3_backup] objects are also destroyed.
  808. **
  809. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  810. ** the transaction is automatically rolled back.
  811. **
  812. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  813. ** must be either a NULL
  814. ** pointer or an [sqlite3] object pointer obtained
  815. ** from [sqlite3_open()], [sqlite3_open16()], or
  816. ** [sqlite3_open_v2()], and not previously closed.
  817. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  818. ** argument is a harmless no-op.
  819. */
  820. SQLITE_API int sqlite3_close(sqlite3*);
  821. SQLITE_API int sqlite3_close_v2(sqlite3*);
  822. /*
  823. ** The type for a callback function.
  824. ** This is legacy and deprecated. It is included for historical
  825. ** compatibility and is not documented.
  826. */
  827. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  828. /*
  829. ** CAPI3REF: One-Step Query Execution Interface
  830. **
  831. ** The sqlite3_exec() interface is a convenience wrapper around
  832. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  833. ** that allows an application to run multiple statements of SQL
  834. ** without having to use a lot of C code.
  835. **
  836. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  837. ** semicolon-separate SQL statements passed into its 2nd argument,
  838. ** in the context of the [database connection] passed in as its 1st
  839. ** argument. ^If the callback function of the 3rd argument to
  840. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  841. ** coming out of the evaluated SQL statements. ^The 4th argument to
  842. ** sqlite3_exec() is relayed through to the 1st argument of each
  843. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  844. ** is NULL, then no callback is ever invoked and result rows are
  845. ** ignored.
  846. **
  847. ** ^If an error occurs while evaluating the SQL statements passed into
  848. ** sqlite3_exec(), then execution of the current statement stops and
  849. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  850. ** is not NULL then any error message is written into memory obtained
  851. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  852. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  853. ** on error message strings returned through the 5th parameter of
  854. ** of sqlite3_exec() after the error message string is no longer needed.
  855. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  856. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  857. ** NULL before returning.
  858. **
  859. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  860. ** routine returns SQLITE_ABORT without invoking the callback again and
  861. ** without running any subsequent SQL statements.
  862. **
  863. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  864. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  865. ** callback is an array of pointers to strings obtained as if from
  866. ** [sqlite3_column_text()], one for each column. ^If an element of a
  867. ** result row is NULL then the corresponding string pointer for the
  868. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  869. ** sqlite3_exec() callback is an array of pointers to strings where each
  870. ** entry represents the name of corresponding result column as obtained
  871. ** from [sqlite3_column_name()].
  872. **
  873. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  874. ** to an empty string, or a pointer that contains only whitespace and/or
  875. ** SQL comments, then no SQL statements are evaluated and the database
  876. ** is not changed.
  877. **
  878. ** Restrictions:
  879. **
  880. ** <ul>
  881. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  882. ** is a valid and open [database connection].
  883. ** <li> The application must not close [database connection] specified by
  884. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  885. ** <li> The application must not modify the SQL statement text passed into
  886. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  887. ** </ul>
  888. */
  889. SQLITE_API int sqlite3_exec(
  890. sqlite3*, /* An open database */
  891. const char *sql, /* SQL to be evaluated */
  892. int (*callback)(void*,int,char**,char**), /* Callback function */
  893. void *, /* 1st argument to callback */
  894. char **errmsg /* Error msg written here */
  895. );
  896. /*
  897. ** CAPI3REF: Result Codes
  898. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  899. ** KEYWORDS: {result code} {result codes}
  900. **
  901. ** Many SQLite functions return an integer result code from the set shown
  902. ** here in order to indicate success or failure.
  903. **
  904. ** New error codes may be added in future versions of SQLite.
  905. **
  906. ** See also: [SQLITE_IOERR_READ | extended result codes],
  907. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  908. */
  909. #define SQLITE_OK 0 /* Successful result */
  910. /* beginning-of-error-codes */
  911. #define SQLITE_ERROR 1 /* SQL error or missing database */
  912. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  913. #define SQLITE_PERM 3 /* Access permission denied */
  914. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  915. #define SQLITE_BUSY 5 /* The database file is locked */
  916. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  917. #define SQLITE_NOMEM 7 /* A malloc() failed */
  918. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  919. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  920. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  921. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  922. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  923. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  924. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  925. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  926. #define SQLITE_EMPTY 16 /* Database is empty */
  927. #define SQLITE_SCHEMA 17 /* The database schema changed */
  928. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  929. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  930. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  931. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  932. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  933. #define SQLITE_AUTH 23 /* Authorization denied */
  934. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  935. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  936. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  937. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  938. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  939. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  940. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  941. /* end-of-error-codes */
  942. /*
  943. ** CAPI3REF: Extended Result Codes
  944. ** KEYWORDS: {extended error code} {extended error codes}
  945. ** KEYWORDS: {extended result code} {extended result codes}
  946. **
  947. ** In its default configuration, SQLite API routines return one of 26 integer
  948. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  949. ** these result codes are too coarse-grained. They do not provide as
  950. ** much information about problems as programmers might like. In an effort to
  951. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  952. ** support for additional result codes that provide more detailed information
  953. ** about errors. The extended result codes are enabled or disabled
  954. ** on a per database connection basis using the
  955. ** [sqlite3_extended_result_codes()] API.
  956. **
  957. ** Some of the available extended result codes are listed here.
  958. ** One may expect the number of extended result codes will be expand
  959. ** over time. Software that uses extended result codes should expect
  960. ** to see new result codes in future releases of SQLite.
  961. **
  962. ** The SQLITE_OK result code will never be extended. It will always
  963. ** be exactly zero.
  964. */
  965. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  966. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  967. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  968. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  969. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  970. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  971. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  972. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  973. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  974. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  975. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  976. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  977. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  978. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  979. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  980. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  981. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  982. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  983. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  984. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  985. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  986. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  987. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  988. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  989. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  990. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  991. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  992. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  993. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  994. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  995. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  996. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  997. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  998. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  999. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1000. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1001. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1002. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1003. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1004. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1005. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1006. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1007. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1008. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1009. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1010. /*
  1011. ** CAPI3REF: Flags For File Open Operations
  1012. **
  1013. ** These bit values are intended for use in the
  1014. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1015. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1016. */
  1017. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1018. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1019. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1020. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1021. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1022. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1023. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1024. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1025. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1026. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1027. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1028. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1029. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1030. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1031. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1032. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1033. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1034. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1035. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1036. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1037. /* Reserved: 0x00F00000 */
  1038. /*
  1039. ** CAPI3REF: Device Characteristics
  1040. **
  1041. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1042. ** object returns an integer which is a vector of these
  1043. ** bit values expressing I/O characteristics of the mass storage
  1044. ** device that holds the file that the [sqlite3_io_methods]
  1045. ** refers to.
  1046. **
  1047. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1048. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1049. ** mean that writes of blocks that are nnn bytes in size and
  1050. ** are aligned to an address which is an integer multiple of
  1051. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1052. ** that when data is appended to a file, the data is appended
  1053. ** first then the size of the file is extended, never the other
  1054. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1055. ** information is written to disk in the same order as calls
  1056. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1057. ** after reboot following a crash or power loss, the only bytes in a
  1058. ** file that were written at the application level might have changed
  1059. ** and that adjacent bytes, even bytes within the same sector are
  1060. ** guaranteed to be unchanged.
  1061. */
  1062. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1063. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1064. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1065. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1066. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1067. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1068. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1069. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1070. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1071. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1072. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1073. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1074. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1075. /*
  1076. ** CAPI3REF: File Locking Levels
  1077. **
  1078. ** SQLite uses one of these integer values as the second
  1079. ** argument to calls it makes to the xLock() and xUnlock() methods
  1080. ** of an [sqlite3_io_methods] object.
  1081. */
  1082. #define SQLITE_LOCK_NONE 0
  1083. #define SQLITE_LOCK_SHARED 1
  1084. #define SQLITE_LOCK_RESERVED 2
  1085. #define SQLITE_LOCK_PENDING 3
  1086. #define SQLITE_LOCK_EXCLUSIVE 4
  1087. /*
  1088. ** CAPI3REF: Synchronization Type Flags
  1089. **
  1090. ** When SQLite invokes the xSync() method of an
  1091. ** [sqlite3_io_methods] object it uses a combination of
  1092. ** these integer values as the second argument.
  1093. **
  1094. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1095. ** sync operation only needs to flush data to mass storage. Inode
  1096. ** information need not be flushed. If the lower four bits of the flag
  1097. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1098. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1099. ** to use Mac OS X style fullsync instead of fsync().
  1100. **
  1101. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1102. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1103. ** settings. The [synchronous pragma] determines when calls to the
  1104. ** xSync VFS method occur and applies uniformly across all platforms.
  1105. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1106. ** energetic or rigorous or forceful the sync operations are and
  1107. ** only make a difference on Mac OSX for the default SQLite code.
  1108. ** (Third-party VFS implementations might also make the distinction
  1109. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1110. ** operating systems natively supported by SQLite, only Mac OSX
  1111. ** cares about the difference.)
  1112. */
  1113. #define SQLITE_SYNC_NORMAL 0x00002
  1114. #define SQLITE_SYNC_FULL 0x00003
  1115. #define SQLITE_SYNC_DATAONLY 0x00010
  1116. /*
  1117. ** CAPI3REF: OS Interface Open File Handle
  1118. **
  1119. ** An [sqlite3_file] object represents an open file in the
  1120. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1121. ** implementations will
  1122. ** want to subclass this object by appending additional fields
  1123. ** for their own use. The pMethods entry is a pointer to an
  1124. ** [sqlite3_io_methods] object that defines methods for performing
  1125. ** I/O operations on the open file.
  1126. */
  1127. typedef struct sqlite3_file sqlite3_file;
  1128. struct sqlite3_file {
  1129. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1130. };
  1131. /*
  1132. ** CAPI3REF: OS Interface File Virtual Methods Object
  1133. **
  1134. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1135. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1136. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1137. ** This object defines the methods used to perform various operations
  1138. ** against the open file represented by the [sqlite3_file] object.
  1139. **
  1140. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1141. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1142. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1143. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1144. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1145. ** to NULL.
  1146. **
  1147. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1148. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1149. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1150. ** flag may be ORed in to indicate that only the data of the file
  1151. ** and not its inode needs to be synced.
  1152. **
  1153. ** The integer values to xLock() and xUnlock() are one of
  1154. ** <ul>
  1155. ** <li> [SQLITE_LOCK_NONE],
  1156. ** <li> [SQLITE_LOCK_SHARED],
  1157. ** <li> [SQLITE_LOCK_RESERVED],
  1158. ** <li> [SQLITE_LOCK_PENDING], or
  1159. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1160. ** </ul>
  1161. ** xLock() increases the lock. xUnlock() decreases the lock.
  1162. ** The xCheckReservedLock() method checks whether any database connection,
  1163. ** either in this process or in some other process, is holding a RESERVED,
  1164. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1165. ** if such a lock exists and false otherwise.
  1166. **
  1167. ** The xFileControl() method is a generic interface that allows custom
  1168. ** VFS implementations to directly control an open file using the
  1169. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1170. ** integer opcode. The third argument is a generic pointer intended to
  1171. ** point to a structure that may contain arguments or space in which to
  1172. ** write return values. Potential uses for xFileControl() might be
  1173. ** functions to enable blocking locks with timeouts, to change the
  1174. ** locking strategy (for example to use dot-file locks), to inquire
  1175. ** about the status of a lock, or to break stale locks. The SQLite
  1176. ** core reserves all opcodes less than 100 for its own use.
  1177. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  1178. ** Applications that define a custom xFileControl method should use opcodes
  1179. ** greater than 100 to avoid conflicts. VFS implementations should
  1180. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1181. ** recognize.
  1182. **
  1183. ** The xSectorSize() method returns the sector size of the
  1184. ** device that underlies the file. The sector size is the
  1185. ** minimum write that can be performed without disturbing
  1186. ** other bytes in the file. The xDeviceCharacteristics()
  1187. ** method returns a bit vector describing behaviors of the
  1188. ** underlying device:
  1189. **
  1190. ** <ul>
  1191. ** <li> [SQLITE_IOCAP_ATOMIC]
  1192. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1193. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1194. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1195. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1196. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1197. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1198. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1199. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1200. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1201. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1202. ** </ul>
  1203. **
  1204. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1205. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1206. ** mean that writes of blocks that are nnn bytes in size and
  1207. ** are aligned to an address which is an integer multiple of
  1208. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1209. ** that when data is appended to a file, the data is appended
  1210. ** first then the size of the file is extended, never the other
  1211. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1212. ** information is written to disk in the same order as calls
  1213. ** to xWrite().
  1214. **
  1215. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1216. ** in the unread portions of the buffer with zeros. A VFS that
  1217. ** fails to zero-fill short reads might seem to work. However,
  1218. ** failure to zero-fill short reads will eventually lead to
  1219. ** database corruption.
  1220. */
  1221. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1222. struct sqlite3_io_methods {
  1223. int iVersion;
  1224. int (*xClose)(sqlite3_file*);
  1225. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1226. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1227. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1228. int (*xSync)(sqlite3_file*, int flags);
  1229. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1230. int (*xLock)(sqlite3_file*, int);
  1231. int (*xUnlock)(sqlite3_file*, int);
  1232. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1233. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1234. int (*xSectorSize)(sqlite3_file*);
  1235. int (*xDeviceCharacteristics)(sqlite3_file*);
  1236. /* Methods above are valid for version 1 */
  1237. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1238. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1239. void (*xShmBarrier)(sqlite3_file*);
  1240. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1241. /* Methods above are valid for version 2 */
  1242. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1243. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1244. /* Methods above are valid for version 3 */
  1245. /* Additional methods may be added in future releases */
  1246. };
  1247. /*
  1248. ** CAPI3REF: Standard File Control Opcodes
  1249. **
  1250. ** These integer constants are opcodes for the xFileControl method
  1251. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1252. ** interface.
  1253. **
  1254. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1255. ** opcode causes the xFileControl method to write the current state of
  1256. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1257. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1258. ** into an integer that the pArg argument points to. This capability
  1259. ** is used during testing and only needs to be supported when SQLITE_TEST
  1260. ** is defined.
  1261. ** <ul>
  1262. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1263. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1264. ** layer a hint of how large the database file will grow to be during the
  1265. ** current transaction. This hint is not guaranteed to be accurate but it
  1266. ** is often close. The underlying VFS might choose to preallocate database
  1267. ** file space based on this hint in order to help writes to the database
  1268. ** file run faster.
  1269. **
  1270. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1271. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1272. ** extends and truncates the database file in chunks of a size specified
  1273. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1274. ** point to an integer (type int) containing the new chunk-size to use
  1275. ** for the nominated database. Allocating database file space in large
  1276. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1277. ** improve performance on some systems.
  1278. **
  1279. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1280. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1281. ** to the [sqlite3_file] object associated with a particular database
  1282. ** connection. See the [sqlite3_file_control()] documentation for
  1283. ** additional information.
  1284. **
  1285. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1286. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  1287. ** SQLite and sent to all VFSes in place of a call to the xSync method
  1288. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  1289. ** Some specialized VFSes need this signal in order to operate correctly
  1290. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  1291. ** VFSes do not need this signal and should silently ignore this opcode.
  1292. ** Applications should not call [sqlite3_file_control()] with this
  1293. ** opcode as doing so may disrupt the operation of the specialized VFSes
  1294. ** that do require it.
  1295. **
  1296. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1297. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1298. ** retry counts and intervals for certain disk I/O operations for the
  1299. ** windows [VFS] in order to provide robustness in the presence of
  1300. ** anti-virus programs. By default, the windows VFS will retry file read,
  1301. ** file write, and file delete operations up to 10 times, with a delay
  1302. ** of 25 milliseconds before the first retry and with the delay increasing
  1303. ** by an additional 25 milliseconds with each subsequent retry. This
  1304. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1305. ** to be adjusted. The values are changed for all database connections
  1306. ** within the same process. The argument is a pointer to an array of two
  1307. ** integers where the first integer i the new retry count and the second
  1308. ** integer is the delay. If either integer is negative, then the setting
  1309. ** is not changed but instead the prior value of that setting is written
  1310. ** into the array entry, allowing the current retry settings to be
  1311. ** interrogated. The zDbName parameter is ignored.
  1312. **
  1313. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1314. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1315. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1316. ** write ahead log and shared memory files used for transaction control
  1317. ** are automatically deleted when the latest connection to the database
  1318. ** closes. Setting persistent WAL mode causes those files to persist after
  1319. ** close. Persisting the files is useful when other processes that do not
  1320. ** have write permission on the directory containing the database file want
  1321. ** to read the database file, as the WAL and shared memory files must exist
  1322. ** in order for the database to be readable. The fourth parameter to
  1323. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1324. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1325. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1326. ** WAL persistence setting.
  1327. **
  1328. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1329. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1330. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1331. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1332. ** xDeviceCharacteristics methods. The fourth parameter to
  1333. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1334. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1335. ** mode. If the integer is -1, then it is overwritten with the current
  1336. ** zero-damage mode setting.
  1337. **
  1338. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1339. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1340. ** a write transaction to indicate that, unless it is rolled back for some
  1341. ** reason, the entire database file will be overwritten by the current
  1342. ** transaction. This is used by VACUUM operations.
  1343. **
  1344. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1345. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1346. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1347. ** final bottom-level VFS are written into memory obtained from
  1348. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1349. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1350. ** The caller is responsible for freeing the memory when done. As with
  1351. ** all file-control actions, there is no guarantee that this will actually
  1352. ** do anything. Callers should initialize the char* variable to a NULL
  1353. ** pointer in case this file-control is not implemented. This file-control
  1354. ** is intended for diagnostic use only.
  1355. **
  1356. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1357. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1358. ** file control is sent to the open [sqlite3_file] object corresponding
  1359. ** to the database file to which the pragma statement refers. ^The argument
  1360. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1361. ** pointers to strings (char**) in which the second element of the array
  1362. ** is the name of the pragma and the third element is the argument to the
  1363. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1364. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1365. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1366. ** or the equivalent and that string will become the result of the pragma or
  1367. ** the error message if the pragma fails. ^If the
  1368. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1369. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1370. ** file control returns [SQLITE_OK], then the parser assumes that the
  1371. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1372. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1373. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1374. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1375. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1376. ** file control occurs at the beginning of pragma statement analysis and so
  1377. ** it is able to override built-in [PRAGMA] statements.
  1378. **
  1379. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1380. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1381. ** file-control may be invoked by SQLite on the database file handle
  1382. ** shortly after it is opened in order to provide a custom VFS with access
  1383. ** to the connections busy-handler callback. The argument is of type (void **)
  1384. ** - an array of two (void *) values. The first (void *) actually points
  1385. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1386. ** busy-handler, this function should be invoked with the second (void *) in
  1387. ** the array as the only argument. If it returns non-zero, then the operation
  1388. ** should be retried. If it returns zero, the custom VFS should abandon the
  1389. ** current operation.
  1390. **
  1391. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1392. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1393. ** to have SQLite generate a
  1394. ** temporary filename using the same algorithm that is followed to generate
  1395. ** temporary filenames for TEMP tables and other internal uses. The
  1396. ** argument should be a char** which will be filled with the filename
  1397. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1398. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1399. **
  1400. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1401. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1402. ** maximum number of bytes that will be used for memory-mapped I/O.
  1403. ** The argument is a pointer to a value of type sqlite3_int64 that
  1404. ** is an advisory maximum number of bytes in the file to memory map. The
  1405. ** pointer is overwritten with the old value. The limit is not changed if
  1406. ** the value originally pointed to is negative, and so the current limit
  1407. ** can be queried by passing in a pointer to a negative number. This
  1408. ** file-control is used internally to implement [PRAGMA mmap_size].
  1409. **
  1410. ** </ul>
  1411. */
  1412. #define SQLITE_FCNTL_LOCKSTATE 1
  1413. #define SQLITE_GET_LOCKPROXYFILE 2
  1414. #define SQLITE_SET_LOCKPROXYFILE 3
  1415. #define SQLITE_LAST_ERRNO 4
  1416. #define SQLITE_FCNTL_SIZE_HINT 5
  1417. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1418. #define SQLITE_FCNTL_FILE_POINTER 7
  1419. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1420. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1421. #define SQLITE_FCNTL_PERSIST_WAL 10
  1422. #define SQLITE_FCNTL_OVERWRITE 11
  1423. #define SQLITE_FCNTL_VFSNAME 12
  1424. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1425. #define SQLITE_FCNTL_PRAGMA 14
  1426. #define SQLITE_FCNTL_BUSYHANDLER 15
  1427. #define SQLITE_FCNTL_TEMPFILENAME 16
  1428. #define SQLITE_FCNTL_MMAP_SIZE 18
  1429. /*
  1430. ** CAPI3REF: Mutex Handle
  1431. **
  1432. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1433. ** abstract type for a mutex object. The SQLite core never looks
  1434. ** at the internal representation of an [sqlite3_mutex]. It only
  1435. ** deals with pointers to the [sqlite3_mutex] object.
  1436. **
  1437. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1438. */
  1439. typedef struct sqlite3_mutex sqlite3_mutex;
  1440. /*
  1441. ** CAPI3REF: OS Interface Object
  1442. **
  1443. ** An instance of the sqlite3_vfs object defines the interface between
  1444. ** the SQLite core and the underlying operating system. The "vfs"
  1445. ** in the name of the object stands for "virtual file system". See
  1446. ** the [VFS | VFS documentation] for further information.
  1447. **
  1448. ** The value of the iVersion field is initially 1 but may be larger in
  1449. ** future versions of SQLite. Additional fields may be appended to this
  1450. ** object when the iVersion value is increased. Note that the structure
  1451. ** of the sqlite3_vfs object changes in the transaction between
  1452. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1453. ** modified.
  1454. **
  1455. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1456. ** structure used by this VFS. mxPathname is the maximum length of
  1457. ** a pathname in this VFS.
  1458. **
  1459. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1460. ** the pNext pointer. The [sqlite3_vfs_register()]
  1461. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1462. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1463. ** searches the list. Neither the application code nor the VFS
  1464. ** implementation should use the pNext pointer.
  1465. **
  1466. ** The pNext field is the only field in the sqlite3_vfs
  1467. ** structure that SQLite will ever modify. SQLite will only access
  1468. ** or modify this field while holding a particular static mutex.
  1469. ** The application should never modify anything within the sqlite3_vfs
  1470. ** object once the object has been registered.
  1471. **
  1472. ** The zName field holds the name of the VFS module. The name must
  1473. ** be unique across all VFS modules.
  1474. **
  1475. ** [[sqlite3_vfs.xOpen]]
  1476. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1477. ** is either a NULL pointer or string obtained
  1478. ** from xFullPathname() with an optional suffix added.
  1479. ** ^If a suffix is added to the zFilename parameter, it will
  1480. ** consist of a single "-" character followed by no more than
  1481. ** 11 alphanumeric and/or "-" characters.
  1482. ** ^SQLite further guarantees that
  1483. ** the string will be valid and unchanged until xClose() is
  1484. ** called. Because of the previous sentence,
  1485. ** the [sqlite3_file] can safely store a pointer to the
  1486. ** filename if it needs to remember the filename for some reason.
  1487. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1488. ** must invent its own temporary name for the file. ^Whenever the
  1489. ** xFilename parameter is NULL it will also be the case that the
  1490. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1491. **
  1492. ** The flags argument to xOpen() includes all bits set in
  1493. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1494. ** or [sqlite3_open16()] is used, then flags includes at least
  1495. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1496. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1497. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1498. **
  1499. ** ^(SQLite will also add one of the following flags to the xOpen()
  1500. ** call, depending on the object being opened:
  1501. **
  1502. ** <ul>
  1503. ** <li> [SQLITE_OPEN_MAIN_DB]
  1504. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1505. ** <li> [SQLITE_OPEN_TEMP_DB]
  1506. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1507. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1508. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1509. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1510. ** <li> [SQLITE_OPEN_WAL]
  1511. ** </ul>)^
  1512. **
  1513. ** The file I/O implementation can use the object type flags to
  1514. ** change the way it deals with files. For example, an application
  1515. ** that does not care about crash recovery or rollback might make
  1516. ** the open of a journal file a no-op. Writes to this journal would
  1517. ** also be no-ops, and any attempt to read the journal would return
  1518. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1519. ** file will be doing page-aligned sector reads and writes in a random
  1520. ** order and set up its I/O subsystem accordingly.
  1521. **
  1522. ** SQLite might also add one of the following flags to the xOpen method:
  1523. **
  1524. ** <ul>
  1525. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1526. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1527. ** </ul>
  1528. **
  1529. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1530. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1531. ** will be set for TEMP databases and their journals, transient
  1532. ** databases, and subjournals.
  1533. **
  1534. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1535. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1536. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1537. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1538. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1539. ** be created, and that it is an error if it already exists.
  1540. ** It is <i>not</i> used to indicate the file should be opened
  1541. ** for exclusive access.
  1542. **
  1543. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1544. ** to hold the [sqlite3_file] structure passed as the third
  1545. ** argument to xOpen. The xOpen method does not have to
  1546. ** allocate the structure; it should just fill it in. Note that
  1547. ** the xOpen method must set the sqlite3_file.pMethods to either
  1548. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1549. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1550. ** element will be valid after xOpen returns regardless of the success
  1551. ** or failure of the xOpen call.
  1552. **
  1553. ** [[sqlite3_vfs.xAccess]]
  1554. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1555. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1556. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1557. ** to test whether a file is at least readable. The file can be a
  1558. ** directory.
  1559. **
  1560. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1561. ** output buffer xFullPathname. The exact size of the output buffer
  1562. ** is also passed as a parameter to both methods. If the output buffer
  1563. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1564. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1565. ** to prevent this by setting mxPathname to a sufficiently large value.
  1566. **
  1567. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1568. ** interfaces are not strictly a part of the filesystem, but they are
  1569. ** included in the VFS structure for completeness.
  1570. ** The xRandomness() function attempts to return nBytes bytes
  1571. ** of good-quality randomness into zOut. The return value is
  1572. ** the actual number of bytes of randomness obtained.
  1573. ** The xSleep() method causes the calling thread to sleep for at
  1574. ** least the number of microseconds given. ^The xCurrentTime()
  1575. ** method returns a Julian Day Number for the current date and time as
  1576. ** a floating point value.
  1577. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1578. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1579. ** a 24-hour day).
  1580. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1581. ** date and time if that method is available (if iVersion is 2 or
  1582. ** greater and the function pointer is not NULL) and will fall back
  1583. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1584. **
  1585. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1586. ** are not used by the SQLite core. These optional interfaces are provided
  1587. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1588. ** system calls with functions under its control, a test program can
  1589. ** simulate faults and error conditions that would otherwise be difficult
  1590. ** or impossible to induce. The set of system calls that can be overridden
  1591. ** varies from one VFS to another, and from one version of the same VFS to the
  1592. ** next. Applications that use these interfaces must be prepared for any
  1593. ** or all of these interfaces to be NULL or for their behavior to change
  1594. ** from one release to the next. Applications must not attempt to access
  1595. ** any of these methods if the iVersion of the VFS is less than 3.
  1596. */
  1597. typedef struct sqlite3_vfs sqlite3_vfs;
  1598. typedef void (*sqlite3_syscall_ptr)(void);
  1599. struct sqlite3_vfs {
  1600. int iVersion; /* Structure version number (currently 3) */
  1601. int szOsFile; /* Size of subclassed sqlite3_file */
  1602. int mxPathname; /* Maximum file pathname length */
  1603. sqlite3_vfs *pNext; /* Next registered VFS */
  1604. const char *zName; /* Name of this virtual file system */
  1605. void *pAppData; /* Pointer to application-specific data */
  1606. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1607. int flags, int *pOutFlags);
  1608. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1609. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1610. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1611. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1612. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1613. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1614. void (*xDlClose)(sqlite3_vfs*, void*);
  1615. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1616. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1617. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1618. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1619. /*
  1620. ** The methods above are in version 1 of the sqlite_vfs object
  1621. ** definition. Those that follow are added in version 2 or later
  1622. */
  1623. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1624. /*
  1625. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1626. ** Those below are for version 3 and greater.
  1627. */
  1628. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1629. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1630. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1631. /*
  1632. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1633. ** New fields may be appended in figure versions. The iVersion
  1634. ** value will increment whenever this happens.
  1635. */
  1636. };
  1637. /*
  1638. ** CAPI3REF: Flags for the xAccess VFS method
  1639. **
  1640. ** These integer constants can be used as the third parameter to
  1641. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1642. ** what kind of permissions the xAccess method is looking for.
  1643. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1644. ** simply checks whether the file exists.
  1645. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1646. ** checks whether the named directory is both readable and writable
  1647. ** (in other words, if files can be added, removed, and renamed within
  1648. ** the directory).
  1649. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1650. ** [temp_store_directory pragma], though this could change in a future
  1651. ** release of SQLite.
  1652. ** With SQLITE_ACCESS_READ, the xAccess method
  1653. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1654. ** currently unused, though it might be used in a future release of
  1655. ** SQLite.
  1656. */
  1657. #define SQLITE_ACCESS_EXISTS 0
  1658. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1659. #define SQLITE_ACCESS_READ 2 /* Unused */
  1660. /*
  1661. ** CAPI3REF: Flags for the xShmLock VFS method
  1662. **
  1663. ** These integer constants define the various locking operations
  1664. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1665. ** following are the only legal combinations of flags to the
  1666. ** xShmLock method:
  1667. **
  1668. ** <ul>
  1669. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1670. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1671. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1672. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1673. ** </ul>
  1674. **
  1675. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1676. ** was given no the corresponding lock.
  1677. **
  1678. ** The xShmLock method can transition between unlocked and SHARED or
  1679. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1680. ** and EXCLUSIVE.
  1681. */
  1682. #define SQLITE_SHM_UNLOCK 1
  1683. #define SQLITE_SHM_LOCK 2
  1684. #define SQLITE_SHM_SHARED 4
  1685. #define SQLITE_SHM_EXCLUSIVE 8
  1686. /*
  1687. ** CAPI3REF: Maximum xShmLock index
  1688. **
  1689. ** The xShmLock method on [sqlite3_io_methods] may use values
  1690. ** between 0 and this upper bound as its "offset" argument.
  1691. ** The SQLite core will never attempt to acquire or release a
  1692. ** lock outside of this range
  1693. */
  1694. #define SQLITE_SHM_NLOCK 8
  1695. /*
  1696. ** CAPI3REF: Initialize The SQLite Library
  1697. **
  1698. ** ^The sqlite3_initialize() routine initializes the
  1699. ** SQLite library. ^The sqlite3_shutdown() routine
  1700. ** deallocates any resources that were allocated by sqlite3_initialize().
  1701. ** These routines are designed to aid in process initialization and
  1702. ** shutdown on embedded systems. Workstation applications using
  1703. ** SQLite normally do not need to invoke either of these routines.
  1704. **
  1705. ** A call to sqlite3_initialize() is an "effective" call if it is
  1706. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1707. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1708. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1709. ** of sqlite3_initialize() does any initialization. All other calls
  1710. ** are harmless no-ops.)^
  1711. **
  1712. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1713. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1714. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1715. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1716. **
  1717. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1718. ** is not. The sqlite3_shutdown() interface must only be called from a
  1719. ** single thread. All open [database connections] must be closed and all
  1720. ** other SQLite resources must be deallocated prior to invoking
  1721. ** sqlite3_shutdown().
  1722. **
  1723. ** Among other things, ^sqlite3_initialize() will invoke
  1724. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1725. ** will invoke sqlite3_os_end().
  1726. **
  1727. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1728. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1729. ** the library (perhaps it is unable to allocate a needed resource such
  1730. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1731. **
  1732. ** ^The sqlite3_initialize() routine is called internally by many other
  1733. ** SQLite interfaces so that an application usually does not need to
  1734. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1735. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1736. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1737. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1738. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1739. ** are omitted and the application must call sqlite3_initialize() directly
  1740. ** prior to using any other SQLite interface. For maximum portability,
  1741. ** it is recommended that applications always invoke sqlite3_initialize()
  1742. ** directly prior to using any other SQLite interface. Future releases
  1743. ** of SQLite may require this. In other words, the behavior exhibited
  1744. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1745. ** default behavior in some future release of SQLite.
  1746. **
  1747. ** The sqlite3_os_init() routine does operating-system specific
  1748. ** initialization of the SQLite library. The sqlite3_os_end()
  1749. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1750. ** performed by these routines include allocation or deallocation
  1751. ** of static resources, initialization of global variables,
  1752. ** setting up a default [sqlite3_vfs] module, or setting up
  1753. ** a default configuration using [sqlite3_config()].
  1754. **
  1755. ** The application should never invoke either sqlite3_os_init()
  1756. ** or sqlite3_os_end() directly. The application should only invoke
  1757. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1758. ** interface is called automatically by sqlite3_initialize() and
  1759. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1760. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1761. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1762. ** When [custom builds | built for other platforms]
  1763. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1764. ** option) the application must supply a suitable implementation for
  1765. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1766. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1767. ** must return [SQLITE_OK] on success and some other [error code] upon
  1768. ** failure.
  1769. */
  1770. SQLITE_API int sqlite3_initialize(void);
  1771. SQLITE_API int sqlite3_shutdown(void);
  1772. SQLITE_API int sqlite3_os_init(void);
  1773. SQLITE_API int sqlite3_os_end(void);
  1774. /*
  1775. ** CAPI3REF: Configuring The SQLite Library
  1776. **
  1777. ** The sqlite3_config() interface is used to make global configuration
  1778. ** changes to SQLite in order to tune SQLite to the specific needs of
  1779. ** the application. The default configuration is recommended for most
  1780. ** applications and so this routine is usually not necessary. It is
  1781. ** provided to support rare applications with unusual needs.
  1782. **
  1783. ** The sqlite3_config() interface is not threadsafe. The application
  1784. ** must insure that no other SQLite interfaces are invoked by other
  1785. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1786. ** may only be invoked prior to library initialization using
  1787. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1788. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1789. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1790. ** Note, however, that ^sqlite3_config() can be called as part of the
  1791. ** implementation of an application-defined [sqlite3_os_init()].
  1792. **
  1793. ** The first argument to sqlite3_config() is an integer
  1794. ** [configuration option] that determines
  1795. ** what property of SQLite is to be configured. Subsequent arguments
  1796. ** vary depending on the [configuration option]
  1797. ** in the first argument.
  1798. **
  1799. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1800. ** ^If the option is unknown or SQLite is unable to set the option
  1801. ** then this routine returns a non-zero [error code].
  1802. */
  1803. SQLITE_API int sqlite3_config(int, ...);
  1804. /*
  1805. ** CAPI3REF: Configure database connections
  1806. **
  1807. ** The sqlite3_db_config() interface is used to make configuration
  1808. ** changes to a [database connection]. The interface is similar to
  1809. ** [sqlite3_config()] except that the changes apply to a single
  1810. ** [database connection] (specified in the first argument).
  1811. **
  1812. ** The second argument to sqlite3_db_config(D,V,...) is the
  1813. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1814. ** that indicates what aspect of the [database connection] is being configured.
  1815. ** Subsequent arguments vary depending on the configuration verb.
  1816. **
  1817. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1818. ** the call is considered successful.
  1819. */
  1820. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1821. /*
  1822. ** CAPI3REF: Memory Allocation Routines
  1823. **
  1824. ** An instance of this object defines the interface between SQLite
  1825. ** and low-level memory allocation routines.
  1826. **
  1827. ** This object is used in only one place in the SQLite interface.
  1828. ** A pointer to an instance of this object is the argument to
  1829. ** [sqlite3_config()] when the configuration option is
  1830. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1831. ** By creating an instance of this object
  1832. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1833. ** during configuration, an application can specify an alternative
  1834. ** memory allocation subsystem for SQLite to use for all of its
  1835. ** dynamic memory needs.
  1836. **
  1837. ** Note that SQLite comes with several [built-in memory allocators]
  1838. ** that are perfectly adequate for the overwhelming majority of applications
  1839. ** and that this object is only useful to a tiny minority of applications
  1840. ** with specialized memory allocation requirements. This object is
  1841. ** also used during testing of SQLite in order to specify an alternative
  1842. ** memory allocator that simulates memory out-of-memory conditions in
  1843. ** order to verify that SQLite recovers gracefully from such
  1844. ** conditions.
  1845. **
  1846. ** The xMalloc, xRealloc, and xFree methods must work like the
  1847. ** malloc(), realloc() and free() functions from the standard C library.
  1848. ** ^SQLite guarantees that the second argument to
  1849. ** xRealloc is always a value returned by a prior call to xRoundup.
  1850. **
  1851. ** xSize should return the allocated size of a memory allocation
  1852. ** previously obtained from xMalloc or xRealloc. The allocated size
  1853. ** is always at least as big as the requested size but may be larger.
  1854. **
  1855. ** The xRoundup method returns what would be the allocated size of
  1856. ** a memory allocation given a particular requested size. Most memory
  1857. ** allocators round up memory allocations at least to the next multiple
  1858. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1859. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1860. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1861. ** that causes the corresponding memory allocation to fail.
  1862. **
  1863. ** The xInit method initializes the memory allocator. (For example,
  1864. ** it might allocate any require mutexes or initialize internal data
  1865. ** structures. The xShutdown method is invoked (indirectly) by
  1866. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1867. ** by xInit. The pAppData pointer is used as the only parameter to
  1868. ** xInit and xShutdown.
  1869. **
  1870. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1871. ** the xInit method, so the xInit method need not be threadsafe. The
  1872. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1873. ** not need to be threadsafe either. For all other methods, SQLite
  1874. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1875. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1876. ** it is by default) and so the methods are automatically serialized.
  1877. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1878. ** methods must be threadsafe or else make their own arrangements for
  1879. ** serialization.
  1880. **
  1881. ** SQLite will never invoke xInit() more than once without an intervening
  1882. ** call to xShutdown().
  1883. */
  1884. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1885. struct sqlite3_mem_methods {
  1886. void *(*xMalloc)(int); /* Memory allocation function */
  1887. void (*xFree)(void*); /* Free a prior allocation */
  1888. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1889. int (*xSize)(void*); /* Return the size of an allocation */
  1890. int (*xRoundup)(int); /* Round up request size to allocation size */
  1891. int (*xInit)(void*); /* Initialize the memory allocator */
  1892. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1893. void *pAppData; /* Argument to xInit() and xShutdown() */
  1894. };
  1895. /*
  1896. ** CAPI3REF: Configuration Options
  1897. ** KEYWORDS: {configuration option}
  1898. **
  1899. ** These constants are the available integer configuration options that
  1900. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1901. **
  1902. ** New configuration options may be added in future releases of SQLite.
  1903. ** Existing configuration options might be discontinued. Applications
  1904. ** should check the return code from [sqlite3_config()] to make sure that
  1905. ** the call worked. The [sqlite3_config()] interface will return a
  1906. ** non-zero [error code] if a discontinued or unsupported configuration option
  1907. ** is invoked.
  1908. **
  1909. ** <dl>
  1910. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1911. ** <dd>There are no arguments to this option. ^This option sets the
  1912. ** [threading mode] to Single-thread. In other words, it disables
  1913. ** all mutexing and puts SQLite into a mode where it can only be used
  1914. ** by a single thread. ^If SQLite is compiled with
  1915. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1916. ** it is not possible to change the [threading mode] from its default
  1917. ** value of Single-thread and so [sqlite3_config()] will return
  1918. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1919. ** configuration option.</dd>
  1920. **
  1921. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1922. ** <dd>There are no arguments to this option. ^This option sets the
  1923. ** [threading mode] to Multi-thread. In other words, it disables
  1924. ** mutexing on [database connection] and [prepared statement] objects.
  1925. ** The application is responsible for serializing access to
  1926. ** [database connections] and [prepared statements]. But other mutexes
  1927. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1928. ** environment as long as no two threads attempt to use the same
  1929. ** [database connection] at the same time. ^If SQLite is compiled with
  1930. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1931. ** it is not possible to set the Multi-thread [threading mode] and
  1932. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1933. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1934. **
  1935. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1936. ** <dd>There are no arguments to this option. ^This option sets the
  1937. ** [threading mode] to Serialized. In other words, this option enables
  1938. ** all mutexes including the recursive
  1939. ** mutexes on [database connection] and [prepared statement] objects.
  1940. ** In this mode (which is the default when SQLite is compiled with
  1941. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1942. ** to [database connections] and [prepared statements] so that the
  1943. ** application is free to use the same [database connection] or the
  1944. ** same [prepared statement] in different threads at the same time.
  1945. ** ^If SQLite is compiled with
  1946. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1947. ** it is not possible to set the Serialized [threading mode] and
  1948. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1949. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1950. **
  1951. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1952. ** <dd> ^(This option takes a single argument which is a pointer to an
  1953. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1954. ** alternative low-level memory allocation routines to be used in place of
  1955. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1956. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1957. ** before the [sqlite3_config()] call returns.</dd>
  1958. **
  1959. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1960. ** <dd> ^(This option takes a single argument which is a pointer to an
  1961. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1962. ** structure is filled with the currently defined memory allocation routines.)^
  1963. ** This option can be used to overload the default memory allocation
  1964. ** routines with a wrapper that simulations memory allocation failure or
  1965. ** tracks memory usage, for example. </dd>
  1966. **
  1967. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1968. ** <dd> ^This option takes single argument of type int, interpreted as a
  1969. ** boolean, which enables or disables the collection of memory allocation
  1970. ** statistics. ^(When memory allocation statistics are disabled, the
  1971. ** following SQLite interfaces become non-operational:
  1972. ** <ul>
  1973. ** <li> [sqlite3_memory_used()]
  1974. ** <li> [sqlite3_memory_highwater()]
  1975. ** <li> [sqlite3_soft_heap_limit64()]
  1976. ** <li> [sqlite3_status()]
  1977. ** </ul>)^
  1978. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1979. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1980. ** allocation statistics are disabled by default.
  1981. ** </dd>
  1982. **
  1983. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1984. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1985. ** scratch memory. There are three arguments: A pointer an 8-byte
  1986. ** aligned memory buffer from which the scratch allocations will be
  1987. ** drawn, the size of each scratch allocation (sz),
  1988. ** and the maximum number of scratch allocations (N). The sz
  1989. ** argument must be a multiple of 16.
  1990. ** The first argument must be a pointer to an 8-byte aligned buffer
  1991. ** of at least sz*N bytes of memory.
  1992. ** ^SQLite will use no more than two scratch buffers per thread. So
  1993. ** N should be set to twice the expected maximum number of threads.
  1994. ** ^SQLite will never require a scratch buffer that is more than 6
  1995. ** times the database page size. ^If SQLite needs needs additional
  1996. ** scratch memory beyond what is provided by this configuration option, then
  1997. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1998. **
  1999. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2000. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  2001. ** the database page cache with the default page cache implementation.
  2002. ** This configuration should not be used if an application-define page
  2003. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  2004. ** There are three arguments to this option: A pointer to 8-byte aligned
  2005. ** memory, the size of each page buffer (sz), and the number of pages (N).
  2006. ** The sz argument should be the size of the largest database page
  2007. ** (a power of two between 512 and 32768) plus a little extra for each
  2008. ** page header. ^The page header size is 20 to 40 bytes depending on
  2009. ** the host architecture. ^It is harmless, apart from the wasted memory,
  2010. ** to make sz a little too large. The first
  2011. ** argument should point to an allocation of at least sz*N bytes of memory.
  2012. ** ^SQLite will use the memory provided by the first argument to satisfy its
  2013. ** memory needs for the first N pages that it adds to cache. ^If additional
  2014. ** page cache memory is needed beyond what is provided by this option, then
  2015. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  2016. ** The pointer in the first argument must
  2017. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  2018. ** will be undefined.</dd>
  2019. **
  2020. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2021. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  2022. ** for all of its dynamic memory allocation needs beyond those provided
  2023. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  2024. ** There are three arguments: An 8-byte aligned pointer to the memory,
  2025. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2026. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2027. ** to using its default memory allocator (the system malloc() implementation),
  2028. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2029. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  2030. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  2031. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2032. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2033. ** boundary or subsequent behavior of SQLite will be undefined.
  2034. ** The minimum allocation size is capped at 2**12. Reasonable values
  2035. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2036. **
  2037. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2038. ** <dd> ^(This option takes a single argument which is a pointer to an
  2039. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  2040. ** alternative low-level mutex routines to be used in place
  2041. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  2042. ** content of the [sqlite3_mutex_methods] structure before the call to
  2043. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2044. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2045. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2046. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2047. ** return [SQLITE_ERROR].</dd>
  2048. **
  2049. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2050. ** <dd> ^(This option takes a single argument which is a pointer to an
  2051. ** instance of the [sqlite3_mutex_methods] structure. The
  2052. ** [sqlite3_mutex_methods]
  2053. ** structure is filled with the currently defined mutex routines.)^
  2054. ** This option can be used to overload the default mutex allocation
  2055. ** routines with a wrapper used to track mutex usage for performance
  2056. ** profiling or testing, for example. ^If SQLite is compiled with
  2057. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2058. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2059. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2060. ** return [SQLITE_ERROR].</dd>
  2061. **
  2062. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2063. ** <dd> ^(This option takes two arguments that determine the default
  2064. ** memory allocation for the lookaside memory allocator on each
  2065. ** [database connection]. The first argument is the
  2066. ** size of each lookaside buffer slot and the second is the number of
  2067. ** slots allocated to each database connection.)^ ^(This option sets the
  2068. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2069. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  2070. ** configuration on individual connections.)^ </dd>
  2071. **
  2072. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2073. ** <dd> ^(This option takes a single argument which is a pointer to
  2074. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  2075. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  2076. ** object and uses it for page cache memory allocations.</dd>
  2077. **
  2078. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2079. ** <dd> ^(This option takes a single argument which is a pointer to an
  2080. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  2081. ** page cache implementation into that object.)^ </dd>
  2082. **
  2083. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2084. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2085. ** global [error log].
  2086. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2087. ** function with a call signature of void(*)(void*,int,const char*),
  2088. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2089. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2090. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2091. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2092. ** passed through as the first parameter to the application-defined logger
  2093. ** function whenever that function is invoked. ^The second parameter to
  2094. ** the logger function is a copy of the first parameter to the corresponding
  2095. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2096. ** [extended result code]. ^The third parameter passed to the logger is
  2097. ** log message after formatting via [sqlite3_snprintf()].
  2098. ** The SQLite logging interface is not reentrant; the logger function
  2099. ** supplied by the application must not invoke any SQLite interface.
  2100. ** In a multi-threaded application, the application-defined logger
  2101. ** function must be threadsafe. </dd>
  2102. **
  2103. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2104. ** <dd> This option takes a single argument of type int. If non-zero, then
  2105. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  2106. ** is globally disabled. If URI handling is globally enabled, all filenames
  2107. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  2108. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2109. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2110. ** connection is opened. If it is globally disabled, filenames are
  2111. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2112. ** database connection is opened. By default, URI handling is globally
  2113. ** disabled. The default value may be changed by compiling with the
  2114. ** [SQLITE_USE_URI] symbol defined.
  2115. **
  2116. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2117. ** <dd> This option takes a single integer argument which is interpreted as
  2118. ** a boolean in order to enable or disable the use of covering indices for
  2119. ** full table scans in the query optimizer. The default setting is determined
  2120. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2121. ** if that compile-time option is omitted.
  2122. ** The ability to disable the use of covering indices for full table scans
  2123. ** is because some incorrectly coded legacy applications might malfunction
  2124. ** malfunction when the optimization is enabled. Providing the ability to
  2125. ** disable the optimization allows the older, buggy application code to work
  2126. ** without change even with newer versions of SQLite.
  2127. **
  2128. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2129. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2130. ** <dd> These options are obsolete and should not be used by new code.
  2131. ** They are retained for backwards compatibility but are now no-ops.
  2132. ** </dd>
  2133. **
  2134. ** [[SQLITE_CONFIG_SQLLOG]]
  2135. ** <dt>SQLITE_CONFIG_SQLLOG
  2136. ** <dd>This option is only available if sqlite is compiled with the
  2137. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2138. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2139. ** The second should be of type (void*). The callback is invoked by the library
  2140. ** in three separate circumstances, identified by the value passed as the
  2141. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2142. ** passed as the second argument has just been opened. The third argument
  2143. ** points to a buffer containing the name of the main database file. If the
  2144. ** fourth parameter is 1, then the SQL statement that the third parameter
  2145. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2146. ** the connection being passed as the second parameter is being closed. The
  2147. ** third parameter is passed NULL In this case. An example of using this
  2148. ** configuration option can be seen in the "test_sqllog.c" source file in
  2149. ** the canonical SQLite source tree.</dd>
  2150. **
  2151. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2152. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2153. ** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2154. ** that are the default mmap size limit (the default setting for
  2155. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2156. ** The default setting can be overridden by each database connection using
  2157. ** either the [PRAGMA mmap_size] command, or by using the
  2158. ** [SQLITE_FCNTL_MMAP_SIZE] file control. The maximum allowed mmap size
  2159. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  2160. ** exceed the compile-time maximum mmap size set by the
  2161. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.
  2162. ** If either argument to this option is negative, then that argument is
  2163. ** changed to its compile-time default.
  2164. ** </dl>
  2165. */
  2166. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2167. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2168. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2169. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2170. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2171. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  2172. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2173. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2174. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2175. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2176. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2177. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2178. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2179. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2180. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2181. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2182. #define SQLITE_CONFIG_URI 17 /* int */
  2183. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2184. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2185. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2186. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2187. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2188. /*
  2189. ** CAPI3REF: Database Connection Configuration Options
  2190. **
  2191. ** These constants are the available integer configuration options that
  2192. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2193. **
  2194. ** New configuration options may be added in future releases of SQLite.
  2195. ** Existing configuration options might be discontinued. Applications
  2196. ** should check the return code from [sqlite3_db_config()] to make sure that
  2197. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2198. ** non-zero [error code] if a discontinued or unsupported configuration option
  2199. ** is invoked.
  2200. **
  2201. ** <dl>
  2202. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2203. ** <dd> ^This option takes three additional arguments that determine the
  2204. ** [lookaside memory allocator] configuration for the [database connection].
  2205. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2206. ** pointer to a memory buffer to use for lookaside memory.
  2207. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2208. ** may be NULL in which case SQLite will allocate the
  2209. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2210. ** size of each lookaside buffer slot. ^The third argument is the number of
  2211. ** slots. The size of the buffer in the first argument must be greater than
  2212. ** or equal to the product of the second and third arguments. The buffer
  2213. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2214. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2215. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2216. ** configuration for a database connection can only be changed when that
  2217. ** connection is not currently using lookaside memory, or in other words
  2218. ** when the "current value" returned by
  2219. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2220. ** Any attempt to change the lookaside memory configuration when lookaside
  2221. ** memory is in use leaves the configuration unchanged and returns
  2222. ** [SQLITE_BUSY].)^</dd>
  2223. **
  2224. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2225. ** <dd> ^This option is used to enable or disable the enforcement of
  2226. ** [foreign key constraints]. There should be two additional arguments.
  2227. ** The first argument is an integer which is 0 to disable FK enforcement,
  2228. ** positive to enable FK enforcement or negative to leave FK enforcement
  2229. ** unchanged. The second parameter is a pointer to an integer into which
  2230. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2231. ** following this call. The second parameter may be a NULL pointer, in
  2232. ** which case the FK enforcement setting is not reported back. </dd>
  2233. **
  2234. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2235. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2236. ** There should be two additional arguments.
  2237. ** The first argument is an integer which is 0 to disable triggers,
  2238. ** positive to enable triggers or negative to leave the setting unchanged.
  2239. ** The second parameter is a pointer to an integer into which
  2240. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2241. ** following this call. The second parameter may be a NULL pointer, in
  2242. ** which case the trigger setting is not reported back. </dd>
  2243. **
  2244. ** </dl>
  2245. */
  2246. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2247. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2248. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2249. /*
  2250. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2251. **
  2252. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2253. ** [extended result codes] feature of SQLite. ^The extended result
  2254. ** codes are disabled by default for historical compatibility.
  2255. */
  2256. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  2257. /*
  2258. ** CAPI3REF: Last Insert Rowid
  2259. **
  2260. ** ^Each entry in an SQLite table has a unique 64-bit signed
  2261. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2262. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2263. ** names are not also used by explicitly declared columns. ^If
  2264. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2265. ** is another alias for the rowid.
  2266. **
  2267. ** ^This routine returns the [rowid] of the most recent
  2268. ** successful [INSERT] into the database from the [database connection]
  2269. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  2270. ** records the last insert rowid of both ordinary tables and [virtual tables].
  2271. ** ^If no successful [INSERT]s
  2272. ** have ever occurred on that database connection, zero is returned.
  2273. **
  2274. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2275. ** method, then this routine will return the [rowid] of the inserted
  2276. ** row as long as the trigger or virtual table method is running.
  2277. ** But once the trigger or virtual table method ends, the value returned
  2278. ** by this routine reverts to what it was before the trigger or virtual
  2279. ** table method began.)^
  2280. **
  2281. ** ^An [INSERT] that fails due to a constraint violation is not a
  2282. ** successful [INSERT] and does not change the value returned by this
  2283. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2284. ** and INSERT OR ABORT make no changes to the return value of this
  2285. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2286. ** encounters a constraint violation, it does not fail. The
  2287. ** INSERT continues to completion after deleting rows that caused
  2288. ** the constraint problem so INSERT OR REPLACE will always change
  2289. ** the return value of this interface.)^
  2290. **
  2291. ** ^For the purposes of this routine, an [INSERT] is considered to
  2292. ** be successful even if it is subsequently rolled back.
  2293. **
  2294. ** This function is accessible to SQL statements via the
  2295. ** [last_insert_rowid() SQL function].
  2296. **
  2297. ** If a separate thread performs a new [INSERT] on the same
  2298. ** database connection while the [sqlite3_last_insert_rowid()]
  2299. ** function is running and thus changes the last insert [rowid],
  2300. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2301. ** unpredictable and might not equal either the old or the new
  2302. ** last insert [rowid].
  2303. */
  2304. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2305. /*
  2306. ** CAPI3REF: Count The Number Of Rows Modified
  2307. **
  2308. ** ^This function returns the number of database rows that were changed
  2309. ** or inserted or deleted by the most recently completed SQL statement
  2310. ** on the [database connection] specified by the first parameter.
  2311. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  2312. ** or [DELETE] statement are counted. Auxiliary changes caused by
  2313. ** triggers or [foreign key actions] are not counted.)^ Use the
  2314. ** [sqlite3_total_changes()] function to find the total number of changes
  2315. ** including changes caused by triggers and foreign key actions.
  2316. **
  2317. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  2318. ** are not counted. Only real table changes are counted.
  2319. **
  2320. ** ^(A "row change" is a change to a single row of a single table
  2321. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  2322. ** are changed as side effects of [REPLACE] constraint resolution,
  2323. ** rollback, ABORT processing, [DROP TABLE], or by any other
  2324. ** mechanisms do not count as direct row changes.)^
  2325. **
  2326. ** A "trigger context" is a scope of execution that begins and
  2327. ** ends with the script of a [CREATE TRIGGER | trigger].
  2328. ** Most SQL statements are
  2329. ** evaluated outside of any trigger. This is the "top level"
  2330. ** trigger context. If a trigger fires from the top level, a
  2331. ** new trigger context is entered for the duration of that one
  2332. ** trigger. Subtriggers create subcontexts for their duration.
  2333. **
  2334. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  2335. ** not create a new trigger context.
  2336. **
  2337. ** ^This function returns the number of direct row changes in the
  2338. ** most recent INSERT, UPDATE, or DELETE statement within the same
  2339. ** trigger context.
  2340. **
  2341. ** ^Thus, when called from the top level, this function returns the
  2342. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  2343. ** that also occurred at the top level. ^(Within the body of a trigger,
  2344. ** the sqlite3_changes() interface can be called to find the number of
  2345. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  2346. ** statement within the body of the same trigger.
  2347. ** However, the number returned does not include changes
  2348. ** caused by subtriggers since those have their own context.)^
  2349. **
  2350. ** See also the [sqlite3_total_changes()] interface, the
  2351. ** [count_changes pragma], and the [changes() SQL function].
  2352. **
  2353. ** If a separate thread makes changes on the same database connection
  2354. ** while [sqlite3_changes()] is running then the value returned
  2355. ** is unpredictable and not meaningful.
  2356. */
  2357. SQLITE_API int sqlite3_changes(sqlite3*);
  2358. /*
  2359. ** CAPI3REF: Total Number Of Rows Modified
  2360. **
  2361. ** ^This function returns the number of row changes caused by [INSERT],
  2362. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2363. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2364. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2365. ** [foreign key actions]. However,
  2366. ** the count does not include changes used to implement [REPLACE] constraints,
  2367. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2368. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2369. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2370. ** are counted.)^
  2371. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2372. ** the statement that makes them is completed (when the statement handle
  2373. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2374. **
  2375. ** See also the [sqlite3_changes()] interface, the
  2376. ** [count_changes pragma], and the [total_changes() SQL function].
  2377. **
  2378. ** If a separate thread makes changes on the same database connection
  2379. ** while [sqlite3_total_changes()] is running then the value
  2380. ** returned is unpredictable and not meaningful.
  2381. */
  2382. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2383. /*
  2384. ** CAPI3REF: Interrupt A Long-Running Query
  2385. **
  2386. ** ^This function causes any pending database operation to abort and
  2387. ** return at its earliest opportunity. This routine is typically
  2388. ** called in response to a user action such as pressing "Cancel"
  2389. ** or Ctrl-C where the user wants a long query operation to halt
  2390. ** immediately.
  2391. **
  2392. ** ^It is safe to call this routine from a thread different from the
  2393. ** thread that is currently running the database operation. But it
  2394. ** is not safe to call this routine with a [database connection] that
  2395. ** is closed or might close before sqlite3_interrupt() returns.
  2396. **
  2397. ** ^If an SQL operation is very nearly finished at the time when
  2398. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2399. ** to be interrupted and might continue to completion.
  2400. **
  2401. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2402. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2403. ** that is inside an explicit transaction, then the entire transaction
  2404. ** will be rolled back automatically.
  2405. **
  2406. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2407. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2408. ** that are started after the sqlite3_interrupt() call and before the
  2409. ** running statements reaches zero are interrupted as if they had been
  2410. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2411. ** that are started after the running statement count reaches zero are
  2412. ** not effected by the sqlite3_interrupt().
  2413. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2414. ** SQL statements is a no-op and has no effect on SQL statements
  2415. ** that are started after the sqlite3_interrupt() call returns.
  2416. **
  2417. ** If the database connection closes while [sqlite3_interrupt()]
  2418. ** is running then bad things will likely happen.
  2419. */
  2420. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2421. /*
  2422. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2423. **
  2424. ** These routines are useful during command-line input to determine if the
  2425. ** currently entered text seems to form a complete SQL statement or
  2426. ** if additional input is needed before sending the text into
  2427. ** SQLite for parsing. ^These routines return 1 if the input string
  2428. ** appears to be a complete SQL statement. ^A statement is judged to be
  2429. ** complete if it ends with a semicolon token and is not a prefix of a
  2430. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2431. ** string literals or quoted identifier names or comments are not
  2432. ** independent tokens (they are part of the token in which they are
  2433. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2434. ** and comments that follow the final semicolon are ignored.
  2435. **
  2436. ** ^These routines return 0 if the statement is incomplete. ^If a
  2437. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2438. **
  2439. ** ^These routines do not parse the SQL statements thus
  2440. ** will not detect syntactically incorrect SQL.
  2441. **
  2442. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2443. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2444. ** automatically by sqlite3_complete16(). If that initialization fails,
  2445. ** then the return value from sqlite3_complete16() will be non-zero
  2446. ** regardless of whether or not the input SQL is complete.)^
  2447. **
  2448. ** The input to [sqlite3_complete()] must be a zero-terminated
  2449. ** UTF-8 string.
  2450. **
  2451. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2452. ** UTF-16 string in native byte order.
  2453. */
  2454. SQLITE_API int sqlite3_complete(const char *sql);
  2455. SQLITE_API int sqlite3_complete16(const void *sql);
  2456. /*
  2457. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2458. **
  2459. ** ^This routine sets a callback function that might be invoked whenever
  2460. ** an attempt is made to open a database table that another thread
  2461. ** or process has locked.
  2462. **
  2463. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2464. ** is returned immediately upon encountering the lock. ^If the busy callback
  2465. ** is not NULL, then the callback might be invoked with two arguments.
  2466. **
  2467. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2468. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2469. ** the busy handler callback is the number of times that the busy handler has
  2470. ** been invoked for this locking event. ^If the
  2471. ** busy callback returns 0, then no additional attempts are made to
  2472. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2473. ** ^If the callback returns non-zero, then another attempt
  2474. ** is made to open the database for reading and the cycle repeats.
  2475. **
  2476. ** The presence of a busy handler does not guarantee that it will be invoked
  2477. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2478. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2479. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2480. ** Consider a scenario where one process is holding a read lock that
  2481. ** it is trying to promote to a reserved lock and
  2482. ** a second process is holding a reserved lock that it is trying
  2483. ** to promote to an exclusive lock. The first process cannot proceed
  2484. ** because it is blocked by the second and the second process cannot
  2485. ** proceed because it is blocked by the first. If both processes
  2486. ** invoke the busy handlers, neither will make any progress. Therefore,
  2487. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2488. ** will induce the first process to release its read lock and allow
  2489. ** the second process to proceed.
  2490. **
  2491. ** ^The default busy callback is NULL.
  2492. **
  2493. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2494. ** when SQLite is in the middle of a large transaction where all the
  2495. ** changes will not fit into the in-memory cache. SQLite will
  2496. ** already hold a RESERVED lock on the database file, but it needs
  2497. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2498. ** pages into the database file without harm to concurrent
  2499. ** readers. ^If it is unable to promote the lock, then the in-memory
  2500. ** cache will be left in an inconsistent state and so the error
  2501. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2502. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2503. ** forces an automatic rollback of the changes. See the
  2504. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2505. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2506. ** this is important.
  2507. **
  2508. ** ^(There can only be a single busy handler defined for each
  2509. ** [database connection]. Setting a new busy handler clears any
  2510. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2511. ** will also set or clear the busy handler.
  2512. **
  2513. ** The busy callback should not take any actions which modify the
  2514. ** database connection that invoked the busy handler. Any such actions
  2515. ** result in undefined behavior.
  2516. **
  2517. ** A busy handler must not close the database connection
  2518. ** or [prepared statement] that invoked the busy handler.
  2519. */
  2520. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2521. /*
  2522. ** CAPI3REF: Set A Busy Timeout
  2523. **
  2524. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2525. ** for a specified amount of time when a table is locked. ^The handler
  2526. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2527. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2528. ** the handler returns 0 which causes [sqlite3_step()] to return
  2529. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2530. **
  2531. ** ^Calling this routine with an argument less than or equal to zero
  2532. ** turns off all busy handlers.
  2533. **
  2534. ** ^(There can only be a single busy handler for a particular
  2535. ** [database connection] any any given moment. If another busy handler
  2536. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2537. ** this routine, that other busy handler is cleared.)^
  2538. */
  2539. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2540. /*
  2541. ** CAPI3REF: Convenience Routines For Running Queries
  2542. **
  2543. ** This is a legacy interface that is preserved for backwards compatibility.
  2544. ** Use of this interface is not recommended.
  2545. **
  2546. ** Definition: A <b>result table</b> is memory data structure created by the
  2547. ** [sqlite3_get_table()] interface. A result table records the
  2548. ** complete query results from one or more queries.
  2549. **
  2550. ** The table conceptually has a number of rows and columns. But
  2551. ** these numbers are not part of the result table itself. These
  2552. ** numbers are obtained separately. Let N be the number of rows
  2553. ** and M be the number of columns.
  2554. **
  2555. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2556. ** There are (N+1)*M elements in the array. The first M pointers point
  2557. ** to zero-terminated strings that contain the names of the columns.
  2558. ** The remaining entries all point to query results. NULL values result
  2559. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2560. ** string representation as returned by [sqlite3_column_text()].
  2561. **
  2562. ** A result table might consist of one or more memory allocations.
  2563. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2564. ** A result table should be deallocated using [sqlite3_free_table()].
  2565. **
  2566. ** ^(As an example of the result table format, suppose a query result
  2567. ** is as follows:
  2568. **
  2569. ** <blockquote><pre>
  2570. ** Name | Age
  2571. ** -----------------------
  2572. ** Alice | 43
  2573. ** Bob | 28
  2574. ** Cindy | 21
  2575. ** </pre></blockquote>
  2576. **
  2577. ** There are two column (M==2) and three rows (N==3). Thus the
  2578. ** result table has 8 entries. Suppose the result table is stored
  2579. ** in an array names azResult. Then azResult holds this content:
  2580. **
  2581. ** <blockquote><pre>
  2582. ** azResult&#91;0] = "Name";
  2583. ** azResult&#91;1] = "Age";
  2584. ** azResult&#91;2] = "Alice";
  2585. ** azResult&#91;3] = "43";
  2586. ** azResult&#91;4] = "Bob";
  2587. ** azResult&#91;5] = "28";
  2588. ** azResult&#91;6] = "Cindy";
  2589. ** azResult&#91;7] = "21";
  2590. ** </pre></blockquote>)^
  2591. **
  2592. ** ^The sqlite3_get_table() function evaluates one or more
  2593. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2594. ** string of its 2nd parameter and returns a result table to the
  2595. ** pointer given in its 3rd parameter.
  2596. **
  2597. ** After the application has finished with the result from sqlite3_get_table(),
  2598. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2599. ** release the memory that was malloced. Because of the way the
  2600. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2601. ** function must not try to call [sqlite3_free()] directly. Only
  2602. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2603. **
  2604. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2605. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2606. ** to any internal data structures of SQLite. It uses only the public
  2607. ** interface defined here. As a consequence, errors that occur in the
  2608. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2609. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2610. ** [sqlite3_errmsg()].
  2611. */
  2612. SQLITE_API int sqlite3_get_table(
  2613. sqlite3 *db, /* An open database */
  2614. const char *zSql, /* SQL to be evaluated */
  2615. char ***pazResult, /* Results of the query */
  2616. int *pnRow, /* Number of result rows written here */
  2617. int *pnColumn, /* Number of result columns written here */
  2618. char **pzErrmsg /* Error msg written here */
  2619. );
  2620. SQLITE_API void sqlite3_free_table(char **result);
  2621. /*
  2622. ** CAPI3REF: Formatted String Printing Functions
  2623. **
  2624. ** These routines are work-alikes of the "printf()" family of functions
  2625. ** from the standard C library.
  2626. **
  2627. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2628. ** results into memory obtained from [sqlite3_malloc()].
  2629. ** The strings returned by these two routines should be
  2630. ** released by [sqlite3_free()]. ^Both routines return a
  2631. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2632. ** memory to hold the resulting string.
  2633. **
  2634. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2635. ** the standard C library. The result is written into the
  2636. ** buffer supplied as the second parameter whose size is given by
  2637. ** the first parameter. Note that the order of the
  2638. ** first two parameters is reversed from snprintf().)^ This is an
  2639. ** historical accident that cannot be fixed without breaking
  2640. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2641. ** returns a pointer to its buffer instead of the number of
  2642. ** characters actually written into the buffer.)^ We admit that
  2643. ** the number of characters written would be a more useful return
  2644. ** value but we cannot change the implementation of sqlite3_snprintf()
  2645. ** now without breaking compatibility.
  2646. **
  2647. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2648. ** guarantees that the buffer is always zero-terminated. ^The first
  2649. ** parameter "n" is the total size of the buffer, including space for
  2650. ** the zero terminator. So the longest string that can be completely
  2651. ** written will be n-1 characters.
  2652. **
  2653. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2654. **
  2655. ** These routines all implement some additional formatting
  2656. ** options that are useful for constructing SQL statements.
  2657. ** All of the usual printf() formatting options apply. In addition, there
  2658. ** is are "%q", "%Q", and "%z" options.
  2659. **
  2660. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2661. ** string from the argument list. But %q also doubles every '\'' character.
  2662. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2663. ** character it escapes that character and allows it to be inserted into
  2664. ** the string.
  2665. **
  2666. ** For example, assume the string variable zText contains text as follows:
  2667. **
  2668. ** <blockquote><pre>
  2669. ** char *zText = "It's a happy day!";
  2670. ** </pre></blockquote>
  2671. **
  2672. ** One can use this text in an SQL statement as follows:
  2673. **
  2674. ** <blockquote><pre>
  2675. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2676. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2677. ** sqlite3_free(zSQL);
  2678. ** </pre></blockquote>
  2679. **
  2680. ** Because the %q format string is used, the '\'' character in zText
  2681. ** is escaped and the SQL generated is as follows:
  2682. **
  2683. ** <blockquote><pre>
  2684. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2685. ** </pre></blockquote>
  2686. **
  2687. ** This is correct. Had we used %s instead of %q, the generated SQL
  2688. ** would have looked like this:
  2689. **
  2690. ** <blockquote><pre>
  2691. ** INSERT INTO table1 VALUES('It's a happy day!');
  2692. ** </pre></blockquote>
  2693. **
  2694. ** This second example is an SQL syntax error. As a general rule you should
  2695. ** always use %q instead of %s when inserting text into a string literal.
  2696. **
  2697. ** ^(The %Q option works like %q except it also adds single quotes around
  2698. ** the outside of the total string. Additionally, if the parameter in the
  2699. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2700. ** single quotes).)^ So, for example, one could say:
  2701. **
  2702. ** <blockquote><pre>
  2703. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2704. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2705. ** sqlite3_free(zSQL);
  2706. ** </pre></blockquote>
  2707. **
  2708. ** The code above will render a correct SQL statement in the zSQL
  2709. ** variable even if the zText variable is a NULL pointer.
  2710. **
  2711. ** ^(The "%z" formatting option works like "%s" but with the
  2712. ** addition that after the string has been read and copied into
  2713. ** the result, [sqlite3_free()] is called on the input string.)^
  2714. */
  2715. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2716. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2717. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2718. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2719. /*
  2720. ** CAPI3REF: Memory Allocation Subsystem
  2721. **
  2722. ** The SQLite core uses these three routines for all of its own
  2723. ** internal memory allocation needs. "Core" in the previous sentence
  2724. ** does not include operating-system specific VFS implementation. The
  2725. ** Windows VFS uses native malloc() and free() for some operations.
  2726. **
  2727. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2728. ** of memory at least N bytes in length, where N is the parameter.
  2729. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2730. ** memory, it returns a NULL pointer. ^If the parameter N to
  2731. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2732. ** a NULL pointer.
  2733. **
  2734. ** ^Calling sqlite3_free() with a pointer previously returned
  2735. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2736. ** that it might be reused. ^The sqlite3_free() routine is
  2737. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2738. ** to sqlite3_free() is harmless. After being freed, memory
  2739. ** should neither be read nor written. Even reading previously freed
  2740. ** memory might result in a segmentation fault or other severe error.
  2741. ** Memory corruption, a segmentation fault, or other severe error
  2742. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2743. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2744. **
  2745. ** ^(The sqlite3_realloc() interface attempts to resize a
  2746. ** prior memory allocation to be at least N bytes, where N is the
  2747. ** second parameter. The memory allocation to be resized is the first
  2748. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2749. ** is a NULL pointer then its behavior is identical to calling
  2750. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2751. ** ^If the second parameter to sqlite3_realloc() is zero or
  2752. ** negative then the behavior is exactly the same as calling
  2753. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2754. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2755. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2756. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2757. ** of the prior allocation are copied into the beginning of buffer returned
  2758. ** by sqlite3_realloc() and the prior allocation is freed.
  2759. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2760. ** is not freed.
  2761. **
  2762. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2763. ** is always aligned to at least an 8 byte boundary, or to a
  2764. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2765. ** option is used.
  2766. **
  2767. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2768. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2769. ** implementation of these routines to be omitted. That capability
  2770. ** is no longer provided. Only built-in memory allocators can be used.
  2771. **
  2772. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2773. ** the system malloc() and free() directly when converting
  2774. ** filenames between the UTF-8 encoding used by SQLite
  2775. ** and whatever filename encoding is used by the particular Windows
  2776. ** installation. Memory allocation errors were detected, but
  2777. ** they were reported back as [SQLITE_CANTOPEN] or
  2778. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2779. **
  2780. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2781. ** must be either NULL or else pointers obtained from a prior
  2782. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2783. ** not yet been released.
  2784. **
  2785. ** The application must not read or write any part of
  2786. ** a block of memory after it has been released using
  2787. ** [sqlite3_free()] or [sqlite3_realloc()].
  2788. */
  2789. SQLITE_API void *sqlite3_malloc(int);
  2790. SQLITE_API void *sqlite3_realloc(void*, int);
  2791. SQLITE_API void sqlite3_free(void*);
  2792. /*
  2793. ** CAPI3REF: Memory Allocator Statistics
  2794. **
  2795. ** SQLite provides these two interfaces for reporting on the status
  2796. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2797. ** routines, which form the built-in memory allocation subsystem.
  2798. **
  2799. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2800. ** of memory currently outstanding (malloced but not freed).
  2801. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2802. ** value of [sqlite3_memory_used()] since the high-water mark
  2803. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2804. ** [sqlite3_memory_highwater()] include any overhead
  2805. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2806. ** but not overhead added by the any underlying system library
  2807. ** routines that [sqlite3_malloc()] may call.
  2808. **
  2809. ** ^The memory high-water mark is reset to the current value of
  2810. ** [sqlite3_memory_used()] if and only if the parameter to
  2811. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2812. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2813. ** prior to the reset.
  2814. */
  2815. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2816. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2817. /*
  2818. ** CAPI3REF: Pseudo-Random Number Generator
  2819. **
  2820. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2821. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2822. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2823. ** the build-in random() and randomblob() SQL functions. This interface allows
  2824. ** applications to access the same PRNG for other purposes.
  2825. **
  2826. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2827. **
  2828. ** ^The first time this routine is invoked (either internally or by
  2829. ** the application) the PRNG is seeded using randomness obtained
  2830. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2831. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2832. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2833. ** method.
  2834. */
  2835. SQLITE_API void sqlite3_randomness(int N, void *P);
  2836. /*
  2837. ** CAPI3REF: Compile-Time Authorization Callbacks
  2838. **
  2839. ** ^This routine registers an authorizer callback with a particular
  2840. ** [database connection], supplied in the first argument.
  2841. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2842. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2843. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2844. ** points during the compilation process, as logic is being created
  2845. ** to perform various actions, the authorizer callback is invoked to
  2846. ** see if those actions are allowed. ^The authorizer callback should
  2847. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2848. ** specific action but allow the SQL statement to continue to be
  2849. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2850. ** rejected with an error. ^If the authorizer callback returns
  2851. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2852. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2853. ** the authorizer will fail with an error message.
  2854. **
  2855. ** When the callback returns [SQLITE_OK], that means the operation
  2856. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2857. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2858. ** authorizer will fail with an error message explaining that
  2859. ** access is denied.
  2860. **
  2861. ** ^The first parameter to the authorizer callback is a copy of the third
  2862. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2863. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2864. ** the particular action to be authorized. ^The third through sixth parameters
  2865. ** to the callback are zero-terminated strings that contain additional
  2866. ** details about the action to be authorized.
  2867. **
  2868. ** ^If the action code is [SQLITE_READ]
  2869. ** and the callback returns [SQLITE_IGNORE] then the
  2870. ** [prepared statement] statement is constructed to substitute
  2871. ** a NULL value in place of the table column that would have
  2872. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2873. ** return can be used to deny an untrusted user access to individual
  2874. ** columns of a table.
  2875. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2876. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2877. ** [truncate optimization] is disabled and all rows are deleted individually.
  2878. **
  2879. ** An authorizer is used when [sqlite3_prepare | preparing]
  2880. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2881. ** do not try to access data they are not allowed to see, or that they do not
  2882. ** try to execute malicious statements that damage the database. For
  2883. ** example, an application may allow a user to enter arbitrary
  2884. ** SQL queries for evaluation by a database. But the application does
  2885. ** not want the user to be able to make arbitrary changes to the
  2886. ** database. An authorizer could then be put in place while the
  2887. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2888. ** disallows everything except [SELECT] statements.
  2889. **
  2890. ** Applications that need to process SQL from untrusted sources
  2891. ** might also consider lowering resource limits using [sqlite3_limit()]
  2892. ** and limiting database size using the [max_page_count] [PRAGMA]
  2893. ** in addition to using an authorizer.
  2894. **
  2895. ** ^(Only a single authorizer can be in place on a database connection
  2896. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2897. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2898. ** The authorizer is disabled by default.
  2899. **
  2900. ** The authorizer callback must not do anything that will modify
  2901. ** the database connection that invoked the authorizer callback.
  2902. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2903. ** database connections for the meaning of "modify" in this paragraph.
  2904. **
  2905. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2906. ** statement might be re-prepared during [sqlite3_step()] due to a
  2907. ** schema change. Hence, the application should ensure that the
  2908. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2909. **
  2910. ** ^Note that the authorizer callback is invoked only during
  2911. ** [sqlite3_prepare()] or its variants. Authorization is not
  2912. ** performed during statement evaluation in [sqlite3_step()], unless
  2913. ** as stated in the previous paragraph, sqlite3_step() invokes
  2914. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2915. */
  2916. SQLITE_API int sqlite3_set_authorizer(
  2917. sqlite3*,
  2918. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2919. void *pUserData
  2920. );
  2921. /*
  2922. ** CAPI3REF: Authorizer Return Codes
  2923. **
  2924. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2925. ** return either [SQLITE_OK] or one of these two constants in order
  2926. ** to signal SQLite whether or not the action is permitted. See the
  2927. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2928. ** information.
  2929. **
  2930. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2931. ** from the [sqlite3_vtab_on_conflict()] interface.
  2932. */
  2933. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2934. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2935. /*
  2936. ** CAPI3REF: Authorizer Action Codes
  2937. **
  2938. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2939. ** that is invoked to authorize certain SQL statement actions. The
  2940. ** second parameter to the callback is an integer code that specifies
  2941. ** what action is being authorized. These are the integer action codes that
  2942. ** the authorizer callback may be passed.
  2943. **
  2944. ** These action code values signify what kind of operation is to be
  2945. ** authorized. The 3rd and 4th parameters to the authorization
  2946. ** callback function will be parameters or NULL depending on which of these
  2947. ** codes is used as the second parameter. ^(The 5th parameter to the
  2948. ** authorizer callback is the name of the database ("main", "temp",
  2949. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2950. ** is the name of the inner-most trigger or view that is responsible for
  2951. ** the access attempt or NULL if this access attempt is directly from
  2952. ** top-level SQL code.
  2953. */
  2954. /******************************************* 3rd ************ 4th ***********/
  2955. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2956. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2957. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2958. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2959. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2960. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2961. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2962. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2963. #define SQLITE_DELETE 9 /* Table Name NULL */
  2964. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2965. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2966. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2967. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2968. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2969. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2970. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2971. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2972. #define SQLITE_INSERT 18 /* Table Name NULL */
  2973. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2974. #define SQLITE_READ 20 /* Table Name Column Name */
  2975. #define SQLITE_SELECT 21 /* NULL NULL */
  2976. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2977. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2978. #define SQLITE_ATTACH 24 /* Filename NULL */
  2979. #define SQLITE_DETACH 25 /* Database Name NULL */
  2980. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2981. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2982. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2983. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2984. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2985. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2986. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2987. #define SQLITE_COPY 0 /* No longer used */
  2988. /*
  2989. ** CAPI3REF: Tracing And Profiling Functions
  2990. **
  2991. ** These routines register callback functions that can be used for
  2992. ** tracing and profiling the execution of SQL statements.
  2993. **
  2994. ** ^The callback function registered by sqlite3_trace() is invoked at
  2995. ** various times when an SQL statement is being run by [sqlite3_step()].
  2996. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2997. ** SQL statement text as the statement first begins executing.
  2998. ** ^(Additional sqlite3_trace() callbacks might occur
  2999. ** as each triggered subprogram is entered. The callbacks for triggers
  3000. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3001. **
  3002. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3003. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3004. **
  3005. ** ^The callback function registered by sqlite3_profile() is invoked
  3006. ** as each SQL statement finishes. ^The profile callback contains
  3007. ** the original statement text and an estimate of wall-clock time
  3008. ** of how long that statement took to run. ^The profile callback
  3009. ** time is in units of nanoseconds, however the current implementation
  3010. ** is only capable of millisecond resolution so the six least significant
  3011. ** digits in the time are meaningless. Future versions of SQLite
  3012. ** might provide greater resolution on the profiler callback. The
  3013. ** sqlite3_profile() function is considered experimental and is
  3014. ** subject to change in future versions of SQLite.
  3015. */
  3016. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  3017. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  3018. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3019. /*
  3020. ** CAPI3REF: Query Progress Callbacks
  3021. **
  3022. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3023. ** function X to be invoked periodically during long running calls to
  3024. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3025. ** database connection D. An example use for this
  3026. ** interface is to keep a GUI updated during a large query.
  3027. **
  3028. ** ^The parameter P is passed through as the only parameter to the
  3029. ** callback function X. ^The parameter N is the number of
  3030. ** [virtual machine instructions] that are evaluated between successive
  3031. ** invocations of the callback X.
  3032. **
  3033. ** ^Only a single progress handler may be defined at one time per
  3034. ** [database connection]; setting a new progress handler cancels the
  3035. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3036. ** ^The progress handler is also disabled by setting N to a value less
  3037. ** than 1.
  3038. **
  3039. ** ^If the progress callback returns non-zero, the operation is
  3040. ** interrupted. This feature can be used to implement a
  3041. ** "Cancel" button on a GUI progress dialog box.
  3042. **
  3043. ** The progress handler callback must not do anything that will modify
  3044. ** the database connection that invoked the progress handler.
  3045. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3046. ** database connections for the meaning of "modify" in this paragraph.
  3047. **
  3048. */
  3049. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  3050. /*
  3051. ** CAPI3REF: Opening A New Database Connection
  3052. **
  3053. ** ^These routines open an SQLite database file as specified by the
  3054. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  3055. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  3056. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  3057. ** returned in *ppDb, even if an error occurs. The only exception is that
  3058. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  3059. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  3060. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  3061. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  3062. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  3063. ** an English language description of the error following a failure of any
  3064. ** of the sqlite3_open() routines.
  3065. **
  3066. ** ^The default encoding for the database will be UTF-8 if
  3067. ** sqlite3_open() or sqlite3_open_v2() is called and
  3068. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  3069. **
  3070. ** Whether or not an error occurs when it is opened, resources
  3071. ** associated with the [database connection] handle should be released by
  3072. ** passing it to [sqlite3_close()] when it is no longer required.
  3073. **
  3074. ** The sqlite3_open_v2() interface works like sqlite3_open()
  3075. ** except that it accepts two additional parameters for additional control
  3076. ** over the new database connection. ^(The flags parameter to
  3077. ** sqlite3_open_v2() can take one of
  3078. ** the following three values, optionally combined with the
  3079. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  3080. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  3081. **
  3082. ** <dl>
  3083. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  3084. ** <dd>The database is opened in read-only mode. If the database does not
  3085. ** already exist, an error is returned.</dd>)^
  3086. **
  3087. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  3088. ** <dd>The database is opened for reading and writing if possible, or reading
  3089. ** only if the file is write protected by the operating system. In either
  3090. ** case the database must already exist, otherwise an error is returned.</dd>)^
  3091. **
  3092. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  3093. ** <dd>The database is opened for reading and writing, and is created if
  3094. ** it does not already exist. This is the behavior that is always used for
  3095. ** sqlite3_open() and sqlite3_open16().</dd>)^
  3096. ** </dl>
  3097. **
  3098. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  3099. ** combinations shown above optionally combined with other
  3100. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  3101. ** then the behavior is undefined.
  3102. **
  3103. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  3104. ** opens in the multi-thread [threading mode] as long as the single-thread
  3105. ** mode has not been set at compile-time or start-time. ^If the
  3106. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  3107. ** in the serialized [threading mode] unless single-thread was
  3108. ** previously selected at compile-time or start-time.
  3109. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  3110. ** eligible to use [shared cache mode], regardless of whether or not shared
  3111. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  3112. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  3113. ** participate in [shared cache mode] even if it is enabled.
  3114. **
  3115. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  3116. ** [sqlite3_vfs] object that defines the operating system interface that
  3117. ** the new database connection should use. ^If the fourth parameter is
  3118. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3119. **
  3120. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  3121. ** is created for the connection. ^This in-memory database will vanish when
  3122. ** the database connection is closed. Future versions of SQLite might
  3123. ** make use of additional special filenames that begin with the ":" character.
  3124. ** It is recommended that when a database filename actually does begin with
  3125. ** a ":" character you should prefix the filename with a pathname such as
  3126. ** "./" to avoid ambiguity.
  3127. **
  3128. ** ^If the filename is an empty string, then a private, temporary
  3129. ** on-disk database will be created. ^This private database will be
  3130. ** automatically deleted as soon as the database connection is closed.
  3131. **
  3132. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  3133. **
  3134. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3135. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3136. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3137. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3138. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3139. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3140. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3141. ** by default, but future releases of SQLite might enable URI filename
  3142. ** interpretation by default. See "[URI filenames]" for additional
  3143. ** information.
  3144. **
  3145. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3146. ** authority, then it must be either an empty string or the string
  3147. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3148. ** error is returned to the caller. ^The fragment component of a URI, if
  3149. ** present, is ignored.
  3150. **
  3151. ** ^SQLite uses the path component of the URI as the name of the disk file
  3152. ** which contains the database. ^If the path begins with a '/' character,
  3153. ** then it is interpreted as an absolute path. ^If the path does not begin
  3154. ** with a '/' (meaning that the authority section is omitted from the URI)
  3155. ** then the path is interpreted as a relative path.
  3156. ** ^On windows, the first component of an absolute path
  3157. ** is a drive specification (e.g. "C:").
  3158. **
  3159. ** [[core URI query parameters]]
  3160. ** The query component of a URI may contain parameters that are interpreted
  3161. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3162. ** SQLite interprets the following three query parameters:
  3163. **
  3164. ** <ul>
  3165. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3166. ** a VFS object that provides the operating system interface that should
  3167. ** be used to access the database file on disk. ^If this option is set to
  3168. ** an empty string the default VFS object is used. ^Specifying an unknown
  3169. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3170. ** present, then the VFS specified by the option takes precedence over
  3171. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3172. **
  3173. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3174. ** "rwc", or "memory". Attempting to set it to any other value is
  3175. ** an error)^.
  3176. ** ^If "ro" is specified, then the database is opened for read-only
  3177. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3178. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3179. ** "rw", then the database is opened for read-write (but not create)
  3180. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3181. ** been set. ^Value "rwc" is equivalent to setting both
  3182. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3183. ** set to "memory" then a pure [in-memory database] that never reads
  3184. ** or writes from disk is used. ^It is an error to specify a value for
  3185. ** the mode parameter that is less restrictive than that specified by
  3186. ** the flags passed in the third parameter to sqlite3_open_v2().
  3187. **
  3188. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3189. ** "private". ^Setting it to "shared" is equivalent to setting the
  3190. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3191. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3192. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3193. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3194. ** a URI filename, its value overrides any behavior requested by setting
  3195. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3196. ** </ul>
  3197. **
  3198. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3199. ** error. Future versions of SQLite might understand additional query
  3200. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3201. ** additional information.
  3202. **
  3203. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3204. **
  3205. ** <table border="1" align=center cellpadding=5>
  3206. ** <tr><th> URI filenames <th> Results
  3207. ** <tr><td> file:data.db <td>
  3208. ** Open the file "data.db" in the current directory.
  3209. ** <tr><td> file:/home/fred/data.db<br>
  3210. ** file:///home/fred/data.db <br>
  3211. ** file://localhost/home/fred/data.db <br> <td>
  3212. ** Open the database file "/home/fred/data.db".
  3213. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3214. ** An error. "darkstar" is not a recognized authority.
  3215. ** <tr><td style="white-space:nowrap">
  3216. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3217. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3218. ** C:. Note that the %20 escaping in this example is not strictly
  3219. ** necessary - space characters can be used literally
  3220. ** in URI filenames.
  3221. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3222. ** Open file "data.db" in the current directory for read-only access.
  3223. ** Regardless of whether or not shared-cache mode is enabled by
  3224. ** default, use a private cache.
  3225. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  3226. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  3227. ** <tr><td> file:data.db?mode=readonly <td>
  3228. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3229. ** </table>
  3230. **
  3231. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3232. ** query components of a URI. A hexadecimal escape sequence consists of a
  3233. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3234. ** specifying an octet value. ^Before the path or query components of a
  3235. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3236. ** hexadecimal escape sequences replaced by a single byte containing the
  3237. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3238. ** the results are undefined.
  3239. **
  3240. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3241. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3242. ** codepage is currently defined. Filenames containing international
  3243. ** characters must be converted to UTF-8 prior to passing them into
  3244. ** sqlite3_open() or sqlite3_open_v2().
  3245. **
  3246. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3247. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3248. ** features that require the use of temporary files may fail.
  3249. **
  3250. ** See also: [sqlite3_temp_directory]
  3251. */
  3252. SQLITE_API int sqlite3_open(
  3253. const char *filename, /* Database filename (UTF-8) */
  3254. sqlite3 **ppDb /* OUT: SQLite db handle */
  3255. );
  3256. SQLITE_API int sqlite3_open16(
  3257. const void *filename, /* Database filename (UTF-16) */
  3258. sqlite3 **ppDb /* OUT: SQLite db handle */
  3259. );
  3260. SQLITE_API int sqlite3_open_v2(
  3261. const char *filename, /* Database filename (UTF-8) */
  3262. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3263. int flags, /* Flags */
  3264. const char *zVfs /* Name of VFS module to use */
  3265. );
  3266. /*
  3267. ** CAPI3REF: Obtain Values For URI Parameters
  3268. **
  3269. ** These are utility routines, useful to VFS implementations, that check
  3270. ** to see if a database file was a URI that contained a specific query
  3271. ** parameter, and if so obtains the value of that query parameter.
  3272. **
  3273. ** If F is the database filename pointer passed into the xOpen() method of
  3274. ** a VFS implementation when the flags parameter to xOpen() has one or
  3275. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3276. ** P is the name of the query parameter, then
  3277. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3278. ** parameter if it exists or a NULL pointer if P does not appear as a
  3279. ** query parameter on F. If P is a query parameter of F
  3280. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3281. ** a pointer to an empty string.
  3282. **
  3283. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3284. ** parameter and returns true (1) or false (0) according to the value
  3285. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3286. ** value of query parameter P is one of "yes", "true", or "on" in any
  3287. ** case or if the value begins with a non-zero number. The
  3288. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3289. ** query parameter P is one of "no", "false", or "off" in any case or
  3290. ** if the value begins with a numeric zero. If P is not a query
  3291. ** parameter on F or if the value of P is does not match any of the
  3292. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3293. **
  3294. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3295. ** 64-bit signed integer and returns that integer, or D if P does not
  3296. ** exist. If the value of P is something other than an integer, then
  3297. ** zero is returned.
  3298. **
  3299. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3300. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3301. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3302. ** VFS method, then the behavior of this routine is undefined and probably
  3303. ** undesirable.
  3304. */
  3305. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3306. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3307. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3308. /*
  3309. ** CAPI3REF: Error Codes And Messages
  3310. **
  3311. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  3312. ** [extended result code] for the most recent failed sqlite3_* API call
  3313. ** associated with a [database connection]. If a prior API call failed
  3314. ** but the most recent API call succeeded, the return value from
  3315. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  3316. ** interface is the same except that it always returns the
  3317. ** [extended result code] even when extended result codes are
  3318. ** disabled.
  3319. **
  3320. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3321. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3322. ** ^(Memory to hold the error message string is managed internally.
  3323. ** The application does not need to worry about freeing the result.
  3324. ** However, the error string might be overwritten or deallocated by
  3325. ** subsequent calls to other SQLite interface functions.)^
  3326. **
  3327. ** ^The sqlite3_errstr() interface returns the English-language text
  3328. ** that describes the [result code], as UTF-8.
  3329. ** ^(Memory to hold the error message string is managed internally
  3330. ** and must not be freed by the application)^.
  3331. **
  3332. ** When the serialized [threading mode] is in use, it might be the
  3333. ** case that a second error occurs on a separate thread in between
  3334. ** the time of the first error and the call to these interfaces.
  3335. ** When that happens, the second error will be reported since these
  3336. ** interfaces always report the most recent result. To avoid
  3337. ** this, each thread can obtain exclusive use of the [database connection] D
  3338. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3339. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3340. ** all calls to the interfaces listed here are completed.
  3341. **
  3342. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3343. ** was invoked incorrectly by the application. In that case, the
  3344. ** error code and message may or may not be set.
  3345. */
  3346. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3347. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3348. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3349. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3350. SQLITE_API const char *sqlite3_errstr(int);
  3351. /*
  3352. ** CAPI3REF: SQL Statement Object
  3353. ** KEYWORDS: {prepared statement} {prepared statements}
  3354. **
  3355. ** An instance of this object represents a single SQL statement.
  3356. ** This object is variously known as a "prepared statement" or a
  3357. ** "compiled SQL statement" or simply as a "statement".
  3358. **
  3359. ** The life of a statement object goes something like this:
  3360. **
  3361. ** <ol>
  3362. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3363. ** function.
  3364. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3365. ** interfaces.
  3366. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3367. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3368. ** to step 2. Do this zero or more times.
  3369. ** <li> Destroy the object using [sqlite3_finalize()].
  3370. ** </ol>
  3371. **
  3372. ** Refer to documentation on individual methods above for additional
  3373. ** information.
  3374. */
  3375. typedef struct sqlite3_stmt sqlite3_stmt;
  3376. /*
  3377. ** CAPI3REF: Run-time Limits
  3378. **
  3379. ** ^(This interface allows the size of various constructs to be limited
  3380. ** on a connection by connection basis. The first parameter is the
  3381. ** [database connection] whose limit is to be set or queried. The
  3382. ** second parameter is one of the [limit categories] that define a
  3383. ** class of constructs to be size limited. The third parameter is the
  3384. ** new limit for that construct.)^
  3385. **
  3386. ** ^If the new limit is a negative number, the limit is unchanged.
  3387. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3388. ** [limits | hard upper bound]
  3389. ** set at compile-time by a C preprocessor macro called
  3390. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3391. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3392. ** ^Attempts to increase a limit above its hard upper bound are
  3393. ** silently truncated to the hard upper bound.
  3394. **
  3395. ** ^Regardless of whether or not the limit was changed, the
  3396. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3397. ** ^Hence, to find the current value of a limit without changing it,
  3398. ** simply invoke this interface with the third parameter set to -1.
  3399. **
  3400. ** Run-time limits are intended for use in applications that manage
  3401. ** both their own internal database and also databases that are controlled
  3402. ** by untrusted external sources. An example application might be a
  3403. ** web browser that has its own databases for storing history and
  3404. ** separate databases controlled by JavaScript applications downloaded
  3405. ** off the Internet. The internal databases can be given the
  3406. ** large, default limits. Databases managed by external sources can
  3407. ** be given much smaller limits designed to prevent a denial of service
  3408. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3409. ** interface to further control untrusted SQL. The size of the database
  3410. ** created by an untrusted script can be contained using the
  3411. ** [max_page_count] [PRAGMA].
  3412. **
  3413. ** New run-time limit categories may be added in future releases.
  3414. */
  3415. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3416. /*
  3417. ** CAPI3REF: Run-Time Limit Categories
  3418. ** KEYWORDS: {limit category} {*limit categories}
  3419. **
  3420. ** These constants define various performance limits
  3421. ** that can be lowered at run-time using [sqlite3_limit()].
  3422. ** The synopsis of the meanings of the various limits is shown below.
  3423. ** Additional information is available at [limits | Limits in SQLite].
  3424. **
  3425. ** <dl>
  3426. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3427. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3428. **
  3429. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3430. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3431. **
  3432. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3433. ** <dd>The maximum number of columns in a table definition or in the
  3434. ** result set of a [SELECT] or the maximum number of columns in an index
  3435. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3436. **
  3437. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3438. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3439. **
  3440. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3441. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3442. **
  3443. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3444. ** <dd>The maximum number of instructions in a virtual machine program
  3445. ** used to implement an SQL statement. This limit is not currently
  3446. ** enforced, though that might be added in some future release of
  3447. ** SQLite.</dd>)^
  3448. **
  3449. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3450. ** <dd>The maximum number of arguments on a function.</dd>)^
  3451. **
  3452. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3453. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3454. **
  3455. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3456. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3457. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3458. ** [GLOB] operators.</dd>)^
  3459. **
  3460. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3461. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3462. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3463. **
  3464. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3465. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3466. ** </dl>
  3467. */
  3468. #define SQLITE_LIMIT_LENGTH 0
  3469. #define SQLITE_LIMIT_SQL_LENGTH 1
  3470. #define SQLITE_LIMIT_COLUMN 2
  3471. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3472. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3473. #define SQLITE_LIMIT_VDBE_OP 5
  3474. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3475. #define SQLITE_LIMIT_ATTACHED 7
  3476. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3477. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3478. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3479. /*
  3480. ** CAPI3REF: Compiling An SQL Statement
  3481. ** KEYWORDS: {SQL statement compiler}
  3482. **
  3483. ** To execute an SQL query, it must first be compiled into a byte-code
  3484. ** program using one of these routines.
  3485. **
  3486. ** The first argument, "db", is a [database connection] obtained from a
  3487. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3488. ** [sqlite3_open16()]. The database connection must not have been closed.
  3489. **
  3490. ** The second argument, "zSql", is the statement to be compiled, encoded
  3491. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3492. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3493. ** use UTF-16.
  3494. **
  3495. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3496. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3497. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3498. ** zSql string ends at either the first '\000' or '\u0000' character or
  3499. ** the nByte-th byte, whichever comes first. If the caller knows
  3500. ** that the supplied string is nul-terminated, then there is a small
  3501. ** performance advantage to be gained by passing an nByte parameter that
  3502. ** is equal to the number of bytes in the input string <i>including</i>
  3503. ** the nul-terminator bytes as this saves SQLite from having to
  3504. ** make a copy of the input string.
  3505. **
  3506. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3507. ** past the end of the first SQL statement in zSql. These routines only
  3508. ** compile the first statement in zSql, so *pzTail is left pointing to
  3509. ** what remains uncompiled.
  3510. **
  3511. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3512. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3513. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3514. ** string or a comment) then *ppStmt is set to NULL.
  3515. ** The calling procedure is responsible for deleting the compiled
  3516. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3517. ** ppStmt may not be NULL.
  3518. **
  3519. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3520. ** otherwise an [error code] is returned.
  3521. **
  3522. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3523. ** recommended for all new programs. The two older interfaces are retained
  3524. ** for backwards compatibility, but their use is discouraged.
  3525. ** ^In the "v2" interfaces, the prepared statement
  3526. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3527. ** original SQL text. This causes the [sqlite3_step()] interface to
  3528. ** behave differently in three ways:
  3529. **
  3530. ** <ol>
  3531. ** <li>
  3532. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3533. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3534. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3535. ** retries will occur before sqlite3_step() gives up and returns an error.
  3536. ** </li>
  3537. **
  3538. ** <li>
  3539. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3540. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3541. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3542. ** and the application would have to make a second call to [sqlite3_reset()]
  3543. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3544. ** interfaces, the underlying reason for the error is returned immediately.
  3545. ** </li>
  3546. **
  3547. ** <li>
  3548. ** ^If the specific value bound to [parameter | host parameter] in the
  3549. ** WHERE clause might influence the choice of query plan for a statement,
  3550. ** then the statement will be automatically recompiled, as if there had been
  3551. ** a schema change, on the first [sqlite3_step()] call following any change
  3552. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3553. ** ^The specific value of WHERE-clause [parameter] might influence the
  3554. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3555. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3556. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3557. ** the
  3558. ** </li>
  3559. ** </ol>
  3560. */
  3561. SQLITE_API int sqlite3_prepare(
  3562. sqlite3 *db, /* Database handle */
  3563. const char *zSql, /* SQL statement, UTF-8 encoded */
  3564. int nByte, /* Maximum length of zSql in bytes. */
  3565. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3566. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3567. );
  3568. SQLITE_API int sqlite3_prepare_v2(
  3569. sqlite3 *db, /* Database handle */
  3570. const char *zSql, /* SQL statement, UTF-8 encoded */
  3571. int nByte, /* Maximum length of zSql in bytes. */
  3572. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3573. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3574. );
  3575. SQLITE_API int sqlite3_prepare16(
  3576. sqlite3 *db, /* Database handle */
  3577. const void *zSql, /* SQL statement, UTF-16 encoded */
  3578. int nByte, /* Maximum length of zSql in bytes. */
  3579. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3580. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3581. );
  3582. SQLITE_API int sqlite3_prepare16_v2(
  3583. sqlite3 *db, /* Database handle */
  3584. const void *zSql, /* SQL statement, UTF-16 encoded */
  3585. int nByte, /* Maximum length of zSql in bytes. */
  3586. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3587. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3588. );
  3589. /*
  3590. ** CAPI3REF: Retrieving Statement SQL
  3591. **
  3592. ** ^This interface can be used to retrieve a saved copy of the original
  3593. ** SQL text used to create a [prepared statement] if that statement was
  3594. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3595. */
  3596. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3597. /*
  3598. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3599. **
  3600. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3601. ** and only if the [prepared statement] X makes no direct changes to
  3602. ** the content of the database file.
  3603. **
  3604. ** Note that [application-defined SQL functions] or
  3605. ** [virtual tables] might change the database indirectly as a side effect.
  3606. ** ^(For example, if an application defines a function "eval()" that
  3607. ** calls [sqlite3_exec()], then the following SQL statement would
  3608. ** change the database file through side-effects:
  3609. **
  3610. ** <blockquote><pre>
  3611. ** SELECT eval('DELETE FROM t1') FROM t2;
  3612. ** </pre></blockquote>
  3613. **
  3614. ** But because the [SELECT] statement does not change the database file
  3615. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3616. **
  3617. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3618. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3619. ** since the statements themselves do not actually modify the database but
  3620. ** rather they control the timing of when other statements modify the
  3621. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3622. ** sqlite3_stmt_readonly() to return true since, while those statements
  3623. ** change the configuration of a database connection, they do not make
  3624. ** changes to the content of the database files on disk.
  3625. */
  3626. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3627. /*
  3628. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3629. **
  3630. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3631. ** [prepared statement] S has been stepped at least once using
  3632. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3633. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3634. ** interface returns false if S is a NULL pointer. If S is not a
  3635. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3636. ** object, then the behavior is undefined and probably undesirable.
  3637. **
  3638. ** This interface can be used in combination [sqlite3_next_stmt()]
  3639. ** to locate all prepared statements associated with a database
  3640. ** connection that are in need of being reset. This can be used,
  3641. ** for example, in diagnostic routines to search for prepared
  3642. ** statements that are holding a transaction open.
  3643. */
  3644. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3645. /*
  3646. ** CAPI3REF: Dynamically Typed Value Object
  3647. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3648. **
  3649. ** SQLite uses the sqlite3_value object to represent all values
  3650. ** that can be stored in a database table. SQLite uses dynamic typing
  3651. ** for the values it stores. ^Values stored in sqlite3_value objects
  3652. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3653. **
  3654. ** An sqlite3_value object may be either "protected" or "unprotected".
  3655. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3656. ** will accept either a protected or an unprotected sqlite3_value.
  3657. ** Every interface that accepts sqlite3_value arguments specifies
  3658. ** whether or not it requires a protected sqlite3_value.
  3659. **
  3660. ** The terms "protected" and "unprotected" refer to whether or not
  3661. ** a mutex is held. An internal mutex is held for a protected
  3662. ** sqlite3_value object but no mutex is held for an unprotected
  3663. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3664. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3665. ** or if SQLite is run in one of reduced mutex modes
  3666. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3667. ** then there is no distinction between protected and unprotected
  3668. ** sqlite3_value objects and they can be used interchangeably. However,
  3669. ** for maximum code portability it is recommended that applications
  3670. ** still make the distinction between protected and unprotected
  3671. ** sqlite3_value objects even when not strictly required.
  3672. **
  3673. ** ^The sqlite3_value objects that are passed as parameters into the
  3674. ** implementation of [application-defined SQL functions] are protected.
  3675. ** ^The sqlite3_value object returned by
  3676. ** [sqlite3_column_value()] is unprotected.
  3677. ** Unprotected sqlite3_value objects may only be used with
  3678. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3679. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3680. ** interfaces require protected sqlite3_value objects.
  3681. */
  3682. typedef struct Mem sqlite3_value;
  3683. /*
  3684. ** CAPI3REF: SQL Function Context Object
  3685. **
  3686. ** The context in which an SQL function executes is stored in an
  3687. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3688. ** is always first parameter to [application-defined SQL functions].
  3689. ** The application-defined SQL function implementation will pass this
  3690. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3691. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3692. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3693. ** and/or [sqlite3_set_auxdata()].
  3694. */
  3695. typedef struct sqlite3_context sqlite3_context;
  3696. /*
  3697. ** CAPI3REF: Binding Values To Prepared Statements
  3698. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3699. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3700. **
  3701. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3702. ** literals may be replaced by a [parameter] that matches one of following
  3703. ** templates:
  3704. **
  3705. ** <ul>
  3706. ** <li> ?
  3707. ** <li> ?NNN
  3708. ** <li> :VVV
  3709. ** <li> @VVV
  3710. ** <li> $VVV
  3711. ** </ul>
  3712. **
  3713. ** In the templates above, NNN represents an integer literal,
  3714. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3715. ** parameters (also called "host parameter names" or "SQL parameters")
  3716. ** can be set using the sqlite3_bind_*() routines defined here.
  3717. **
  3718. ** ^The first argument to the sqlite3_bind_*() routines is always
  3719. ** a pointer to the [sqlite3_stmt] object returned from
  3720. ** [sqlite3_prepare_v2()] or its variants.
  3721. **
  3722. ** ^The second argument is the index of the SQL parameter to be set.
  3723. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3724. ** SQL parameter is used more than once, second and subsequent
  3725. ** occurrences have the same index as the first occurrence.
  3726. ** ^The index for named parameters can be looked up using the
  3727. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3728. ** for "?NNN" parameters is the value of NNN.
  3729. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3730. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3731. **
  3732. ** ^The third argument is the value to bind to the parameter.
  3733. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3734. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3735. ** is ignored and the end result is the same as sqlite3_bind_null().
  3736. **
  3737. ** ^(In those routines that have a fourth argument, its value is the
  3738. ** number of bytes in the parameter. To be clear: the value is the
  3739. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3740. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3741. ** is negative, then the length of the string is
  3742. ** the number of bytes up to the first zero terminator.
  3743. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3744. ** the behavior is undefined.
  3745. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3746. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3747. ** where the NUL terminator would occur assuming the string were NUL
  3748. ** terminated. If any NUL characters occur at byte offsets less than
  3749. ** the value of the fourth parameter then the resulting string value will
  3750. ** contain embedded NULs. The result of expressions involving strings
  3751. ** with embedded NULs is undefined.
  3752. **
  3753. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3754. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3755. ** string after SQLite has finished with it. ^The destructor is called
  3756. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3757. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3758. ** ^If the fifth argument is
  3759. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3760. ** information is in static, unmanaged space and does not need to be freed.
  3761. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3762. ** SQLite makes its own private copy of the data immediately, before
  3763. ** the sqlite3_bind_*() routine returns.
  3764. **
  3765. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3766. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3767. ** (just an integer to hold its size) while it is being processed.
  3768. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3769. ** content is later written using
  3770. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3771. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3772. **
  3773. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3774. ** for the [prepared statement] or with a prepared statement for which
  3775. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3776. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3777. ** routine is passed a [prepared statement] that has been finalized, the
  3778. ** result is undefined and probably harmful.
  3779. **
  3780. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3781. ** ^Unbound parameters are interpreted as NULL.
  3782. **
  3783. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3784. ** [error code] if anything goes wrong.
  3785. ** ^[SQLITE_RANGE] is returned if the parameter
  3786. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3787. **
  3788. ** See also: [sqlite3_bind_parameter_count()],
  3789. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3790. */
  3791. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3792. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3793. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3794. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3795. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3796. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3797. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3798. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3799. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3800. /*
  3801. ** CAPI3REF: Number Of SQL Parameters
  3802. **
  3803. ** ^This routine can be used to find the number of [SQL parameters]
  3804. ** in a [prepared statement]. SQL parameters are tokens of the
  3805. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3806. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3807. ** to the parameters at a later time.
  3808. **
  3809. ** ^(This routine actually returns the index of the largest (rightmost)
  3810. ** parameter. For all forms except ?NNN, this will correspond to the
  3811. ** number of unique parameters. If parameters of the ?NNN form are used,
  3812. ** there may be gaps in the list.)^
  3813. **
  3814. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3815. ** [sqlite3_bind_parameter_name()], and
  3816. ** [sqlite3_bind_parameter_index()].
  3817. */
  3818. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3819. /*
  3820. ** CAPI3REF: Name Of A Host Parameter
  3821. **
  3822. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3823. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3824. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3825. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3826. ** respectively.
  3827. ** In other words, the initial ":" or "$" or "@" or "?"
  3828. ** is included as part of the name.)^
  3829. ** ^Parameters of the form "?" without a following integer have no name
  3830. ** and are referred to as "nameless" or "anonymous parameters".
  3831. **
  3832. ** ^The first host parameter has an index of 1, not 0.
  3833. **
  3834. ** ^If the value N is out of range or if the N-th parameter is
  3835. ** nameless, then NULL is returned. ^The returned string is
  3836. ** always in UTF-8 encoding even if the named parameter was
  3837. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3838. ** [sqlite3_prepare16_v2()].
  3839. **
  3840. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3841. ** [sqlite3_bind_parameter_count()], and
  3842. ** [sqlite3_bind_parameter_index()].
  3843. */
  3844. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3845. /*
  3846. ** CAPI3REF: Index Of A Parameter With A Given Name
  3847. **
  3848. ** ^Return the index of an SQL parameter given its name. ^The
  3849. ** index value returned is suitable for use as the second
  3850. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3851. ** is returned if no matching parameter is found. ^The parameter
  3852. ** name must be given in UTF-8 even if the original statement
  3853. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3854. **
  3855. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3856. ** [sqlite3_bind_parameter_count()], and
  3857. ** [sqlite3_bind_parameter_index()].
  3858. */
  3859. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3860. /*
  3861. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3862. **
  3863. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3864. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3865. ** ^Use this routine to reset all host parameters to NULL.
  3866. */
  3867. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3868. /*
  3869. ** CAPI3REF: Number Of Columns In A Result Set
  3870. **
  3871. ** ^Return the number of columns in the result set returned by the
  3872. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3873. ** statement that does not return data (for example an [UPDATE]).
  3874. **
  3875. ** See also: [sqlite3_data_count()]
  3876. */
  3877. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3878. /*
  3879. ** CAPI3REF: Column Names In A Result Set
  3880. **
  3881. ** ^These routines return the name assigned to a particular column
  3882. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3883. ** interface returns a pointer to a zero-terminated UTF-8 string
  3884. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3885. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3886. ** that implements the [SELECT] statement. ^The second parameter is the
  3887. ** column number. ^The leftmost column is number 0.
  3888. **
  3889. ** ^The returned string pointer is valid until either the [prepared statement]
  3890. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3891. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3892. ** or until the next call to
  3893. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3894. **
  3895. ** ^If sqlite3_malloc() fails during the processing of either routine
  3896. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3897. ** NULL pointer is returned.
  3898. **
  3899. ** ^The name of a result column is the value of the "AS" clause for
  3900. ** that column, if there is an AS clause. If there is no AS clause
  3901. ** then the name of the column is unspecified and may change from
  3902. ** one release of SQLite to the next.
  3903. */
  3904. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3905. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3906. /*
  3907. ** CAPI3REF: Source Of Data In A Query Result
  3908. **
  3909. ** ^These routines provide a means to determine the database, table, and
  3910. ** table column that is the origin of a particular result column in
  3911. ** [SELECT] statement.
  3912. ** ^The name of the database or table or column can be returned as
  3913. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3914. ** the database name, the _table_ routines return the table name, and
  3915. ** the origin_ routines return the column name.
  3916. ** ^The returned string is valid until the [prepared statement] is destroyed
  3917. ** using [sqlite3_finalize()] or until the statement is automatically
  3918. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3919. ** or until the same information is requested
  3920. ** again in a different encoding.
  3921. **
  3922. ** ^The names returned are the original un-aliased names of the
  3923. ** database, table, and column.
  3924. **
  3925. ** ^The first argument to these interfaces is a [prepared statement].
  3926. ** ^These functions return information about the Nth result column returned by
  3927. ** the statement, where N is the second function argument.
  3928. ** ^The left-most column is column 0 for these routines.
  3929. **
  3930. ** ^If the Nth column returned by the statement is an expression or
  3931. ** subquery and is not a column value, then all of these functions return
  3932. ** NULL. ^These routine might also return NULL if a memory allocation error
  3933. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3934. ** or column that query result column was extracted from.
  3935. **
  3936. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3937. ** UTF-16 encoded strings and the other functions return UTF-8.
  3938. **
  3939. ** ^These APIs are only available if the library was compiled with the
  3940. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3941. **
  3942. ** If two or more threads call one or more of these routines against the same
  3943. ** prepared statement and column at the same time then the results are
  3944. ** undefined.
  3945. **
  3946. ** If two or more threads call one or more
  3947. ** [sqlite3_column_database_name | column metadata interfaces]
  3948. ** for the same [prepared statement] and result column
  3949. ** at the same time then the results are undefined.
  3950. */
  3951. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3952. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3953. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3954. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3955. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3956. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3957. /*
  3958. ** CAPI3REF: Declared Datatype Of A Query Result
  3959. **
  3960. ** ^(The first parameter is a [prepared statement].
  3961. ** If this statement is a [SELECT] statement and the Nth column of the
  3962. ** returned result set of that [SELECT] is a table column (not an
  3963. ** expression or subquery) then the declared type of the table
  3964. ** column is returned.)^ ^If the Nth column of the result set is an
  3965. ** expression or subquery, then a NULL pointer is returned.
  3966. ** ^The returned string is always UTF-8 encoded.
  3967. **
  3968. ** ^(For example, given the database schema:
  3969. **
  3970. ** CREATE TABLE t1(c1 VARIANT);
  3971. **
  3972. ** and the following statement to be compiled:
  3973. **
  3974. ** SELECT c1 + 1, c1 FROM t1;
  3975. **
  3976. ** this routine would return the string "VARIANT" for the second result
  3977. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3978. **
  3979. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3980. ** is declared to contain a particular type does not mean that the
  3981. ** data stored in that column is of the declared type. SQLite is
  3982. ** strongly typed, but the typing is dynamic not static. ^Type
  3983. ** is associated with individual values, not with the containers
  3984. ** used to hold those values.
  3985. */
  3986. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3987. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3988. /*
  3989. ** CAPI3REF: Evaluate An SQL Statement
  3990. **
  3991. ** After a [prepared statement] has been prepared using either
  3992. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3993. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3994. ** must be called one or more times to evaluate the statement.
  3995. **
  3996. ** The details of the behavior of the sqlite3_step() interface depend
  3997. ** on whether the statement was prepared using the newer "v2" interface
  3998. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3999. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  4000. ** new "v2" interface is recommended for new applications but the legacy
  4001. ** interface will continue to be supported.
  4002. **
  4003. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  4004. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  4005. ** ^With the "v2" interface, any of the other [result codes] or
  4006. ** [extended result codes] might be returned as well.
  4007. **
  4008. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  4009. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  4010. ** or occurs outside of an explicit transaction, then you can retry the
  4011. ** statement. If the statement is not a [COMMIT] and occurs within an
  4012. ** explicit transaction then you should rollback the transaction before
  4013. ** continuing.
  4014. **
  4015. ** ^[SQLITE_DONE] means that the statement has finished executing
  4016. ** successfully. sqlite3_step() should not be called again on this virtual
  4017. ** machine without first calling [sqlite3_reset()] to reset the virtual
  4018. ** machine back to its initial state.
  4019. **
  4020. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  4021. ** is returned each time a new row of data is ready for processing by the
  4022. ** caller. The values may be accessed using the [column access functions].
  4023. ** sqlite3_step() is called again to retrieve the next row of data.
  4024. **
  4025. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  4026. ** violation) has occurred. sqlite3_step() should not be called again on
  4027. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  4028. ** ^With the legacy interface, a more specific error code (for example,
  4029. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  4030. ** can be obtained by calling [sqlite3_reset()] on the
  4031. ** [prepared statement]. ^In the "v2" interface,
  4032. ** the more specific error code is returned directly by sqlite3_step().
  4033. **
  4034. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  4035. ** Perhaps it was called on a [prepared statement] that has
  4036. ** already been [sqlite3_finalize | finalized] or on one that had
  4037. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  4038. ** be the case that the same database connection is being used by two or
  4039. ** more threads at the same moment in time.
  4040. **
  4041. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  4042. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  4043. ** other than [SQLITE_ROW] before any subsequent invocation of
  4044. ** sqlite3_step(). Failure to reset the prepared statement using
  4045. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  4046. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  4047. ** calling [sqlite3_reset()] automatically in this circumstance rather
  4048. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  4049. ** break because any application that ever receives an SQLITE_MISUSE error
  4050. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  4051. ** can be used to restore the legacy behavior.
  4052. **
  4053. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  4054. ** API always returns a generic error code, [SQLITE_ERROR], following any
  4055. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  4056. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  4057. ** specific [error codes] that better describes the error.
  4058. ** We admit that this is a goofy design. The problem has been fixed
  4059. ** with the "v2" interface. If you prepare all of your SQL statements
  4060. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4061. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4062. ** then the more specific [error codes] are returned directly
  4063. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4064. */
  4065. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  4066. /*
  4067. ** CAPI3REF: Number of columns in a result set
  4068. **
  4069. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4070. ** current row of the result set of [prepared statement] P.
  4071. ** ^If prepared statement P does not have results ready to return
  4072. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4073. ** interfaces) then sqlite3_data_count(P) returns 0.
  4074. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4075. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4076. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4077. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4078. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4079. ** where it always returns zero since each step of that multi-step
  4080. ** pragma returns 0 columns of data.
  4081. **
  4082. ** See also: [sqlite3_column_count()]
  4083. */
  4084. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  4085. /*
  4086. ** CAPI3REF: Fundamental Datatypes
  4087. ** KEYWORDS: SQLITE_TEXT
  4088. **
  4089. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4090. **
  4091. ** <ul>
  4092. ** <li> 64-bit signed integer
  4093. ** <li> 64-bit IEEE floating point number
  4094. ** <li> string
  4095. ** <li> BLOB
  4096. ** <li> NULL
  4097. ** </ul>)^
  4098. **
  4099. ** These constants are codes for each of those types.
  4100. **
  4101. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4102. ** for a completely different meaning. Software that links against both
  4103. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4104. ** SQLITE_TEXT.
  4105. */
  4106. #define SQLITE_INTEGER 1
  4107. #define SQLITE_FLOAT 2
  4108. #define SQLITE_BLOB 4
  4109. #define SQLITE_NULL 5
  4110. #ifdef SQLITE_TEXT
  4111. # undef SQLITE_TEXT
  4112. #else
  4113. # define SQLITE_TEXT 3
  4114. #endif
  4115. #define SQLITE3_TEXT 3
  4116. /*
  4117. ** CAPI3REF: Result Values From A Query
  4118. ** KEYWORDS: {column access functions}
  4119. **
  4120. ** These routines form the "result set" interface.
  4121. **
  4122. ** ^These routines return information about a single column of the current
  4123. ** result row of a query. ^In every case the first argument is a pointer
  4124. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4125. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4126. ** and the second argument is the index of the column for which information
  4127. ** should be returned. ^The leftmost column of the result set has the index 0.
  4128. ** ^The number of columns in the result can be determined using
  4129. ** [sqlite3_column_count()].
  4130. **
  4131. ** If the SQL statement does not currently point to a valid row, or if the
  4132. ** column index is out of range, the result is undefined.
  4133. ** These routines may only be called when the most recent call to
  4134. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4135. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4136. ** If any of these routines are called after [sqlite3_reset()] or
  4137. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4138. ** something other than [SQLITE_ROW], the results are undefined.
  4139. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4140. ** are called from a different thread while any of these routines
  4141. ** are pending, then the results are undefined.
  4142. **
  4143. ** ^The sqlite3_column_type() routine returns the
  4144. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4145. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4146. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4147. ** returned by sqlite3_column_type() is only meaningful if no type
  4148. ** conversions have occurred as described below. After a type conversion,
  4149. ** the value returned by sqlite3_column_type() is undefined. Future
  4150. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4151. ** following a type conversion.
  4152. **
  4153. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4154. ** routine returns the number of bytes in that BLOB or string.
  4155. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4156. ** the string to UTF-8 and then returns the number of bytes.
  4157. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4158. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4159. ** the number of bytes in that string.
  4160. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4161. **
  4162. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4163. ** routine returns the number of bytes in that BLOB or string.
  4164. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4165. ** the string to UTF-16 and then returns the number of bytes.
  4166. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4167. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4168. ** the number of bytes in that string.
  4169. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4170. **
  4171. ** ^The values returned by [sqlite3_column_bytes()] and
  4172. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4173. ** of the string. ^For clarity: the values returned by
  4174. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4175. ** bytes in the string, not the number of characters.
  4176. **
  4177. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4178. ** even empty strings, are always zero-terminated. ^The return
  4179. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4180. **
  4181. ** ^The object returned by [sqlite3_column_value()] is an
  4182. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  4183. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  4184. ** If the [unprotected sqlite3_value] object returned by
  4185. ** [sqlite3_column_value()] is used in any other way, including calls
  4186. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4187. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  4188. **
  4189. ** These routines attempt to convert the value where appropriate. ^For
  4190. ** example, if the internal representation is FLOAT and a text result
  4191. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4192. ** conversion automatically. ^(The following table details the conversions
  4193. ** that are applied:
  4194. **
  4195. ** <blockquote>
  4196. ** <table border="1">
  4197. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4198. **
  4199. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4200. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4201. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  4202. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  4203. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4204. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4205. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4206. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  4207. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4208. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  4209. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  4210. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  4211. ** <tr><td> TEXT <td> BLOB <td> No change
  4212. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  4213. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  4214. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4215. ** </table>
  4216. ** </blockquote>)^
  4217. **
  4218. ** The table above makes reference to standard C library functions atoi()
  4219. ** and atof(). SQLite does not really use these functions. It has its
  4220. ** own equivalent internal routines. The atoi() and atof() names are
  4221. ** used in the table for brevity and because they are familiar to most
  4222. ** C programmers.
  4223. **
  4224. ** Note that when type conversions occur, pointers returned by prior
  4225. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4226. ** sqlite3_column_text16() may be invalidated.
  4227. ** Type conversions and pointer invalidations might occur
  4228. ** in the following cases:
  4229. **
  4230. ** <ul>
  4231. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4232. ** sqlite3_column_text16() is called. A zero-terminator might
  4233. ** need to be added to the string.</li>
  4234. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4235. ** sqlite3_column_text16() is called. The content must be converted
  4236. ** to UTF-16.</li>
  4237. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4238. ** sqlite3_column_text() is called. The content must be converted
  4239. ** to UTF-8.</li>
  4240. ** </ul>
  4241. **
  4242. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4243. ** not invalidate a prior pointer, though of course the content of the buffer
  4244. ** that the prior pointer references will have been modified. Other kinds
  4245. ** of conversion are done in place when it is possible, but sometimes they
  4246. ** are not possible and in those cases prior pointers are invalidated.
  4247. **
  4248. ** The safest and easiest to remember policy is to invoke these routines
  4249. ** in one of the following ways:
  4250. **
  4251. ** <ul>
  4252. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4253. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4254. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4255. ** </ul>
  4256. **
  4257. ** In other words, you should call sqlite3_column_text(),
  4258. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4259. ** into the desired format, then invoke sqlite3_column_bytes() or
  4260. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4261. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4262. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4263. ** with calls to sqlite3_column_bytes().
  4264. **
  4265. ** ^The pointers returned are valid until a type conversion occurs as
  4266. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4267. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4268. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  4269. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4270. ** [sqlite3_free()].
  4271. **
  4272. ** ^(If a memory allocation error occurs during the evaluation of any
  4273. ** of these routines, a default value is returned. The default value
  4274. ** is either the integer 0, the floating point number 0.0, or a NULL
  4275. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4276. ** [SQLITE_NOMEM].)^
  4277. */
  4278. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4279. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4280. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4281. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4282. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4283. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4284. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4285. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4286. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4287. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4288. /*
  4289. ** CAPI3REF: Destroy A Prepared Statement Object
  4290. **
  4291. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4292. ** ^If the most recent evaluation of the statement encountered no errors
  4293. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4294. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4295. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4296. ** [extended error code].
  4297. **
  4298. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4299. ** the life cycle of [prepared statement] S:
  4300. ** before statement S is ever evaluated, after
  4301. ** one or more calls to [sqlite3_reset()], or after any call
  4302. ** to [sqlite3_step()] regardless of whether or not the statement has
  4303. ** completed execution.
  4304. **
  4305. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4306. **
  4307. ** The application must finalize every [prepared statement] in order to avoid
  4308. ** resource leaks. It is a grievous error for the application to try to use
  4309. ** a prepared statement after it has been finalized. Any use of a prepared
  4310. ** statement after it has been finalized can result in undefined and
  4311. ** undesirable behavior such as segfaults and heap corruption.
  4312. */
  4313. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4314. /*
  4315. ** CAPI3REF: Reset A Prepared Statement Object
  4316. **
  4317. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4318. ** object back to its initial state, ready to be re-executed.
  4319. ** ^Any SQL statement variables that had values bound to them using
  4320. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4321. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4322. **
  4323. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4324. ** back to the beginning of its program.
  4325. **
  4326. ** ^If the most recent call to [sqlite3_step(S)] for the
  4327. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4328. ** or if [sqlite3_step(S)] has never before been called on S,
  4329. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4330. **
  4331. ** ^If the most recent call to [sqlite3_step(S)] for the
  4332. ** [prepared statement] S indicated an error, then
  4333. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4334. **
  4335. ** ^The [sqlite3_reset(S)] interface does not change the values
  4336. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4337. */
  4338. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4339. /*
  4340. ** CAPI3REF: Create Or Redefine SQL Functions
  4341. ** KEYWORDS: {function creation routines}
  4342. ** KEYWORDS: {application-defined SQL function}
  4343. ** KEYWORDS: {application-defined SQL functions}
  4344. **
  4345. ** ^These functions (collectively known as "function creation routines")
  4346. ** are used to add SQL functions or aggregates or to redefine the behavior
  4347. ** of existing SQL functions or aggregates. The only differences between
  4348. ** these routines are the text encoding expected for
  4349. ** the second parameter (the name of the function being created)
  4350. ** and the presence or absence of a destructor callback for
  4351. ** the application data pointer.
  4352. **
  4353. ** ^The first parameter is the [database connection] to which the SQL
  4354. ** function is to be added. ^If an application uses more than one database
  4355. ** connection then application-defined SQL functions must be added
  4356. ** to each database connection separately.
  4357. **
  4358. ** ^The second parameter is the name of the SQL function to be created or
  4359. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4360. ** representation, exclusive of the zero-terminator. ^Note that the name
  4361. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4362. ** ^Any attempt to create a function with a longer name
  4363. ** will result in [SQLITE_MISUSE] being returned.
  4364. **
  4365. ** ^The third parameter (nArg)
  4366. ** is the number of arguments that the SQL function or
  4367. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4368. ** aggregate may take any number of arguments between 0 and the limit
  4369. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4370. ** parameter is less than -1 or greater than 127 then the behavior is
  4371. ** undefined.
  4372. **
  4373. ** ^The fourth parameter, eTextRep, specifies what
  4374. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4375. ** its parameters. Every SQL function implementation must be able to work
  4376. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  4377. ** more efficient with one encoding than another. ^An application may
  4378. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  4379. ** times with the same function but with different values of eTextRep.
  4380. ** ^When multiple implementations of the same function are available, SQLite
  4381. ** will pick the one that involves the least amount of data conversion.
  4382. ** If there is only a single implementation which does not care what text
  4383. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  4384. **
  4385. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4386. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4387. **
  4388. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4389. ** pointers to C-language functions that implement the SQL function or
  4390. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4391. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4392. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4393. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4394. ** SQL function or aggregate, pass NULL pointers for all three function
  4395. ** callbacks.
  4396. **
  4397. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4398. ** then it is destructor for the application data pointer.
  4399. ** The destructor is invoked when the function is deleted, either by being
  4400. ** overloaded or when the database connection closes.)^
  4401. ** ^The destructor is also invoked if the call to
  4402. ** sqlite3_create_function_v2() fails.
  4403. ** ^When the destructor callback of the tenth parameter is invoked, it
  4404. ** is passed a single argument which is a copy of the application data
  4405. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4406. **
  4407. ** ^It is permitted to register multiple implementations of the same
  4408. ** functions with the same name but with either differing numbers of
  4409. ** arguments or differing preferred text encodings. ^SQLite will use
  4410. ** the implementation that most closely matches the way in which the
  4411. ** SQL function is used. ^A function implementation with a non-negative
  4412. ** nArg parameter is a better match than a function implementation with
  4413. ** a negative nArg. ^A function where the preferred text encoding
  4414. ** matches the database encoding is a better
  4415. ** match than a function where the encoding is different.
  4416. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4417. ** is a closer match than a function where the encoding difference is
  4418. ** between UTF8 and UTF16.
  4419. **
  4420. ** ^Built-in functions may be overloaded by new application-defined functions.
  4421. **
  4422. ** ^An application-defined function is permitted to call other
  4423. ** SQLite interfaces. However, such calls must not
  4424. ** close the database connection nor finalize or reset the prepared
  4425. ** statement in which the function is running.
  4426. */
  4427. SQLITE_API int sqlite3_create_function(
  4428. sqlite3 *db,
  4429. const char *zFunctionName,
  4430. int nArg,
  4431. int eTextRep,
  4432. void *pApp,
  4433. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4434. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4435. void (*xFinal)(sqlite3_context*)
  4436. );
  4437. SQLITE_API int sqlite3_create_function16(
  4438. sqlite3 *db,
  4439. const void *zFunctionName,
  4440. int nArg,
  4441. int eTextRep,
  4442. void *pApp,
  4443. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4444. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4445. void (*xFinal)(sqlite3_context*)
  4446. );
  4447. SQLITE_API int sqlite3_create_function_v2(
  4448. sqlite3 *db,
  4449. const char *zFunctionName,
  4450. int nArg,
  4451. int eTextRep,
  4452. void *pApp,
  4453. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4454. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4455. void (*xFinal)(sqlite3_context*),
  4456. void(*xDestroy)(void*)
  4457. );
  4458. /*
  4459. ** CAPI3REF: Text Encodings
  4460. **
  4461. ** These constant define integer codes that represent the various
  4462. ** text encodings supported by SQLite.
  4463. */
  4464. #define SQLITE_UTF8 1
  4465. #define SQLITE_UTF16LE 2
  4466. #define SQLITE_UTF16BE 3
  4467. #define SQLITE_UTF16 4 /* Use native byte order */
  4468. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  4469. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4470. /*
  4471. ** CAPI3REF: Deprecated Functions
  4472. ** DEPRECATED
  4473. **
  4474. ** These functions are [deprecated]. In order to maintain
  4475. ** backwards compatibility with older code, these functions continue
  4476. ** to be supported. However, new applications should avoid
  4477. ** the use of these functions. To help encourage people to avoid
  4478. ** using these functions, we are not going to tell you what they do.
  4479. */
  4480. #ifndef SQLITE_OMIT_DEPRECATED
  4481. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4482. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4483. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4484. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4485. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4486. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4487. void*,sqlite3_int64);
  4488. #endif
  4489. /*
  4490. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4491. **
  4492. ** The C-language implementation of SQL functions and aggregates uses
  4493. ** this set of interface routines to access the parameter values on
  4494. ** the function or aggregate.
  4495. **
  4496. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4497. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4498. ** define callbacks that implement the SQL functions and aggregates.
  4499. ** The 3rd parameter to these callbacks is an array of pointers to
  4500. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4501. ** each parameter to the SQL function. These routines are used to
  4502. ** extract values from the [sqlite3_value] objects.
  4503. **
  4504. ** These routines work only with [protected sqlite3_value] objects.
  4505. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4506. ** object results in undefined behavior.
  4507. **
  4508. ** ^These routines work just like the corresponding [column access functions]
  4509. ** except that these routines take a single [protected sqlite3_value] object
  4510. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4511. **
  4512. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4513. ** in the native byte-order of the host machine. ^The
  4514. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4515. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4516. **
  4517. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4518. ** numeric affinity to the value. This means that an attempt is
  4519. ** made to convert the value to an integer or floating point. If
  4520. ** such a conversion is possible without loss of information (in other
  4521. ** words, if the value is a string that looks like a number)
  4522. ** then the conversion is performed. Otherwise no conversion occurs.
  4523. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4524. **
  4525. ** Please pay particular attention to the fact that the pointer returned
  4526. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4527. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4528. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4529. ** or [sqlite3_value_text16()].
  4530. **
  4531. ** These routines must be called from the same thread as
  4532. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4533. */
  4534. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4535. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4536. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4537. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4538. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4539. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4540. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4541. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4542. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4543. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4544. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4545. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4546. /*
  4547. ** CAPI3REF: Obtain Aggregate Function Context
  4548. **
  4549. ** Implementations of aggregate SQL functions use this
  4550. ** routine to allocate memory for storing their state.
  4551. **
  4552. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4553. ** for a particular aggregate function, SQLite
  4554. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4555. ** to the new memory. ^On second and subsequent calls to
  4556. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4557. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4558. ** called once for each invocation of the xStep callback and then one
  4559. ** last time when the xFinal callback is invoked. ^(When no rows match
  4560. ** an aggregate query, the xStep() callback of the aggregate function
  4561. ** implementation is never called and xFinal() is called exactly once.
  4562. ** In those cases, sqlite3_aggregate_context() might be called for the
  4563. ** first time from within xFinal().)^
  4564. **
  4565. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4566. ** when first called if N is less than or equal to zero or if a memory
  4567. ** allocate error occurs.
  4568. **
  4569. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4570. ** determined by the N parameter on first successful call. Changing the
  4571. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4572. ** the same aggregate function instance will not resize the memory
  4573. ** allocation.)^ Within the xFinal callback, it is customary to set
  4574. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4575. ** pointless memory allocations occur.
  4576. **
  4577. ** ^SQLite automatically frees the memory allocated by
  4578. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4579. **
  4580. ** The first parameter must be a copy of the
  4581. ** [sqlite3_context | SQL function context] that is the first parameter
  4582. ** to the xStep or xFinal callback routine that implements the aggregate
  4583. ** function.
  4584. **
  4585. ** This routine must be called from the same thread in which
  4586. ** the aggregate SQL function is running.
  4587. */
  4588. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4589. /*
  4590. ** CAPI3REF: User Data For Functions
  4591. **
  4592. ** ^The sqlite3_user_data() interface returns a copy of
  4593. ** the pointer that was the pUserData parameter (the 5th parameter)
  4594. ** of the [sqlite3_create_function()]
  4595. ** and [sqlite3_create_function16()] routines that originally
  4596. ** registered the application defined function.
  4597. **
  4598. ** This routine must be called from the same thread in which
  4599. ** the application-defined function is running.
  4600. */
  4601. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4602. /*
  4603. ** CAPI3REF: Database Connection For Functions
  4604. **
  4605. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4606. ** the pointer to the [database connection] (the 1st parameter)
  4607. ** of the [sqlite3_create_function()]
  4608. ** and [sqlite3_create_function16()] routines that originally
  4609. ** registered the application defined function.
  4610. */
  4611. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4612. /*
  4613. ** CAPI3REF: Function Auxiliary Data
  4614. **
  4615. ** The following two functions may be used by scalar SQL functions to
  4616. ** associate metadata with argument values. If the same value is passed to
  4617. ** multiple invocations of the same SQL function during query execution, under
  4618. ** some circumstances the associated metadata may be preserved. This may
  4619. ** be used, for example, to add a regular-expression matching scalar
  4620. ** function. The compiled version of the regular expression is stored as
  4621. ** metadata associated with the SQL value passed as the regular expression
  4622. ** pattern. The compiled regular expression can be reused on multiple
  4623. ** invocations of the same function so that the original pattern string
  4624. ** does not need to be recompiled on each invocation.
  4625. **
  4626. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4627. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4628. ** value to the application-defined function. ^If no metadata has been ever
  4629. ** been set for the Nth argument of the function, or if the corresponding
  4630. ** function parameter has changed since the meta-data was set,
  4631. ** then sqlite3_get_auxdata() returns a NULL pointer.
  4632. **
  4633. ** ^The sqlite3_set_auxdata() interface saves the metadata
  4634. ** pointed to by its 3rd parameter as the metadata for the N-th
  4635. ** argument of the application-defined function. Subsequent
  4636. ** calls to sqlite3_get_auxdata() might return this data, if it has
  4637. ** not been destroyed.
  4638. ** ^If it is not NULL, SQLite will invoke the destructor
  4639. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  4640. ** the metadata when the corresponding function parameter changes
  4641. ** or when the SQL statement completes, whichever comes first.
  4642. **
  4643. ** SQLite is free to call the destructor and drop metadata on any
  4644. ** parameter of any function at any time. ^The only guarantee is that
  4645. ** the destructor will be called before the metadata is dropped.
  4646. **
  4647. ** ^(In practice, metadata is preserved between function calls for
  4648. ** expressions that are constant at compile time. This includes literal
  4649. ** values and [parameters].)^
  4650. **
  4651. ** These routines must be called from the same thread in which
  4652. ** the SQL function is running.
  4653. */
  4654. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4655. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4656. /*
  4657. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4658. **
  4659. ** These are special values for the destructor that is passed in as the
  4660. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4661. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4662. ** and will never change. It does not need to be destroyed. ^The
  4663. ** SQLITE_TRANSIENT value means that the content will likely change in
  4664. ** the near future and that SQLite should make its own private copy of
  4665. ** the content before returning.
  4666. **
  4667. ** The typedef is necessary to work around problems in certain
  4668. ** C++ compilers.
  4669. */
  4670. typedef void (*sqlite3_destructor_type)(void*);
  4671. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4672. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4673. /*
  4674. ** CAPI3REF: Setting The Result Of An SQL Function
  4675. **
  4676. ** These routines are used by the xFunc or xFinal callbacks that
  4677. ** implement SQL functions and aggregates. See
  4678. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4679. ** for additional information.
  4680. **
  4681. ** These functions work very much like the [parameter binding] family of
  4682. ** functions used to bind values to host parameters in prepared statements.
  4683. ** Refer to the [SQL parameter] documentation for additional information.
  4684. **
  4685. ** ^The sqlite3_result_blob() interface sets the result from
  4686. ** an application-defined function to be the BLOB whose content is pointed
  4687. ** to by the second parameter and which is N bytes long where N is the
  4688. ** third parameter.
  4689. **
  4690. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4691. ** the application-defined function to be a BLOB containing all zero
  4692. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4693. **
  4694. ** ^The sqlite3_result_double() interface sets the result from
  4695. ** an application-defined function to be a floating point value specified
  4696. ** by its 2nd argument.
  4697. **
  4698. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4699. ** cause the implemented SQL function to throw an exception.
  4700. ** ^SQLite uses the string pointed to by the
  4701. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4702. ** as the text of an error message. ^SQLite interprets the error
  4703. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4704. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4705. ** byte order. ^If the third parameter to sqlite3_result_error()
  4706. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4707. ** message all text up through the first zero character.
  4708. ** ^If the third parameter to sqlite3_result_error() or
  4709. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4710. ** bytes (not characters) from the 2nd parameter as the error message.
  4711. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4712. ** routines make a private copy of the error message text before
  4713. ** they return. Hence, the calling function can deallocate or
  4714. ** modify the text after they return without harm.
  4715. ** ^The sqlite3_result_error_code() function changes the error code
  4716. ** returned by SQLite as a result of an error in a function. ^By default,
  4717. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4718. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4719. **
  4720. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4721. ** error indicating that a string or BLOB is too long to represent.
  4722. **
  4723. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4724. ** error indicating that a memory allocation failed.
  4725. **
  4726. ** ^The sqlite3_result_int() interface sets the return value
  4727. ** of the application-defined function to be the 32-bit signed integer
  4728. ** value given in the 2nd argument.
  4729. ** ^The sqlite3_result_int64() interface sets the return value
  4730. ** of the application-defined function to be the 64-bit signed integer
  4731. ** value given in the 2nd argument.
  4732. **
  4733. ** ^The sqlite3_result_null() interface sets the return value
  4734. ** of the application-defined function to be NULL.
  4735. **
  4736. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4737. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4738. ** set the return value of the application-defined function to be
  4739. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4740. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4741. ** ^SQLite takes the text result from the application from
  4742. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4743. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4744. ** is negative, then SQLite takes result text from the 2nd parameter
  4745. ** through the first zero character.
  4746. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4747. ** is non-negative, then as many bytes (not characters) of the text
  4748. ** pointed to by the 2nd parameter are taken as the application-defined
  4749. ** function result. If the 3rd parameter is non-negative, then it
  4750. ** must be the byte offset into the string where the NUL terminator would
  4751. ** appear if the string where NUL terminated. If any NUL characters occur
  4752. ** in the string at a byte offset that is less than the value of the 3rd
  4753. ** parameter, then the resulting string will contain embedded NULs and the
  4754. ** result of expressions operating on strings with embedded NULs is undefined.
  4755. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4756. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4757. ** function as the destructor on the text or BLOB result when it has
  4758. ** finished using that result.
  4759. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4760. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4761. ** assumes that the text or BLOB result is in constant space and does not
  4762. ** copy the content of the parameter nor call a destructor on the content
  4763. ** when it has finished using that result.
  4764. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4765. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4766. ** then SQLite makes a copy of the result into space obtained from
  4767. ** from [sqlite3_malloc()] before it returns.
  4768. **
  4769. ** ^The sqlite3_result_value() interface sets the result of
  4770. ** the application-defined function to be a copy the
  4771. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4772. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4773. ** so that the [sqlite3_value] specified in the parameter may change or
  4774. ** be deallocated after sqlite3_result_value() returns without harm.
  4775. ** ^A [protected sqlite3_value] object may always be used where an
  4776. ** [unprotected sqlite3_value] object is required, so either
  4777. ** kind of [sqlite3_value] object can be used with this interface.
  4778. **
  4779. ** If these routines are called from within the different thread
  4780. ** than the one containing the application-defined function that received
  4781. ** the [sqlite3_context] pointer, the results are undefined.
  4782. */
  4783. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4784. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4785. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4786. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4787. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4788. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4789. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4790. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4791. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4792. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4793. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4794. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4795. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4796. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4797. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4798. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4799. /*
  4800. ** CAPI3REF: Define New Collating Sequences
  4801. **
  4802. ** ^These functions add, remove, or modify a [collation] associated
  4803. ** with the [database connection] specified as the first argument.
  4804. **
  4805. ** ^The name of the collation is a UTF-8 string
  4806. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4807. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4808. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4809. ** considered to be the same name.
  4810. **
  4811. ** ^(The third argument (eTextRep) must be one of the constants:
  4812. ** <ul>
  4813. ** <li> [SQLITE_UTF8],
  4814. ** <li> [SQLITE_UTF16LE],
  4815. ** <li> [SQLITE_UTF16BE],
  4816. ** <li> [SQLITE_UTF16], or
  4817. ** <li> [SQLITE_UTF16_ALIGNED].
  4818. ** </ul>)^
  4819. ** ^The eTextRep argument determines the encoding of strings passed
  4820. ** to the collating function callback, xCallback.
  4821. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4822. ** force strings to be UTF16 with native byte order.
  4823. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4824. ** on an even byte address.
  4825. **
  4826. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4827. ** through as the first argument to the collating function callback.
  4828. **
  4829. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4830. ** ^Multiple collating functions can be registered using the same name but
  4831. ** with different eTextRep parameters and SQLite will use whichever
  4832. ** function requires the least amount of data transformation.
  4833. ** ^If the xCallback argument is NULL then the collating function is
  4834. ** deleted. ^When all collating functions having the same name are deleted,
  4835. ** that collation is no longer usable.
  4836. **
  4837. ** ^The collating function callback is invoked with a copy of the pArg
  4838. ** application data pointer and with two strings in the encoding specified
  4839. ** by the eTextRep argument. The collating function must return an
  4840. ** integer that is negative, zero, or positive
  4841. ** if the first string is less than, equal to, or greater than the second,
  4842. ** respectively. A collating function must always return the same answer
  4843. ** given the same inputs. If two or more collating functions are registered
  4844. ** to the same collation name (using different eTextRep values) then all
  4845. ** must give an equivalent answer when invoked with equivalent strings.
  4846. ** The collating function must obey the following properties for all
  4847. ** strings A, B, and C:
  4848. **
  4849. ** <ol>
  4850. ** <li> If A==B then B==A.
  4851. ** <li> If A==B and B==C then A==C.
  4852. ** <li> If A&lt;B THEN B&gt;A.
  4853. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4854. ** </ol>
  4855. **
  4856. ** If a collating function fails any of the above constraints and that
  4857. ** collating function is registered and used, then the behavior of SQLite
  4858. ** is undefined.
  4859. **
  4860. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4861. ** with the addition that the xDestroy callback is invoked on pArg when
  4862. ** the collating function is deleted.
  4863. ** ^Collating functions are deleted when they are overridden by later
  4864. ** calls to the collation creation functions or when the
  4865. ** [database connection] is closed using [sqlite3_close()].
  4866. **
  4867. ** ^The xDestroy callback is <u>not</u> called if the
  4868. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4869. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4870. ** check the return code and dispose of the application data pointer
  4871. ** themselves rather than expecting SQLite to deal with it for them.
  4872. ** This is different from every other SQLite interface. The inconsistency
  4873. ** is unfortunate but cannot be changed without breaking backwards
  4874. ** compatibility.
  4875. **
  4876. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4877. */
  4878. SQLITE_API int sqlite3_create_collation(
  4879. sqlite3*,
  4880. const char *zName,
  4881. int eTextRep,
  4882. void *pArg,
  4883. int(*xCompare)(void*,int,const void*,int,const void*)
  4884. );
  4885. SQLITE_API int sqlite3_create_collation_v2(
  4886. sqlite3*,
  4887. const char *zName,
  4888. int eTextRep,
  4889. void *pArg,
  4890. int(*xCompare)(void*,int,const void*,int,const void*),
  4891. void(*xDestroy)(void*)
  4892. );
  4893. SQLITE_API int sqlite3_create_collation16(
  4894. sqlite3*,
  4895. const void *zName,
  4896. int eTextRep,
  4897. void *pArg,
  4898. int(*xCompare)(void*,int,const void*,int,const void*)
  4899. );
  4900. /*
  4901. ** CAPI3REF: Collation Needed Callbacks
  4902. **
  4903. ** ^To avoid having to register all collation sequences before a database
  4904. ** can be used, a single callback function may be registered with the
  4905. ** [database connection] to be invoked whenever an undefined collation
  4906. ** sequence is required.
  4907. **
  4908. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4909. ** then it is passed the names of undefined collation sequences as strings
  4910. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4911. ** the names are passed as UTF-16 in machine native byte order.
  4912. ** ^A call to either function replaces the existing collation-needed callback.
  4913. **
  4914. ** ^(When the callback is invoked, the first argument passed is a copy
  4915. ** of the second argument to sqlite3_collation_needed() or
  4916. ** sqlite3_collation_needed16(). The second argument is the database
  4917. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4918. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4919. ** sequence function required. The fourth parameter is the name of the
  4920. ** required collation sequence.)^
  4921. **
  4922. ** The callback function should register the desired collation using
  4923. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4924. ** [sqlite3_create_collation_v2()].
  4925. */
  4926. SQLITE_API int sqlite3_collation_needed(
  4927. sqlite3*,
  4928. void*,
  4929. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4930. );
  4931. SQLITE_API int sqlite3_collation_needed16(
  4932. sqlite3*,
  4933. void*,
  4934. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4935. );
  4936. #ifdef SQLITE_HAS_CODEC
  4937. /*
  4938. ** Specify the key for an encrypted database. This routine should be
  4939. ** called right after sqlite3_open().
  4940. **
  4941. ** The code to implement this API is not available in the public release
  4942. ** of SQLite.
  4943. */
  4944. SQLITE_API int sqlite3_key(
  4945. sqlite3 *db, /* Database to be rekeyed */
  4946. const void *pKey, int nKey /* The key */
  4947. );
  4948. /*
  4949. ** Change the key on an open database. If the current database is not
  4950. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4951. ** database is decrypted.
  4952. **
  4953. ** The code to implement this API is not available in the public release
  4954. ** of SQLite.
  4955. */
  4956. SQLITE_API int sqlite3_rekey(
  4957. sqlite3 *db, /* Database to be rekeyed */
  4958. const void *pKey, int nKey /* The new key */
  4959. );
  4960. /*
  4961. ** Specify the activation key for a SEE database. Unless
  4962. ** activated, none of the SEE routines will work.
  4963. */
  4964. SQLITE_API void sqlite3_activate_see(
  4965. const char *zPassPhrase /* Activation phrase */
  4966. );
  4967. #endif
  4968. #ifdef SQLITE_ENABLE_CEROD
  4969. /*
  4970. ** Specify the activation key for a CEROD database. Unless
  4971. ** activated, none of the CEROD routines will work.
  4972. */
  4973. SQLITE_API void sqlite3_activate_cerod(
  4974. const char *zPassPhrase /* Activation phrase */
  4975. );
  4976. #endif
  4977. /*
  4978. ** CAPI3REF: Suspend Execution For A Short Time
  4979. **
  4980. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4981. ** for at least a number of milliseconds specified in its parameter.
  4982. **
  4983. ** If the operating system does not support sleep requests with
  4984. ** millisecond time resolution, then the time will be rounded up to
  4985. ** the nearest second. The number of milliseconds of sleep actually
  4986. ** requested from the operating system is returned.
  4987. **
  4988. ** ^SQLite implements this interface by calling the xSleep()
  4989. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4990. ** of the default VFS is not implemented correctly, or not implemented at
  4991. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4992. ** in the previous paragraphs.
  4993. */
  4994. SQLITE_API int sqlite3_sleep(int);
  4995. /*
  4996. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4997. **
  4998. ** ^(If this global variable is made to point to a string which is
  4999. ** the name of a folder (a.k.a. directory), then all temporary files
  5000. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5001. ** will be placed in that directory.)^ ^If this variable
  5002. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5003. ** temporary file directory.
  5004. **
  5005. ** It is not safe to read or modify this variable in more than one
  5006. ** thread at a time. It is not safe to read or modify this variable
  5007. ** if a [database connection] is being used at the same time in a separate
  5008. ** thread.
  5009. ** It is intended that this variable be set once
  5010. ** as part of process initialization and before any SQLite interface
  5011. ** routines have been called and that this variable remain unchanged
  5012. ** thereafter.
  5013. **
  5014. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5015. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5016. ** the [temp_store_directory pragma] always assumes that any string
  5017. ** that this variable points to is held in memory obtained from
  5018. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5019. ** using [sqlite3_free].
  5020. ** Hence, if this variable is modified directly, either it should be
  5021. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5022. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5023. **
  5024. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5025. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5026. ** features that require the use of temporary files may fail. Here is an
  5027. ** example of how to do this using C++ with the Windows Runtime:
  5028. **
  5029. ** <blockquote><pre>
  5030. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5031. ** &nbsp; TemporaryFolder->Path->Data();
  5032. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5033. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5034. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5035. ** &nbsp; NULL, NULL);
  5036. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5037. ** </pre></blockquote>
  5038. */
  5039. SQLITE_API char *sqlite3_temp_directory;
  5040. /*
  5041. ** CAPI3REF: Name Of The Folder Holding Database Files
  5042. **
  5043. ** ^(If this global variable is made to point to a string which is
  5044. ** the name of a folder (a.k.a. directory), then all database files
  5045. ** specified with a relative pathname and created or accessed by
  5046. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5047. ** to be relative to that directory.)^ ^If this variable is a NULL
  5048. ** pointer, then SQLite assumes that all database files specified
  5049. ** with a relative pathname are relative to the current directory
  5050. ** for the process. Only the windows VFS makes use of this global
  5051. ** variable; it is ignored by the unix VFS.
  5052. **
  5053. ** Changing the value of this variable while a database connection is
  5054. ** open can result in a corrupt database.
  5055. **
  5056. ** It is not safe to read or modify this variable in more than one
  5057. ** thread at a time. It is not safe to read or modify this variable
  5058. ** if a [database connection] is being used at the same time in a separate
  5059. ** thread.
  5060. ** It is intended that this variable be set once
  5061. ** as part of process initialization and before any SQLite interface
  5062. ** routines have been called and that this variable remain unchanged
  5063. ** thereafter.
  5064. **
  5065. ** ^The [data_store_directory pragma] may modify this variable and cause
  5066. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5067. ** the [data_store_directory pragma] always assumes that any string
  5068. ** that this variable points to is held in memory obtained from
  5069. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5070. ** using [sqlite3_free].
  5071. ** Hence, if this variable is modified directly, either it should be
  5072. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5073. ** or else the use of the [data_store_directory pragma] should be avoided.
  5074. */
  5075. SQLITE_API char *sqlite3_data_directory;
  5076. /*
  5077. ** CAPI3REF: Test For Auto-Commit Mode
  5078. ** KEYWORDS: {autocommit mode}
  5079. **
  5080. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5081. ** zero if the given database connection is or is not in autocommit mode,
  5082. ** respectively. ^Autocommit mode is on by default.
  5083. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5084. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5085. **
  5086. ** If certain kinds of errors occur on a statement within a multi-statement
  5087. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5088. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5089. ** transaction might be rolled back automatically. The only way to
  5090. ** find out whether SQLite automatically rolled back the transaction after
  5091. ** an error is to use this function.
  5092. **
  5093. ** If another thread changes the autocommit status of the database
  5094. ** connection while this routine is running, then the return value
  5095. ** is undefined.
  5096. */
  5097. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  5098. /*
  5099. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5100. **
  5101. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5102. ** to which a [prepared statement] belongs. ^The [database connection]
  5103. ** returned by sqlite3_db_handle is the same [database connection]
  5104. ** that was the first argument
  5105. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5106. ** create the statement in the first place.
  5107. */
  5108. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  5109. /*
  5110. ** CAPI3REF: Return The Filename For A Database Connection
  5111. **
  5112. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5113. ** associated with database N of connection D. ^The main database file
  5114. ** has the name "main". If there is no attached database N on the database
  5115. ** connection D, or if database N is a temporary or in-memory database, then
  5116. ** a NULL pointer is returned.
  5117. **
  5118. ** ^The filename returned by this function is the output of the
  5119. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5120. ** will be an absolute pathname, even if the filename used
  5121. ** to open the database originally was a URI or relative pathname.
  5122. */
  5123. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5124. /*
  5125. ** CAPI3REF: Determine if a database is read-only
  5126. **
  5127. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5128. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5129. ** the name of a database on connection D.
  5130. */
  5131. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5132. /*
  5133. ** CAPI3REF: Find the next prepared statement
  5134. **
  5135. ** ^This interface returns a pointer to the next [prepared statement] after
  5136. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5137. ** then this interface returns a pointer to the first prepared statement
  5138. ** associated with the database connection pDb. ^If no prepared statement
  5139. ** satisfies the conditions of this routine, it returns NULL.
  5140. **
  5141. ** The [database connection] pointer D in a call to
  5142. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5143. ** connection and in particular must not be a NULL pointer.
  5144. */
  5145. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5146. /*
  5147. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5148. **
  5149. ** ^The sqlite3_commit_hook() interface registers a callback
  5150. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5151. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5152. ** for the same database connection is overridden.
  5153. ** ^The sqlite3_rollback_hook() interface registers a callback
  5154. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5155. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5156. ** for the same database connection is overridden.
  5157. ** ^The pArg argument is passed through to the callback.
  5158. ** ^If the callback on a commit hook function returns non-zero,
  5159. ** then the commit is converted into a rollback.
  5160. **
  5161. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5162. ** return the P argument from the previous call of the same function
  5163. ** on the same [database connection] D, or NULL for
  5164. ** the first call for each function on D.
  5165. **
  5166. ** The commit and rollback hook callbacks are not reentrant.
  5167. ** The callback implementation must not do anything that will modify
  5168. ** the database connection that invoked the callback. Any actions
  5169. ** to modify the database connection must be deferred until after the
  5170. ** completion of the [sqlite3_step()] call that triggered the commit
  5171. ** or rollback hook in the first place.
  5172. ** Note that running any other SQL statements, including SELECT statements,
  5173. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5174. ** the database connections for the meaning of "modify" in this paragraph.
  5175. **
  5176. ** ^Registering a NULL function disables the callback.
  5177. **
  5178. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5179. ** operation is allowed to continue normally. ^If the commit hook
  5180. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5181. ** ^The rollback hook is invoked on a rollback that results from a commit
  5182. ** hook returning non-zero, just as it would be with any other rollback.
  5183. **
  5184. ** ^For the purposes of this API, a transaction is said to have been
  5185. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5186. ** an error or constraint causes an implicit rollback to occur.
  5187. ** ^The rollback callback is not invoked if a transaction is
  5188. ** automatically rolled back because the database connection is closed.
  5189. **
  5190. ** See also the [sqlite3_update_hook()] interface.
  5191. */
  5192. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5193. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5194. /*
  5195. ** CAPI3REF: Data Change Notification Callbacks
  5196. **
  5197. ** ^The sqlite3_update_hook() interface registers a callback function
  5198. ** with the [database connection] identified by the first argument
  5199. ** to be invoked whenever a row is updated, inserted or deleted.
  5200. ** ^Any callback set by a previous call to this function
  5201. ** for the same database connection is overridden.
  5202. **
  5203. ** ^The second argument is a pointer to the function to invoke when a
  5204. ** row is updated, inserted or deleted.
  5205. ** ^The first argument to the callback is a copy of the third argument
  5206. ** to sqlite3_update_hook().
  5207. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5208. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5209. ** to be invoked.
  5210. ** ^The third and fourth arguments to the callback contain pointers to the
  5211. ** database and table name containing the affected row.
  5212. ** ^The final callback parameter is the [rowid] of the row.
  5213. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5214. **
  5215. ** ^(The update hook is not invoked when internal system tables are
  5216. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5217. **
  5218. ** ^In the current implementation, the update hook
  5219. ** is not invoked when duplication rows are deleted because of an
  5220. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5221. ** invoked when rows are deleted using the [truncate optimization].
  5222. ** The exceptions defined in this paragraph might change in a future
  5223. ** release of SQLite.
  5224. **
  5225. ** The update hook implementation must not do anything that will modify
  5226. ** the database connection that invoked the update hook. Any actions
  5227. ** to modify the database connection must be deferred until after the
  5228. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5229. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5230. ** database connections for the meaning of "modify" in this paragraph.
  5231. **
  5232. ** ^The sqlite3_update_hook(D,C,P) function
  5233. ** returns the P argument from the previous call
  5234. ** on the same [database connection] D, or NULL for
  5235. ** the first call on D.
  5236. **
  5237. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5238. ** interfaces.
  5239. */
  5240. SQLITE_API void *sqlite3_update_hook(
  5241. sqlite3*,
  5242. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5243. void*
  5244. );
  5245. /*
  5246. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5247. **
  5248. ** ^(This routine enables or disables the sharing of the database cache
  5249. ** and schema data structures between [database connection | connections]
  5250. ** to the same database. Sharing is enabled if the argument is true
  5251. ** and disabled if the argument is false.)^
  5252. **
  5253. ** ^Cache sharing is enabled and disabled for an entire process.
  5254. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5255. ** sharing was enabled or disabled for each thread separately.
  5256. **
  5257. ** ^(The cache sharing mode set by this interface effects all subsequent
  5258. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5259. ** Existing database connections continue use the sharing mode
  5260. ** that was in effect at the time they were opened.)^
  5261. **
  5262. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5263. ** successfully. An [error code] is returned otherwise.)^
  5264. **
  5265. ** ^Shared cache is disabled by default. But this might change in
  5266. ** future releases of SQLite. Applications that care about shared
  5267. ** cache setting should set it explicitly.
  5268. **
  5269. ** This interface is threadsafe on processors where writing a
  5270. ** 32-bit integer is atomic.
  5271. **
  5272. ** See Also: [SQLite Shared-Cache Mode]
  5273. */
  5274. SQLITE_API int sqlite3_enable_shared_cache(int);
  5275. /*
  5276. ** CAPI3REF: Attempt To Free Heap Memory
  5277. **
  5278. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5279. ** of heap memory by deallocating non-essential memory allocations
  5280. ** held by the database library. Memory used to cache database
  5281. ** pages to improve performance is an example of non-essential memory.
  5282. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5283. ** which might be more or less than the amount requested.
  5284. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5285. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5286. **
  5287. ** See also: [sqlite3_db_release_memory()]
  5288. */
  5289. SQLITE_API int sqlite3_release_memory(int);
  5290. /*
  5291. ** CAPI3REF: Free Memory Used By A Database Connection
  5292. **
  5293. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5294. ** memory as possible from database connection D. Unlike the
  5295. ** [sqlite3_release_memory()] interface, this interface is effect even
  5296. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5297. ** omitted.
  5298. **
  5299. ** See also: [sqlite3_release_memory()]
  5300. */
  5301. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5302. /*
  5303. ** CAPI3REF: Impose A Limit On Heap Size
  5304. **
  5305. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5306. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5307. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5308. ** limit by reducing the number of pages held in the page cache
  5309. ** as heap memory usages approaches the limit.
  5310. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5311. ** below the limit, it will exceed the limit rather than generate
  5312. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5313. ** is advisory only.
  5314. **
  5315. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5316. ** the soft heap limit prior to the call, or negative in the case of an
  5317. ** error. ^If the argument N is negative
  5318. ** then no change is made to the soft heap limit. Hence, the current
  5319. ** size of the soft heap limit can be determined by invoking
  5320. ** sqlite3_soft_heap_limit64() with a negative argument.
  5321. **
  5322. ** ^If the argument N is zero then the soft heap limit is disabled.
  5323. **
  5324. ** ^(The soft heap limit is not enforced in the current implementation
  5325. ** if one or more of following conditions are true:
  5326. **
  5327. ** <ul>
  5328. ** <li> The soft heap limit is set to zero.
  5329. ** <li> Memory accounting is disabled using a combination of the
  5330. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5331. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5332. ** <li> An alternative page cache implementation is specified using
  5333. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5334. ** <li> The page cache allocates from its own memory pool supplied
  5335. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5336. ** from the heap.
  5337. ** </ul>)^
  5338. **
  5339. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5340. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5341. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5342. ** the soft heap limit is enforced on every memory allocation. Without
  5343. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5344. ** when memory is allocated by the page cache. Testing suggests that because
  5345. ** the page cache is the predominate memory user in SQLite, most
  5346. ** applications will achieve adequate soft heap limit enforcement without
  5347. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5348. **
  5349. ** The circumstances under which SQLite will enforce the soft heap limit may
  5350. ** changes in future releases of SQLite.
  5351. */
  5352. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5353. /*
  5354. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5355. ** DEPRECATED
  5356. **
  5357. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5358. ** interface. This routine is provided for historical compatibility
  5359. ** only. All new applications should use the
  5360. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5361. */
  5362. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5363. /*
  5364. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5365. **
  5366. ** ^This routine returns metadata about a specific column of a specific
  5367. ** database table accessible using the [database connection] handle
  5368. ** passed as the first function argument.
  5369. **
  5370. ** ^The column is identified by the second, third and fourth parameters to
  5371. ** this function. ^The second parameter is either the name of the database
  5372. ** (i.e. "main", "temp", or an attached database) containing the specified
  5373. ** table or NULL. ^If it is NULL, then all attached databases are searched
  5374. ** for the table using the same algorithm used by the database engine to
  5375. ** resolve unqualified table references.
  5376. **
  5377. ** ^The third and fourth parameters to this function are the table and column
  5378. ** name of the desired column, respectively. Neither of these parameters
  5379. ** may be NULL.
  5380. **
  5381. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5382. ** and subsequent parameters to this function. ^Any of these arguments may be
  5383. ** NULL, in which case the corresponding element of metadata is omitted.
  5384. **
  5385. ** ^(<blockquote>
  5386. ** <table border="1">
  5387. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5388. **
  5389. ** <tr><td> 5th <td> const char* <td> Data type
  5390. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5391. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5392. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5393. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5394. ** </table>
  5395. ** </blockquote>)^
  5396. **
  5397. ** ^The memory pointed to by the character pointers returned for the
  5398. ** declaration type and collation sequence is valid only until the next
  5399. ** call to any SQLite API function.
  5400. **
  5401. ** ^If the specified table is actually a view, an [error code] is returned.
  5402. **
  5403. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  5404. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5405. ** parameters are set for the explicitly declared column. ^(If there is no
  5406. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5407. ** parameters are set as follows:
  5408. **
  5409. ** <pre>
  5410. ** data type: "INTEGER"
  5411. ** collation sequence: "BINARY"
  5412. ** not null: 0
  5413. ** primary key: 1
  5414. ** auto increment: 0
  5415. ** </pre>)^
  5416. **
  5417. ** ^(This function may load one or more schemas from database files. If an
  5418. ** error occurs during this process, or if the requested table or column
  5419. ** cannot be found, an [error code] is returned and an error message left
  5420. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  5421. **
  5422. ** ^This API is only available if the library was compiled with the
  5423. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5424. */
  5425. SQLITE_API int sqlite3_table_column_metadata(
  5426. sqlite3 *db, /* Connection handle */
  5427. const char *zDbName, /* Database name or NULL */
  5428. const char *zTableName, /* Table name */
  5429. const char *zColumnName, /* Column name */
  5430. char const **pzDataType, /* OUTPUT: Declared data type */
  5431. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5432. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5433. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5434. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5435. );
  5436. /*
  5437. ** CAPI3REF: Load An Extension
  5438. **
  5439. ** ^This interface loads an SQLite extension library from the named file.
  5440. **
  5441. ** ^The sqlite3_load_extension() interface attempts to load an
  5442. ** [SQLite extension] library contained in the file zFile. If
  5443. ** the file cannot be loaded directly, attempts are made to load
  5444. ** with various operating-system specific extensions added.
  5445. ** So for example, if "samplelib" cannot be loaded, then names like
  5446. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5447. ** be tried also.
  5448. **
  5449. ** ^The entry point is zProc.
  5450. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5451. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5452. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5453. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5454. ** characters in the filename from the last "/" to the first following
  5455. ** "." and omitting any initial "lib".)^
  5456. ** ^The sqlite3_load_extension() interface returns
  5457. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5458. ** ^If an error occurs and pzErrMsg is not 0, then the
  5459. ** [sqlite3_load_extension()] interface shall attempt to
  5460. ** fill *pzErrMsg with error message text stored in memory
  5461. ** obtained from [sqlite3_malloc()]. The calling function
  5462. ** should free this memory by calling [sqlite3_free()].
  5463. **
  5464. ** ^Extension loading must be enabled using
  5465. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5466. ** otherwise an error will be returned.
  5467. **
  5468. ** See also the [load_extension() SQL function].
  5469. */
  5470. SQLITE_API int sqlite3_load_extension(
  5471. sqlite3 *db, /* Load the extension into this database connection */
  5472. const char *zFile, /* Name of the shared library containing extension */
  5473. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5474. char **pzErrMsg /* Put error message here if not 0 */
  5475. );
  5476. /*
  5477. ** CAPI3REF: Enable Or Disable Extension Loading
  5478. **
  5479. ** ^So as not to open security holes in older applications that are
  5480. ** unprepared to deal with [extension loading], and as a means of disabling
  5481. ** [extension loading] while evaluating user-entered SQL, the following API
  5482. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5483. **
  5484. ** ^Extension loading is off by default.
  5485. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5486. ** to turn extension loading on and call it with onoff==0 to turn
  5487. ** it back off again.
  5488. */
  5489. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5490. /*
  5491. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5492. **
  5493. ** ^This interface causes the xEntryPoint() function to be invoked for
  5494. ** each new [database connection] that is created. The idea here is that
  5495. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5496. ** that is to be automatically loaded into all new database connections.
  5497. **
  5498. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5499. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5500. ** arguments and expects and integer result as if the signature of the
  5501. ** entry point where as follows:
  5502. **
  5503. ** <blockquote><pre>
  5504. ** &nbsp; int xEntryPoint(
  5505. ** &nbsp; sqlite3 *db,
  5506. ** &nbsp; const char **pzErrMsg,
  5507. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5508. ** &nbsp; );
  5509. ** </pre></blockquote>)^
  5510. **
  5511. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5512. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5513. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5514. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5515. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5516. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5517. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5518. **
  5519. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5520. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5521. ** will be called more than once for each database connection that is opened.
  5522. **
  5523. ** See also: [sqlite3_reset_auto_extension()].
  5524. */
  5525. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5526. /*
  5527. ** CAPI3REF: Reset Automatic Extension Loading
  5528. **
  5529. ** ^This interface disables all automatic extensions previously
  5530. ** registered using [sqlite3_auto_extension()].
  5531. */
  5532. SQLITE_API void sqlite3_reset_auto_extension(void);
  5533. /*
  5534. ** The interface to the virtual-table mechanism is currently considered
  5535. ** to be experimental. The interface might change in incompatible ways.
  5536. ** If this is a problem for you, do not use the interface at this time.
  5537. **
  5538. ** When the virtual-table mechanism stabilizes, we will declare the
  5539. ** interface fixed, support it indefinitely, and remove this comment.
  5540. */
  5541. /*
  5542. ** Structures used by the virtual table interface
  5543. */
  5544. typedef struct sqlite3_vtab sqlite3_vtab;
  5545. typedef struct sqlite3_index_info sqlite3_index_info;
  5546. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5547. typedef struct sqlite3_module sqlite3_module;
  5548. /*
  5549. ** CAPI3REF: Virtual Table Object
  5550. ** KEYWORDS: sqlite3_module {virtual table module}
  5551. **
  5552. ** This structure, sometimes called a "virtual table module",
  5553. ** defines the implementation of a [virtual tables].
  5554. ** This structure consists mostly of methods for the module.
  5555. **
  5556. ** ^A virtual table module is created by filling in a persistent
  5557. ** instance of this structure and passing a pointer to that instance
  5558. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5559. ** ^The registration remains valid until it is replaced by a different
  5560. ** module or until the [database connection] closes. The content
  5561. ** of this structure must not change while it is registered with
  5562. ** any database connection.
  5563. */
  5564. struct sqlite3_module {
  5565. int iVersion;
  5566. int (*xCreate)(sqlite3*, void *pAux,
  5567. int argc, const char *const*argv,
  5568. sqlite3_vtab **ppVTab, char**);
  5569. int (*xConnect)(sqlite3*, void *pAux,
  5570. int argc, const char *const*argv,
  5571. sqlite3_vtab **ppVTab, char**);
  5572. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5573. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5574. int (*xDestroy)(sqlite3_vtab *pVTab);
  5575. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5576. int (*xClose)(sqlite3_vtab_cursor*);
  5577. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5578. int argc, sqlite3_value **argv);
  5579. int (*xNext)(sqlite3_vtab_cursor*);
  5580. int (*xEof)(sqlite3_vtab_cursor*);
  5581. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5582. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5583. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5584. int (*xBegin)(sqlite3_vtab *pVTab);
  5585. int (*xSync)(sqlite3_vtab *pVTab);
  5586. int (*xCommit)(sqlite3_vtab *pVTab);
  5587. int (*xRollback)(sqlite3_vtab *pVTab);
  5588. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5589. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5590. void **ppArg);
  5591. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5592. /* The methods above are in version 1 of the sqlite_module object. Those
  5593. ** below are for version 2 and greater. */
  5594. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5595. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5596. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5597. };
  5598. /*
  5599. ** CAPI3REF: Virtual Table Indexing Information
  5600. ** KEYWORDS: sqlite3_index_info
  5601. **
  5602. ** The sqlite3_index_info structure and its substructures is used as part
  5603. ** of the [virtual table] interface to
  5604. ** pass information into and receive the reply from the [xBestIndex]
  5605. ** method of a [virtual table module]. The fields under **Inputs** are the
  5606. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5607. ** results into the **Outputs** fields.
  5608. **
  5609. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5610. **
  5611. ** <blockquote>column OP expr</blockquote>
  5612. **
  5613. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5614. ** stored in aConstraint[].op using one of the
  5615. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5616. ** ^(The index of the column is stored in
  5617. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5618. ** expr on the right-hand side can be evaluated (and thus the constraint
  5619. ** is usable) and false if it cannot.)^
  5620. **
  5621. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5622. ** and makes other simplifications to the WHERE clause in an attempt to
  5623. ** get as many WHERE clause terms into the form shown above as possible.
  5624. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5625. ** relevant to the particular virtual table being queried.
  5626. **
  5627. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5628. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5629. **
  5630. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5631. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5632. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5633. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5634. ** is true, then the constraint is assumed to be fully handled by the
  5635. ** virtual table and is not checked again by SQLite.)^
  5636. **
  5637. ** ^The idxNum and idxPtr values are recorded and passed into the
  5638. ** [xFilter] method.
  5639. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5640. ** needToFreeIdxPtr is true.
  5641. **
  5642. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5643. ** the correct order to satisfy the ORDER BY clause so that no separate
  5644. ** sorting step is required.
  5645. **
  5646. ** ^The estimatedCost value is an estimate of the cost of doing the
  5647. ** particular lookup. A full scan of a table with N entries should have
  5648. ** a cost of N. A binary search of a table of N entries should have a
  5649. ** cost of approximately log(N).
  5650. */
  5651. struct sqlite3_index_info {
  5652. /* Inputs */
  5653. int nConstraint; /* Number of entries in aConstraint */
  5654. struct sqlite3_index_constraint {
  5655. int iColumn; /* Column on left-hand side of constraint */
  5656. unsigned char op; /* Constraint operator */
  5657. unsigned char usable; /* True if this constraint is usable */
  5658. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5659. } *aConstraint; /* Table of WHERE clause constraints */
  5660. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5661. struct sqlite3_index_orderby {
  5662. int iColumn; /* Column number */
  5663. unsigned char desc; /* True for DESC. False for ASC. */
  5664. } *aOrderBy; /* The ORDER BY clause */
  5665. /* Outputs */
  5666. struct sqlite3_index_constraint_usage {
  5667. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5668. unsigned char omit; /* Do not code a test for this constraint */
  5669. } *aConstraintUsage;
  5670. int idxNum; /* Number used to identify the index */
  5671. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5672. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5673. int orderByConsumed; /* True if output is already ordered */
  5674. double estimatedCost; /* Estimated cost of using this index */
  5675. };
  5676. /*
  5677. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5678. **
  5679. ** These macros defined the allowed values for the
  5680. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5681. ** an operator that is part of a constraint term in the wHERE clause of
  5682. ** a query that uses a [virtual table].
  5683. */
  5684. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5685. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5686. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5687. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5688. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5689. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5690. /*
  5691. ** CAPI3REF: Register A Virtual Table Implementation
  5692. **
  5693. ** ^These routines are used to register a new [virtual table module] name.
  5694. ** ^Module names must be registered before
  5695. ** creating a new [virtual table] using the module and before using a
  5696. ** preexisting [virtual table] for the module.
  5697. **
  5698. ** ^The module name is registered on the [database connection] specified
  5699. ** by the first parameter. ^The name of the module is given by the
  5700. ** second parameter. ^The third parameter is a pointer to
  5701. ** the implementation of the [virtual table module]. ^The fourth
  5702. ** parameter is an arbitrary client data pointer that is passed through
  5703. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5704. ** when a new virtual table is be being created or reinitialized.
  5705. **
  5706. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5707. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5708. ** invoke the destructor function (if it is not NULL) when SQLite
  5709. ** no longer needs the pClientData pointer. ^The destructor will also
  5710. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5711. ** ^The sqlite3_create_module()
  5712. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5713. ** destructor.
  5714. */
  5715. SQLITE_API int sqlite3_create_module(
  5716. sqlite3 *db, /* SQLite connection to register module with */
  5717. const char *zName, /* Name of the module */
  5718. const sqlite3_module *p, /* Methods for the module */
  5719. void *pClientData /* Client data for xCreate/xConnect */
  5720. );
  5721. SQLITE_API int sqlite3_create_module_v2(
  5722. sqlite3 *db, /* SQLite connection to register module with */
  5723. const char *zName, /* Name of the module */
  5724. const sqlite3_module *p, /* Methods for the module */
  5725. void *pClientData, /* Client data for xCreate/xConnect */
  5726. void(*xDestroy)(void*) /* Module destructor function */
  5727. );
  5728. /*
  5729. ** CAPI3REF: Virtual Table Instance Object
  5730. ** KEYWORDS: sqlite3_vtab
  5731. **
  5732. ** Every [virtual table module] implementation uses a subclass
  5733. ** of this object to describe a particular instance
  5734. ** of the [virtual table]. Each subclass will
  5735. ** be tailored to the specific needs of the module implementation.
  5736. ** The purpose of this superclass is to define certain fields that are
  5737. ** common to all module implementations.
  5738. **
  5739. ** ^Virtual tables methods can set an error message by assigning a
  5740. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5741. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5742. ** prior to assigning a new string to zErrMsg. ^After the error message
  5743. ** is delivered up to the client application, the string will be automatically
  5744. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5745. */
  5746. struct sqlite3_vtab {
  5747. const sqlite3_module *pModule; /* The module for this virtual table */
  5748. int nRef; /* NO LONGER USED */
  5749. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5750. /* Virtual table implementations will typically add additional fields */
  5751. };
  5752. /*
  5753. ** CAPI3REF: Virtual Table Cursor Object
  5754. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5755. **
  5756. ** Every [virtual table module] implementation uses a subclass of the
  5757. ** following structure to describe cursors that point into the
  5758. ** [virtual table] and are used
  5759. ** to loop through the virtual table. Cursors are created using the
  5760. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5761. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5762. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5763. ** of the module. Each module implementation will define
  5764. ** the content of a cursor structure to suit its own needs.
  5765. **
  5766. ** This superclass exists in order to define fields of the cursor that
  5767. ** are common to all implementations.
  5768. */
  5769. struct sqlite3_vtab_cursor {
  5770. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5771. /* Virtual table implementations will typically add additional fields */
  5772. };
  5773. /*
  5774. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5775. **
  5776. ** ^The [xCreate] and [xConnect] methods of a
  5777. ** [virtual table module] call this interface
  5778. ** to declare the format (the names and datatypes of the columns) of
  5779. ** the virtual tables they implement.
  5780. */
  5781. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5782. /*
  5783. ** CAPI3REF: Overload A Function For A Virtual Table
  5784. **
  5785. ** ^(Virtual tables can provide alternative implementations of functions
  5786. ** using the [xFindFunction] method of the [virtual table module].
  5787. ** But global versions of those functions
  5788. ** must exist in order to be overloaded.)^
  5789. **
  5790. ** ^(This API makes sure a global version of a function with a particular
  5791. ** name and number of parameters exists. If no such function exists
  5792. ** before this API is called, a new function is created.)^ ^The implementation
  5793. ** of the new function always causes an exception to be thrown. So
  5794. ** the new function is not good for anything by itself. Its only
  5795. ** purpose is to be a placeholder function that can be overloaded
  5796. ** by a [virtual table].
  5797. */
  5798. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5799. /*
  5800. ** The interface to the virtual-table mechanism defined above (back up
  5801. ** to a comment remarkably similar to this one) is currently considered
  5802. ** to be experimental. The interface might change in incompatible ways.
  5803. ** If this is a problem for you, do not use the interface at this time.
  5804. **
  5805. ** When the virtual-table mechanism stabilizes, we will declare the
  5806. ** interface fixed, support it indefinitely, and remove this comment.
  5807. */
  5808. /*
  5809. ** CAPI3REF: A Handle To An Open BLOB
  5810. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5811. **
  5812. ** An instance of this object represents an open BLOB on which
  5813. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5814. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5815. ** and destroyed by [sqlite3_blob_close()].
  5816. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5817. ** can be used to read or write small subsections of the BLOB.
  5818. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5819. */
  5820. typedef struct sqlite3_blob sqlite3_blob;
  5821. /*
  5822. ** CAPI3REF: Open A BLOB For Incremental I/O
  5823. **
  5824. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5825. ** in row iRow, column zColumn, table zTable in database zDb;
  5826. ** in other words, the same BLOB that would be selected by:
  5827. **
  5828. ** <pre>
  5829. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5830. ** </pre>)^
  5831. **
  5832. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5833. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5834. ** ^It is not possible to open a column that is part of an index or primary
  5835. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5836. ** not possible to open a column that is part of a [child key] for writing.
  5837. **
  5838. ** ^Note that the database name is not the filename that contains
  5839. ** the database but rather the symbolic name of the database that
  5840. ** appears after the AS keyword when the database is connected using [ATTACH].
  5841. ** ^For the main database file, the database name is "main".
  5842. ** ^For TEMP tables, the database name is "temp".
  5843. **
  5844. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5845. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5846. ** to be a null pointer.)^
  5847. ** ^This function sets the [database connection] error code and message
  5848. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5849. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5850. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5851. ** regardless of the success or failure of this routine.
  5852. **
  5853. ** ^(If the row that a BLOB handle points to is modified by an
  5854. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5855. ** then the BLOB handle is marked as "expired".
  5856. ** This is true if any column of the row is changed, even a column
  5857. ** other than the one the BLOB handle is open on.)^
  5858. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5859. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5860. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5861. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5862. ** commit if the transaction continues to completion.)^
  5863. **
  5864. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5865. ** the opened blob. ^The size of a blob may not be changed by this
  5866. ** interface. Use the [UPDATE] SQL command to change the size of a
  5867. ** blob.
  5868. **
  5869. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5870. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5871. ** to create an empty, zero-filled blob in which to read or write using
  5872. ** this interface.
  5873. **
  5874. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5875. ** be released by a call to [sqlite3_blob_close()].
  5876. */
  5877. SQLITE_API int sqlite3_blob_open(
  5878. sqlite3*,
  5879. const char *zDb,
  5880. const char *zTable,
  5881. const char *zColumn,
  5882. sqlite3_int64 iRow,
  5883. int flags,
  5884. sqlite3_blob **ppBlob
  5885. );
  5886. /*
  5887. ** CAPI3REF: Move a BLOB Handle to a New Row
  5888. **
  5889. ** ^This function is used to move an existing blob handle so that it points
  5890. ** to a different row of the same database table. ^The new row is identified
  5891. ** by the rowid value passed as the second argument. Only the row can be
  5892. ** changed. ^The database, table and column on which the blob handle is open
  5893. ** remain the same. Moving an existing blob handle to a new row can be
  5894. ** faster than closing the existing handle and opening a new one.
  5895. **
  5896. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5897. ** it must exist and there must be either a blob or text value stored in
  5898. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5899. ** it does not contain a blob or text value, or if another error occurs, an
  5900. ** SQLite error code is returned and the blob handle is considered aborted.
  5901. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5902. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5903. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5904. ** always returns zero.
  5905. **
  5906. ** ^This function sets the database handle error code and message.
  5907. */
  5908. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5909. /*
  5910. ** CAPI3REF: Close A BLOB Handle
  5911. **
  5912. ** ^Closes an open [BLOB handle].
  5913. **
  5914. ** ^Closing a BLOB shall cause the current transaction to commit
  5915. ** if there are no other BLOBs, no pending prepared statements, and the
  5916. ** database connection is in [autocommit mode].
  5917. ** ^If any writes were made to the BLOB, they might be held in cache
  5918. ** until the close operation if they will fit.
  5919. **
  5920. ** ^(Closing the BLOB often forces the changes
  5921. ** out to disk and so if any I/O errors occur, they will likely occur
  5922. ** at the time when the BLOB is closed. Any errors that occur during
  5923. ** closing are reported as a non-zero return value.)^
  5924. **
  5925. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5926. ** an error code, the BLOB is still closed.)^
  5927. **
  5928. ** ^Calling this routine with a null pointer (such as would be returned
  5929. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5930. */
  5931. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5932. /*
  5933. ** CAPI3REF: Return The Size Of An Open BLOB
  5934. **
  5935. ** ^Returns the size in bytes of the BLOB accessible via the
  5936. ** successfully opened [BLOB handle] in its only argument. ^The
  5937. ** incremental blob I/O routines can only read or overwriting existing
  5938. ** blob content; they cannot change the size of a blob.
  5939. **
  5940. ** This routine only works on a [BLOB handle] which has been created
  5941. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5942. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5943. ** to this routine results in undefined and probably undesirable behavior.
  5944. */
  5945. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5946. /*
  5947. ** CAPI3REF: Read Data From A BLOB Incrementally
  5948. **
  5949. ** ^(This function is used to read data from an open [BLOB handle] into a
  5950. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5951. ** from the open BLOB, starting at offset iOffset.)^
  5952. **
  5953. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5954. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5955. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5956. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5957. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5958. **
  5959. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5960. ** error code of [SQLITE_ABORT].
  5961. **
  5962. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5963. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5964. **
  5965. ** This routine only works on a [BLOB handle] which has been created
  5966. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5967. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5968. ** to this routine results in undefined and probably undesirable behavior.
  5969. **
  5970. ** See also: [sqlite3_blob_write()].
  5971. */
  5972. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5973. /*
  5974. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5975. **
  5976. ** ^This function is used to write data into an open [BLOB handle] from a
  5977. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5978. ** into the open BLOB, starting at offset iOffset.
  5979. **
  5980. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5981. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5982. ** this function returns [SQLITE_READONLY].
  5983. **
  5984. ** ^This function may only modify the contents of the BLOB; it is
  5985. ** not possible to increase the size of a BLOB using this API.
  5986. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5987. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5988. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5989. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5990. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5991. **
  5992. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5993. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5994. ** before the [BLOB handle] expired are not rolled back by the
  5995. ** expiration of the handle, though of course those changes might
  5996. ** have been overwritten by the statement that expired the BLOB handle
  5997. ** or by other independent statements.
  5998. **
  5999. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6000. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6001. **
  6002. ** This routine only works on a [BLOB handle] which has been created
  6003. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6004. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6005. ** to this routine results in undefined and probably undesirable behavior.
  6006. **
  6007. ** See also: [sqlite3_blob_read()].
  6008. */
  6009. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6010. /*
  6011. ** CAPI3REF: Virtual File System Objects
  6012. **
  6013. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6014. ** that SQLite uses to interact
  6015. ** with the underlying operating system. Most SQLite builds come with a
  6016. ** single default VFS that is appropriate for the host computer.
  6017. ** New VFSes can be registered and existing VFSes can be unregistered.
  6018. ** The following interfaces are provided.
  6019. **
  6020. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6021. ** ^Names are case sensitive.
  6022. ** ^Names are zero-terminated UTF-8 strings.
  6023. ** ^If there is no match, a NULL pointer is returned.
  6024. ** ^If zVfsName is NULL then the default VFS is returned.
  6025. **
  6026. ** ^New VFSes are registered with sqlite3_vfs_register().
  6027. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6028. ** ^The same VFS can be registered multiple times without injury.
  6029. ** ^To make an existing VFS into the default VFS, register it again
  6030. ** with the makeDflt flag set. If two different VFSes with the
  6031. ** same name are registered, the behavior is undefined. If a
  6032. ** VFS is registered with a name that is NULL or an empty string,
  6033. ** then the behavior is undefined.
  6034. **
  6035. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6036. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6037. ** the default. The choice for the new VFS is arbitrary.)^
  6038. */
  6039. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  6040. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6041. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  6042. /*
  6043. ** CAPI3REF: Mutexes
  6044. **
  6045. ** The SQLite core uses these routines for thread
  6046. ** synchronization. Though they are intended for internal
  6047. ** use by SQLite, code that links against SQLite is
  6048. ** permitted to use any of these routines.
  6049. **
  6050. ** The SQLite source code contains multiple implementations
  6051. ** of these mutex routines. An appropriate implementation
  6052. ** is selected automatically at compile-time. ^(The following
  6053. ** implementations are available in the SQLite core:
  6054. **
  6055. ** <ul>
  6056. ** <li> SQLITE_MUTEX_PTHREADS
  6057. ** <li> SQLITE_MUTEX_W32
  6058. ** <li> SQLITE_MUTEX_NOOP
  6059. ** </ul>)^
  6060. **
  6061. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  6062. ** that does no real locking and is appropriate for use in
  6063. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  6064. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6065. ** and Windows.
  6066. **
  6067. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6068. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6069. ** implementation is included with the library. In this case the
  6070. ** application must supply a custom mutex implementation using the
  6071. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6072. ** before calling sqlite3_initialize() or any other public sqlite3_
  6073. ** function that calls sqlite3_initialize().)^
  6074. **
  6075. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6076. ** mutex and returns a pointer to it. ^If it returns NULL
  6077. ** that means that a mutex could not be allocated. ^SQLite
  6078. ** will unwind its stack and return an error. ^(The argument
  6079. ** to sqlite3_mutex_alloc() is one of these integer constants:
  6080. **
  6081. ** <ul>
  6082. ** <li> SQLITE_MUTEX_FAST
  6083. ** <li> SQLITE_MUTEX_RECURSIVE
  6084. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6085. ** <li> SQLITE_MUTEX_STATIC_MEM
  6086. ** <li> SQLITE_MUTEX_STATIC_MEM2
  6087. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6088. ** <li> SQLITE_MUTEX_STATIC_LRU
  6089. ** <li> SQLITE_MUTEX_STATIC_LRU2
  6090. ** </ul>)^
  6091. **
  6092. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6093. ** cause sqlite3_mutex_alloc() to create
  6094. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6095. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6096. ** The mutex implementation does not need to make a distinction
  6097. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6098. ** not want to. ^SQLite will only request a recursive mutex in
  6099. ** cases where it really needs one. ^If a faster non-recursive mutex
  6100. ** implementation is available on the host platform, the mutex subsystem
  6101. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6102. **
  6103. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6104. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6105. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  6106. ** used by the current version of SQLite. Future versions of SQLite
  6107. ** may add additional static mutexes. Static mutexes are for internal
  6108. ** use by SQLite only. Applications that use SQLite mutexes should
  6109. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6110. ** SQLITE_MUTEX_RECURSIVE.
  6111. **
  6112. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6113. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6114. ** returns a different mutex on every call. ^But for the static
  6115. ** mutex types, the same mutex is returned on every call that has
  6116. ** the same type number.
  6117. **
  6118. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6119. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  6120. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  6121. ** use when they are deallocated. Attempting to deallocate a static
  6122. ** mutex results in undefined behavior. ^SQLite never deallocates
  6123. ** a static mutex.
  6124. **
  6125. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6126. ** to enter a mutex. ^If another thread is already within the mutex,
  6127. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6128. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6129. ** upon successful entry. ^(Mutexes created using
  6130. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6131. ** In such cases the,
  6132. ** mutex must be exited an equal number of times before another thread
  6133. ** can enter.)^ ^(If the same thread tries to enter any other
  6134. ** kind of mutex more than once, the behavior is undefined.
  6135. ** SQLite will never exhibit
  6136. ** such behavior in its own use of mutexes.)^
  6137. **
  6138. ** ^(Some systems (for example, Windows 95) do not support the operation
  6139. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6140. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6141. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  6142. **
  6143. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6144. ** previously entered by the same thread. ^(The behavior
  6145. ** is undefined if the mutex is not currently entered by the
  6146. ** calling thread or is not currently allocated. SQLite will
  6147. ** never do either.)^
  6148. **
  6149. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6150. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6151. ** behave as no-ops.
  6152. **
  6153. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6154. */
  6155. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  6156. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  6157. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  6158. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  6159. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  6160. /*
  6161. ** CAPI3REF: Mutex Methods Object
  6162. **
  6163. ** An instance of this structure defines the low-level routines
  6164. ** used to allocate and use mutexes.
  6165. **
  6166. ** Usually, the default mutex implementations provided by SQLite are
  6167. ** sufficient, however the user has the option of substituting a custom
  6168. ** implementation for specialized deployments or systems for which SQLite
  6169. ** does not provide a suitable implementation. In this case, the user
  6170. ** creates and populates an instance of this structure to pass
  6171. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6172. ** Additionally, an instance of this structure can be used as an
  6173. ** output variable when querying the system for the current mutex
  6174. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6175. **
  6176. ** ^The xMutexInit method defined by this structure is invoked as
  6177. ** part of system initialization by the sqlite3_initialize() function.
  6178. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6179. ** effective call to [sqlite3_initialize()].
  6180. **
  6181. ** ^The xMutexEnd method defined by this structure is invoked as
  6182. ** part of system shutdown by the sqlite3_shutdown() function. The
  6183. ** implementation of this method is expected to release all outstanding
  6184. ** resources obtained by the mutex methods implementation, especially
  6185. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6186. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6187. **
  6188. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6189. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6190. ** xMutexNotheld) implement the following interfaces (respectively):
  6191. **
  6192. ** <ul>
  6193. ** <li> [sqlite3_mutex_alloc()] </li>
  6194. ** <li> [sqlite3_mutex_free()] </li>
  6195. ** <li> [sqlite3_mutex_enter()] </li>
  6196. ** <li> [sqlite3_mutex_try()] </li>
  6197. ** <li> [sqlite3_mutex_leave()] </li>
  6198. ** <li> [sqlite3_mutex_held()] </li>
  6199. ** <li> [sqlite3_mutex_notheld()] </li>
  6200. ** </ul>)^
  6201. **
  6202. ** The only difference is that the public sqlite3_XXX functions enumerated
  6203. ** above silently ignore any invocations that pass a NULL pointer instead
  6204. ** of a valid mutex handle. The implementations of the methods defined
  6205. ** by this structure are not required to handle this case, the results
  6206. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6207. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6208. ** it is passed a NULL pointer).
  6209. **
  6210. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  6211. ** invoke xMutexInit() multiple times within the same process and without
  6212. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6213. ** xMutexInit() must be no-ops.
  6214. **
  6215. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6216. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  6217. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6218. ** memory allocation for a fast or recursive mutex.
  6219. **
  6220. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6221. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6222. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6223. ** prior to returning.
  6224. */
  6225. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6226. struct sqlite3_mutex_methods {
  6227. int (*xMutexInit)(void);
  6228. int (*xMutexEnd)(void);
  6229. sqlite3_mutex *(*xMutexAlloc)(int);
  6230. void (*xMutexFree)(sqlite3_mutex *);
  6231. void (*xMutexEnter)(sqlite3_mutex *);
  6232. int (*xMutexTry)(sqlite3_mutex *);
  6233. void (*xMutexLeave)(sqlite3_mutex *);
  6234. int (*xMutexHeld)(sqlite3_mutex *);
  6235. int (*xMutexNotheld)(sqlite3_mutex *);
  6236. };
  6237. /*
  6238. ** CAPI3REF: Mutex Verification Routines
  6239. **
  6240. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6241. ** are intended for use inside assert() statements. ^The SQLite core
  6242. ** never uses these routines except inside an assert() and applications
  6243. ** are advised to follow the lead of the core. ^The SQLite core only
  6244. ** provides implementations for these routines when it is compiled
  6245. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  6246. ** are only required to provide these routines if SQLITE_DEBUG is
  6247. ** defined and if NDEBUG is not defined.
  6248. **
  6249. ** ^These routines should return true if the mutex in their argument
  6250. ** is held or not held, respectively, by the calling thread.
  6251. **
  6252. ** ^The implementation is not required to provide versions of these
  6253. ** routines that actually work. If the implementation does not provide working
  6254. ** versions of these routines, it should at least provide stubs that always
  6255. ** return true so that one does not get spurious assertion failures.
  6256. **
  6257. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  6258. ** the routine should return 1. This seems counter-intuitive since
  6259. ** clearly the mutex cannot be held if it does not exist. But
  6260. ** the reason the mutex does not exist is because the build is not
  6261. ** using mutexes. And we do not want the assert() containing the
  6262. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6263. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  6264. ** interface should also return 1 when given a NULL pointer.
  6265. */
  6266. #ifndef NDEBUG
  6267. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6268. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6269. #endif
  6270. /*
  6271. ** CAPI3REF: Mutex Types
  6272. **
  6273. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6274. ** which is one of these integer constants.
  6275. **
  6276. ** The set of static mutexes may change from one SQLite release to the
  6277. ** next. Applications that override the built-in mutex logic must be
  6278. ** prepared to accommodate additional static mutexes.
  6279. */
  6280. #define SQLITE_MUTEX_FAST 0
  6281. #define SQLITE_MUTEX_RECURSIVE 1
  6282. #define SQLITE_MUTEX_STATIC_MASTER 2
  6283. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6284. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6285. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6286. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6287. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6288. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6289. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6290. /*
  6291. ** CAPI3REF: Retrieve the mutex for a database connection
  6292. **
  6293. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6294. ** serializes access to the [database connection] given in the argument
  6295. ** when the [threading mode] is Serialized.
  6296. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6297. ** routine returns a NULL pointer.
  6298. */
  6299. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6300. /*
  6301. ** CAPI3REF: Low-Level Control Of Database Files
  6302. **
  6303. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6304. ** xFileControl method for the [sqlite3_io_methods] object associated
  6305. ** with a particular database identified by the second argument. ^The
  6306. ** name of the database is "main" for the main database or "temp" for the
  6307. ** TEMP database, or the name that appears after the AS keyword for
  6308. ** databases that are added using the [ATTACH] SQL command.
  6309. ** ^A NULL pointer can be used in place of "main" to refer to the
  6310. ** main database file.
  6311. ** ^The third and fourth parameters to this routine
  6312. ** are passed directly through to the second and third parameters of
  6313. ** the xFileControl method. ^The return value of the xFileControl
  6314. ** method becomes the return value of this routine.
  6315. **
  6316. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6317. ** a pointer to the underlying [sqlite3_file] object to be written into
  6318. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6319. ** case is a short-circuit path which does not actually invoke the
  6320. ** underlying sqlite3_io_methods.xFileControl method.
  6321. **
  6322. ** ^If the second parameter (zDbName) does not match the name of any
  6323. ** open database file, then SQLITE_ERROR is returned. ^This error
  6324. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6325. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6326. ** also return SQLITE_ERROR. There is no way to distinguish between
  6327. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6328. ** xFileControl method.
  6329. **
  6330. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6331. */
  6332. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6333. /*
  6334. ** CAPI3REF: Testing Interface
  6335. **
  6336. ** ^The sqlite3_test_control() interface is used to read out internal
  6337. ** state of SQLite and to inject faults into SQLite for testing
  6338. ** purposes. ^The first parameter is an operation code that determines
  6339. ** the number, meaning, and operation of all subsequent parameters.
  6340. **
  6341. ** This interface is not for use by applications. It exists solely
  6342. ** for verifying the correct operation of the SQLite library. Depending
  6343. ** on how the SQLite library is compiled, this interface might not exist.
  6344. **
  6345. ** The details of the operation codes, their meanings, the parameters
  6346. ** they take, and what they do are all subject to change without notice.
  6347. ** Unlike most of the SQLite API, this function is not guaranteed to
  6348. ** operate consistently from one release to the next.
  6349. */
  6350. SQLITE_API int sqlite3_test_control(int op, ...);
  6351. /*
  6352. ** CAPI3REF: Testing Interface Operation Codes
  6353. **
  6354. ** These constants are the valid operation code parameters used
  6355. ** as the first argument to [sqlite3_test_control()].
  6356. **
  6357. ** These parameters and their meanings are subject to change
  6358. ** without notice. These values are for testing purposes only.
  6359. ** Applications should not use any of these parameters or the
  6360. ** [sqlite3_test_control()] interface.
  6361. */
  6362. #define SQLITE_TESTCTRL_FIRST 5
  6363. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6364. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6365. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6366. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6367. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6368. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6369. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6370. #define SQLITE_TESTCTRL_ASSERT 12
  6371. #define SQLITE_TESTCTRL_ALWAYS 13
  6372. #define SQLITE_TESTCTRL_RESERVE 14
  6373. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6374. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6375. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6376. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6377. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  6378. #define SQLITE_TESTCTRL_LAST 19
  6379. /*
  6380. ** CAPI3REF: SQLite Runtime Status
  6381. **
  6382. ** ^This interface is used to retrieve runtime status information
  6383. ** about the performance of SQLite, and optionally to reset various
  6384. ** highwater marks. ^The first argument is an integer code for
  6385. ** the specific parameter to measure. ^(Recognized integer codes
  6386. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6387. ** ^The current value of the parameter is returned into *pCurrent.
  6388. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6389. ** resetFlag is true, then the highest record value is reset after
  6390. ** *pHighwater is written. ^(Some parameters do not record the highest
  6391. ** value. For those parameters
  6392. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6393. ** ^(Other parameters record only the highwater mark and not the current
  6394. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6395. **
  6396. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  6397. ** non-zero [error code] on failure.
  6398. **
  6399. ** This routine is threadsafe but is not atomic. This routine can be
  6400. ** called while other threads are running the same or different SQLite
  6401. ** interfaces. However the values returned in *pCurrent and
  6402. ** *pHighwater reflect the status of SQLite at different points in time
  6403. ** and it is possible that another thread might change the parameter
  6404. ** in between the times when *pCurrent and *pHighwater are written.
  6405. **
  6406. ** See also: [sqlite3_db_status()]
  6407. */
  6408. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6409. /*
  6410. ** CAPI3REF: Status Parameters
  6411. ** KEYWORDS: {status parameters}
  6412. **
  6413. ** These integer constants designate various run-time status parameters
  6414. ** that can be returned by [sqlite3_status()].
  6415. **
  6416. ** <dl>
  6417. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6418. ** <dd>This parameter is the current amount of memory checked out
  6419. ** using [sqlite3_malloc()], either directly or indirectly. The
  6420. ** figure includes calls made to [sqlite3_malloc()] by the application
  6421. ** and internal memory usage by the SQLite library. Scratch memory
  6422. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6423. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6424. ** this parameter. The amount returned is the sum of the allocation
  6425. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6426. **
  6427. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6428. ** <dd>This parameter records the largest memory allocation request
  6429. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6430. ** internal equivalents). Only the value returned in the
  6431. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6432. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6433. **
  6434. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6435. ** <dd>This parameter records the number of separate memory allocations
  6436. ** currently checked out.</dd>)^
  6437. **
  6438. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6439. ** <dd>This parameter returns the number of pages used out of the
  6440. ** [pagecache memory allocator] that was configured using
  6441. ** [SQLITE_CONFIG_PAGECACHE]. The
  6442. ** value returned is in pages, not in bytes.</dd>)^
  6443. **
  6444. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6445. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6446. ** <dd>This parameter returns the number of bytes of page cache
  6447. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6448. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6449. ** returned value includes allocations that overflowed because they
  6450. ** where too large (they were larger than the "sz" parameter to
  6451. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6452. ** no space was left in the page cache.</dd>)^
  6453. **
  6454. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6455. ** <dd>This parameter records the largest memory allocation request
  6456. ** handed to [pagecache memory allocator]. Only the value returned in the
  6457. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6458. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6459. **
  6460. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6461. ** <dd>This parameter returns the number of allocations used out of the
  6462. ** [scratch memory allocator] configured using
  6463. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6464. ** in bytes. Since a single thread may only have one scratch allocation
  6465. ** outstanding at time, this parameter also reports the number of threads
  6466. ** using scratch memory at the same time.</dd>)^
  6467. **
  6468. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6469. ** <dd>This parameter returns the number of bytes of scratch memory
  6470. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6471. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6472. ** returned include overflows because the requested allocation was too
  6473. ** larger (that is, because the requested allocation was larger than the
  6474. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6475. ** slots were available.
  6476. ** </dd>)^
  6477. **
  6478. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6479. ** <dd>This parameter records the largest memory allocation request
  6480. ** handed to [scratch memory allocator]. Only the value returned in the
  6481. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6482. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6483. **
  6484. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6485. ** <dd>This parameter records the deepest parser stack. It is only
  6486. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6487. ** </dl>
  6488. **
  6489. ** New status parameters may be added from time to time.
  6490. */
  6491. #define SQLITE_STATUS_MEMORY_USED 0
  6492. #define SQLITE_STATUS_PAGECACHE_USED 1
  6493. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6494. #define SQLITE_STATUS_SCRATCH_USED 3
  6495. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6496. #define SQLITE_STATUS_MALLOC_SIZE 5
  6497. #define SQLITE_STATUS_PARSER_STACK 6
  6498. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6499. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6500. #define SQLITE_STATUS_MALLOC_COUNT 9
  6501. /*
  6502. ** CAPI3REF: Database Connection Status
  6503. **
  6504. ** ^This interface is used to retrieve runtime status information
  6505. ** about a single [database connection]. ^The first argument is the
  6506. ** database connection object to be interrogated. ^The second argument
  6507. ** is an integer constant, taken from the set of
  6508. ** [SQLITE_DBSTATUS options], that
  6509. ** determines the parameter to interrogate. The set of
  6510. ** [SQLITE_DBSTATUS options] is likely
  6511. ** to grow in future releases of SQLite.
  6512. **
  6513. ** ^The current value of the requested parameter is written into *pCur
  6514. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6515. ** the resetFlg is true, then the highest instantaneous value is
  6516. ** reset back down to the current value.
  6517. **
  6518. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6519. ** non-zero [error code] on failure.
  6520. **
  6521. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6522. */
  6523. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6524. /*
  6525. ** CAPI3REF: Status Parameters for database connections
  6526. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6527. **
  6528. ** These constants are the available integer "verbs" that can be passed as
  6529. ** the second argument to the [sqlite3_db_status()] interface.
  6530. **
  6531. ** New verbs may be added in future releases of SQLite. Existing verbs
  6532. ** might be discontinued. Applications should check the return code from
  6533. ** [sqlite3_db_status()] to make sure that the call worked.
  6534. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6535. ** if a discontinued or unsupported verb is invoked.
  6536. **
  6537. ** <dl>
  6538. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6539. ** <dd>This parameter returns the number of lookaside memory slots currently
  6540. ** checked out.</dd>)^
  6541. **
  6542. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6543. ** <dd>This parameter returns the number malloc attempts that were
  6544. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6545. ** the current value is always zero.)^
  6546. **
  6547. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6548. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6549. ** <dd>This parameter returns the number malloc attempts that might have
  6550. ** been satisfied using lookaside memory but failed due to the amount of
  6551. ** memory requested being larger than the lookaside slot size.
  6552. ** Only the high-water value is meaningful;
  6553. ** the current value is always zero.)^
  6554. **
  6555. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6556. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6557. ** <dd>This parameter returns the number malloc attempts that might have
  6558. ** been satisfied using lookaside memory but failed due to all lookaside
  6559. ** memory already being in use.
  6560. ** Only the high-water value is meaningful;
  6561. ** the current value is always zero.)^
  6562. **
  6563. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6564. ** <dd>This parameter returns the approximate number of of bytes of heap
  6565. ** memory used by all pager caches associated with the database connection.)^
  6566. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6567. **
  6568. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6569. ** <dd>This parameter returns the approximate number of of bytes of heap
  6570. ** memory used to store the schema for all databases associated
  6571. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6572. ** ^The full amount of memory used by the schemas is reported, even if the
  6573. ** schema memory is shared with other database connections due to
  6574. ** [shared cache mode] being enabled.
  6575. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6576. **
  6577. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6578. ** <dd>This parameter returns the approximate number of of bytes of heap
  6579. ** and lookaside memory used by all prepared statements associated with
  6580. ** the database connection.)^
  6581. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6582. ** </dd>
  6583. **
  6584. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6585. ** <dd>This parameter returns the number of pager cache hits that have
  6586. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6587. ** is always 0.
  6588. ** </dd>
  6589. **
  6590. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6591. ** <dd>This parameter returns the number of pager cache misses that have
  6592. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6593. ** is always 0.
  6594. ** </dd>
  6595. **
  6596. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6597. ** <dd>This parameter returns the number of dirty cache entries that have
  6598. ** been written to disk. Specifically, the number of pages written to the
  6599. ** wal file in wal mode databases, or the number of pages written to the
  6600. ** database file in rollback mode databases. Any pages written as part of
  6601. ** transaction rollback or database recovery operations are not included.
  6602. ** If an IO or other error occurs while writing a page to disk, the effect
  6603. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6604. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6605. ** </dd>
  6606. ** </dl>
  6607. */
  6608. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6609. #define SQLITE_DBSTATUS_CACHE_USED 1
  6610. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6611. #define SQLITE_DBSTATUS_STMT_USED 3
  6612. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6613. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6614. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6615. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6616. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6617. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6618. #define SQLITE_DBSTATUS_MAX 9 /* Largest defined DBSTATUS */
  6619. /*
  6620. ** CAPI3REF: Prepared Statement Status
  6621. **
  6622. ** ^(Each prepared statement maintains various
  6623. ** [SQLITE_STMTSTATUS counters] that measure the number
  6624. ** of times it has performed specific operations.)^ These counters can
  6625. ** be used to monitor the performance characteristics of the prepared
  6626. ** statements. For example, if the number of table steps greatly exceeds
  6627. ** the number of table searches or result rows, that would tend to indicate
  6628. ** that the prepared statement is using a full table scan rather than
  6629. ** an index.
  6630. **
  6631. ** ^(This interface is used to retrieve and reset counter values from
  6632. ** a [prepared statement]. The first argument is the prepared statement
  6633. ** object to be interrogated. The second argument
  6634. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6635. ** to be interrogated.)^
  6636. ** ^The current value of the requested counter is returned.
  6637. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6638. ** interface call returns.
  6639. **
  6640. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6641. */
  6642. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6643. /*
  6644. ** CAPI3REF: Status Parameters for prepared statements
  6645. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6646. **
  6647. ** These preprocessor macros define integer codes that name counter
  6648. ** values associated with the [sqlite3_stmt_status()] interface.
  6649. ** The meanings of the various counters are as follows:
  6650. **
  6651. ** <dl>
  6652. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6653. ** <dd>^This is the number of times that SQLite has stepped forward in
  6654. ** a table as part of a full table scan. Large numbers for this counter
  6655. ** may indicate opportunities for performance improvement through
  6656. ** careful use of indices.</dd>
  6657. **
  6658. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6659. ** <dd>^This is the number of sort operations that have occurred.
  6660. ** A non-zero value in this counter may indicate an opportunity to
  6661. ** improvement performance through careful use of indices.</dd>
  6662. **
  6663. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6664. ** <dd>^This is the number of rows inserted into transient indices that
  6665. ** were created automatically in order to help joins run faster.
  6666. ** A non-zero value in this counter may indicate an opportunity to
  6667. ** improvement performance by adding permanent indices that do not
  6668. ** need to be reinitialized each time the statement is run.</dd>
  6669. ** </dl>
  6670. */
  6671. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6672. #define SQLITE_STMTSTATUS_SORT 2
  6673. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6674. /*
  6675. ** CAPI3REF: Custom Page Cache Object
  6676. **
  6677. ** The sqlite3_pcache type is opaque. It is implemented by
  6678. ** the pluggable module. The SQLite core has no knowledge of
  6679. ** its size or internal structure and never deals with the
  6680. ** sqlite3_pcache object except by holding and passing pointers
  6681. ** to the object.
  6682. **
  6683. ** See [sqlite3_pcache_methods2] for additional information.
  6684. */
  6685. typedef struct sqlite3_pcache sqlite3_pcache;
  6686. /*
  6687. ** CAPI3REF: Custom Page Cache Object
  6688. **
  6689. ** The sqlite3_pcache_page object represents a single page in the
  6690. ** page cache. The page cache will allocate instances of this
  6691. ** object. Various methods of the page cache use pointers to instances
  6692. ** of this object as parameters or as their return value.
  6693. **
  6694. ** See [sqlite3_pcache_methods2] for additional information.
  6695. */
  6696. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6697. struct sqlite3_pcache_page {
  6698. void *pBuf; /* The content of the page */
  6699. void *pExtra; /* Extra information associated with the page */
  6700. };
  6701. /*
  6702. ** CAPI3REF: Application Defined Page Cache.
  6703. ** KEYWORDS: {page cache}
  6704. **
  6705. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6706. ** register an alternative page cache implementation by passing in an
  6707. ** instance of the sqlite3_pcache_methods2 structure.)^
  6708. ** In many applications, most of the heap memory allocated by
  6709. ** SQLite is used for the page cache.
  6710. ** By implementing a
  6711. ** custom page cache using this API, an application can better control
  6712. ** the amount of memory consumed by SQLite, the way in which
  6713. ** that memory is allocated and released, and the policies used to
  6714. ** determine exactly which parts of a database file are cached and for
  6715. ** how long.
  6716. **
  6717. ** The alternative page cache mechanism is an
  6718. ** extreme measure that is only needed by the most demanding applications.
  6719. ** The built-in page cache is recommended for most uses.
  6720. **
  6721. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6722. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6723. ** the application may discard the parameter after the call to
  6724. ** [sqlite3_config()] returns.)^
  6725. **
  6726. ** [[the xInit() page cache method]]
  6727. ** ^(The xInit() method is called once for each effective
  6728. ** call to [sqlite3_initialize()])^
  6729. ** (usually only once during the lifetime of the process). ^(The xInit()
  6730. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6731. ** The intent of the xInit() method is to set up global data structures
  6732. ** required by the custom page cache implementation.
  6733. ** ^(If the xInit() method is NULL, then the
  6734. ** built-in default page cache is used instead of the application defined
  6735. ** page cache.)^
  6736. **
  6737. ** [[the xShutdown() page cache method]]
  6738. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6739. ** It can be used to clean up
  6740. ** any outstanding resources before process shutdown, if required.
  6741. ** ^The xShutdown() method may be NULL.
  6742. **
  6743. ** ^SQLite automatically serializes calls to the xInit method,
  6744. ** so the xInit method need not be threadsafe. ^The
  6745. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6746. ** not need to be threadsafe either. All other methods must be threadsafe
  6747. ** in multithreaded applications.
  6748. **
  6749. ** ^SQLite will never invoke xInit() more than once without an intervening
  6750. ** call to xShutdown().
  6751. **
  6752. ** [[the xCreate() page cache methods]]
  6753. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6754. ** SQLite will typically create one cache instance for each open database file,
  6755. ** though this is not guaranteed. ^The
  6756. ** first parameter, szPage, is the size in bytes of the pages that must
  6757. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6758. ** second parameter szExtra is a number of bytes of extra storage
  6759. ** associated with each page cache entry. ^The szExtra parameter will
  6760. ** a number less than 250. SQLite will use the
  6761. ** extra szExtra bytes on each page to store metadata about the underlying
  6762. ** database page on disk. The value passed into szExtra depends
  6763. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6764. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6765. ** created will be used to cache database pages of a file stored on disk, or
  6766. ** false if it is used for an in-memory database. The cache implementation
  6767. ** does not have to do anything special based with the value of bPurgeable;
  6768. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6769. ** never invoke xUnpin() except to deliberately delete a page.
  6770. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6771. ** false will always have the "discard" flag set to true.
  6772. ** ^Hence, a cache created with bPurgeable false will
  6773. ** never contain any unpinned pages.
  6774. **
  6775. ** [[the xCachesize() page cache method]]
  6776. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6777. ** suggested maximum cache-size (number of pages stored by) the cache
  6778. ** instance passed as the first argument. This is the value configured using
  6779. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6780. ** parameter, the implementation is not required to do anything with this
  6781. ** value; it is advisory only.
  6782. **
  6783. ** [[the xPagecount() page cache methods]]
  6784. ** The xPagecount() method must return the number of pages currently
  6785. ** stored in the cache, both pinned and unpinned.
  6786. **
  6787. ** [[the xFetch() page cache methods]]
  6788. ** The xFetch() method locates a page in the cache and returns a pointer to
  6789. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6790. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6791. ** pointer to a buffer of szPage bytes used to store the content of a
  6792. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6793. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6794. ** for each entry in the page cache.
  6795. **
  6796. ** The page to be fetched is determined by the key. ^The minimum key value
  6797. ** is 1. After it has been retrieved using xFetch, the page is considered
  6798. ** to be "pinned".
  6799. **
  6800. ** If the requested page is already in the page cache, then the page cache
  6801. ** implementation must return a pointer to the page buffer with its content
  6802. ** intact. If the requested page is not already in the cache, then the
  6803. ** cache implementation should use the value of the createFlag
  6804. ** parameter to help it determined what action to take:
  6805. **
  6806. ** <table border=1 width=85% align=center>
  6807. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6808. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6809. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6810. ** Otherwise return NULL.
  6811. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6812. ** NULL if allocating a new page is effectively impossible.
  6813. ** </table>
  6814. **
  6815. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6816. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6817. ** failed.)^ In between the to xFetch() calls, SQLite may
  6818. ** attempt to unpin one or more cache pages by spilling the content of
  6819. ** pinned pages to disk and synching the operating system disk cache.
  6820. **
  6821. ** [[the xUnpin() page cache method]]
  6822. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6823. ** as its second argument. If the third parameter, discard, is non-zero,
  6824. ** then the page must be evicted from the cache.
  6825. ** ^If the discard parameter is
  6826. ** zero, then the page may be discarded or retained at the discretion of
  6827. ** page cache implementation. ^The page cache implementation
  6828. ** may choose to evict unpinned pages at any time.
  6829. **
  6830. ** The cache must not perform any reference counting. A single
  6831. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6832. ** to xFetch().
  6833. **
  6834. ** [[the xRekey() page cache methods]]
  6835. ** The xRekey() method is used to change the key value associated with the
  6836. ** page passed as the second argument. If the cache
  6837. ** previously contains an entry associated with newKey, it must be
  6838. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6839. ** to be pinned.
  6840. **
  6841. ** When SQLite calls the xTruncate() method, the cache must discard all
  6842. ** existing cache entries with page numbers (keys) greater than or equal
  6843. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6844. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6845. ** they can be safely discarded.
  6846. **
  6847. ** [[the xDestroy() page cache method]]
  6848. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6849. ** All resources associated with the specified cache should be freed. ^After
  6850. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6851. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6852. ** functions.
  6853. **
  6854. ** [[the xShrink() page cache method]]
  6855. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6856. ** free up as much of heap memory as possible. The page cache implementation
  6857. ** is not obligated to free any memory, but well-behaved implementations should
  6858. ** do their best.
  6859. */
  6860. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6861. struct sqlite3_pcache_methods2 {
  6862. int iVersion;
  6863. void *pArg;
  6864. int (*xInit)(void*);
  6865. void (*xShutdown)(void*);
  6866. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6867. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6868. int (*xPagecount)(sqlite3_pcache*);
  6869. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6870. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6871. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6872. unsigned oldKey, unsigned newKey);
  6873. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6874. void (*xDestroy)(sqlite3_pcache*);
  6875. void (*xShrink)(sqlite3_pcache*);
  6876. };
  6877. /*
  6878. ** This is the obsolete pcache_methods object that has now been replaced
  6879. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6880. ** retained in the header file for backwards compatibility only.
  6881. */
  6882. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6883. struct sqlite3_pcache_methods {
  6884. void *pArg;
  6885. int (*xInit)(void*);
  6886. void (*xShutdown)(void*);
  6887. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6888. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6889. int (*xPagecount)(sqlite3_pcache*);
  6890. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6891. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6892. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6893. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6894. void (*xDestroy)(sqlite3_pcache*);
  6895. };
  6896. /*
  6897. ** CAPI3REF: Online Backup Object
  6898. **
  6899. ** The sqlite3_backup object records state information about an ongoing
  6900. ** online backup operation. ^The sqlite3_backup object is created by
  6901. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6902. ** [sqlite3_backup_finish()].
  6903. **
  6904. ** See Also: [Using the SQLite Online Backup API]
  6905. */
  6906. typedef struct sqlite3_backup sqlite3_backup;
  6907. /*
  6908. ** CAPI3REF: Online Backup API.
  6909. **
  6910. ** The backup API copies the content of one database into another.
  6911. ** It is useful either for creating backups of databases or
  6912. ** for copying in-memory databases to or from persistent files.
  6913. **
  6914. ** See Also: [Using the SQLite Online Backup API]
  6915. **
  6916. ** ^SQLite holds a write transaction open on the destination database file
  6917. ** for the duration of the backup operation.
  6918. ** ^The source database is read-locked only while it is being read;
  6919. ** it is not locked continuously for the entire backup operation.
  6920. ** ^Thus, the backup may be performed on a live source database without
  6921. ** preventing other database connections from
  6922. ** reading or writing to the source database while the backup is underway.
  6923. **
  6924. ** ^(To perform a backup operation:
  6925. ** <ol>
  6926. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6927. ** backup,
  6928. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6929. ** the data between the two databases, and finally
  6930. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6931. ** associated with the backup operation.
  6932. ** </ol>)^
  6933. ** There should be exactly one call to sqlite3_backup_finish() for each
  6934. ** successful call to sqlite3_backup_init().
  6935. **
  6936. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6937. **
  6938. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6939. ** [database connection] associated with the destination database
  6940. ** and the database name, respectively.
  6941. ** ^The database name is "main" for the main database, "temp" for the
  6942. ** temporary database, or the name specified after the AS keyword in
  6943. ** an [ATTACH] statement for an attached database.
  6944. ** ^The S and M arguments passed to
  6945. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6946. ** and database name of the source database, respectively.
  6947. ** ^The source and destination [database connections] (parameters S and D)
  6948. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6949. ** an error.
  6950. **
  6951. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6952. ** returned and an error code and error message are stored in the
  6953. ** destination [database connection] D.
  6954. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6955. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6956. ** [sqlite3_errmsg16()] functions.
  6957. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6958. ** [sqlite3_backup] object.
  6959. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6960. ** sqlite3_backup_finish() functions to perform the specified backup
  6961. ** operation.
  6962. **
  6963. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6964. **
  6965. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6966. ** the source and destination databases specified by [sqlite3_backup] object B.
  6967. ** ^If N is negative, all remaining source pages are copied.
  6968. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6969. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6970. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6971. ** from source to destination, then it returns [SQLITE_DONE].
  6972. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6973. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6974. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6975. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6976. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6977. **
  6978. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6979. ** <ol>
  6980. ** <li> the destination database was opened read-only, or
  6981. ** <li> the destination database is using write-ahead-log journaling
  6982. ** and the destination and source page sizes differ, or
  6983. ** <li> the destination database is an in-memory database and the
  6984. ** destination and source page sizes differ.
  6985. ** </ol>)^
  6986. **
  6987. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6988. ** the [sqlite3_busy_handler | busy-handler function]
  6989. ** is invoked (if one is specified). ^If the
  6990. ** busy-handler returns non-zero before the lock is available, then
  6991. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6992. ** sqlite3_backup_step() can be retried later. ^If the source
  6993. ** [database connection]
  6994. ** is being used to write to the source database when sqlite3_backup_step()
  6995. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6996. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6997. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6998. ** [SQLITE_READONLY] is returned, then
  6999. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7000. ** errors are considered fatal.)^ The application must accept
  7001. ** that the backup operation has failed and pass the backup operation handle
  7002. ** to the sqlite3_backup_finish() to release associated resources.
  7003. **
  7004. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7005. ** on the destination file. ^The exclusive lock is not released until either
  7006. ** sqlite3_backup_finish() is called or the backup operation is complete
  7007. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7008. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7009. ** lasts for the duration of the sqlite3_backup_step() call.
  7010. ** ^Because the source database is not locked between calls to
  7011. ** sqlite3_backup_step(), the source database may be modified mid-way
  7012. ** through the backup process. ^If the source database is modified by an
  7013. ** external process or via a database connection other than the one being
  7014. ** used by the backup operation, then the backup will be automatically
  7015. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7016. ** database is modified by the using the same database connection as is used
  7017. ** by the backup operation, then the backup database is automatically
  7018. ** updated at the same time.
  7019. **
  7020. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7021. **
  7022. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7023. ** application wishes to abandon the backup operation, the application
  7024. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7025. ** ^The sqlite3_backup_finish() interfaces releases all
  7026. ** resources associated with the [sqlite3_backup] object.
  7027. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7028. ** active write-transaction on the destination database is rolled back.
  7029. ** The [sqlite3_backup] object is invalid
  7030. ** and may not be used following a call to sqlite3_backup_finish().
  7031. **
  7032. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7033. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7034. ** sqlite3_backup_step() completed.
  7035. ** ^If an out-of-memory condition or IO error occurred during any prior
  7036. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7037. ** sqlite3_backup_finish() returns the corresponding [error code].
  7038. **
  7039. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7040. ** is not a permanent error and does not affect the return value of
  7041. ** sqlite3_backup_finish().
  7042. **
  7043. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  7044. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7045. **
  7046. ** ^Each call to sqlite3_backup_step() sets two values inside
  7047. ** the [sqlite3_backup] object: the number of pages still to be backed
  7048. ** up and the total number of pages in the source database file.
  7049. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  7050. ** retrieve these two values, respectively.
  7051. **
  7052. ** ^The values returned by these functions are only updated by
  7053. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  7054. ** operation, then the values are not updated to account for any extra
  7055. ** pages that need to be updated or the size of the source database file
  7056. ** changing.
  7057. **
  7058. ** <b>Concurrent Usage of Database Handles</b>
  7059. **
  7060. ** ^The source [database connection] may be used by the application for other
  7061. ** purposes while a backup operation is underway or being initialized.
  7062. ** ^If SQLite is compiled and configured to support threadsafe database
  7063. ** connections, then the source database connection may be used concurrently
  7064. ** from within other threads.
  7065. **
  7066. ** However, the application must guarantee that the destination
  7067. ** [database connection] is not passed to any other API (by any thread) after
  7068. ** sqlite3_backup_init() is called and before the corresponding call to
  7069. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7070. ** if the application incorrectly accesses the destination [database connection]
  7071. ** and so no error code is reported, but the operations may malfunction
  7072. ** nevertheless. Use of the destination database connection while a
  7073. ** backup is in progress might also also cause a mutex deadlock.
  7074. **
  7075. ** If running in [shared cache mode], the application must
  7076. ** guarantee that the shared cache used by the destination database
  7077. ** is not accessed while the backup is running. In practice this means
  7078. ** that the application must guarantee that the disk file being
  7079. ** backed up to is not accessed by any connection within the process,
  7080. ** not just the specific connection that was passed to sqlite3_backup_init().
  7081. **
  7082. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7083. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7084. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7085. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7086. ** same time as another thread is invoking sqlite3_backup_step() it is
  7087. ** possible that they return invalid values.
  7088. */
  7089. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  7090. sqlite3 *pDest, /* Destination database handle */
  7091. const char *zDestName, /* Destination database name */
  7092. sqlite3 *pSource, /* Source database handle */
  7093. const char *zSourceName /* Source database name */
  7094. );
  7095. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7096. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  7097. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  7098. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  7099. /*
  7100. ** CAPI3REF: Unlock Notification
  7101. **
  7102. ** ^When running in shared-cache mode, a database operation may fail with
  7103. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7104. ** individual tables within the shared-cache cannot be obtained. See
  7105. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7106. ** ^This API may be used to register a callback that SQLite will invoke
  7107. ** when the connection currently holding the required lock relinquishes it.
  7108. ** ^This API is only available if the library was compiled with the
  7109. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7110. **
  7111. ** See Also: [Using the SQLite Unlock Notification Feature].
  7112. **
  7113. ** ^Shared-cache locks are released when a database connection concludes
  7114. ** its current transaction, either by committing it or rolling it back.
  7115. **
  7116. ** ^When a connection (known as the blocked connection) fails to obtain a
  7117. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7118. ** identity of the database connection (the blocking connection) that
  7119. ** has locked the required resource is stored internally. ^After an
  7120. ** application receives an SQLITE_LOCKED error, it may call the
  7121. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7122. ** the first argument to register for a callback that will be invoked
  7123. ** when the blocking connections current transaction is concluded. ^The
  7124. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7125. ** call that concludes the blocking connections transaction.
  7126. **
  7127. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7128. ** there is a chance that the blocking connection will have already
  7129. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7130. ** If this happens, then the specified callback is invoked immediately,
  7131. ** from within the call to sqlite3_unlock_notify().)^
  7132. **
  7133. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7134. ** shared-cache table, and more than one other connection currently holds
  7135. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7136. ** the other connections to use as the blocking connection.
  7137. **
  7138. ** ^(There may be at most one unlock-notify callback registered by a
  7139. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7140. ** blocked connection already has a registered unlock-notify callback,
  7141. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7142. ** called with a NULL pointer as its second argument, then any existing
  7143. ** unlock-notify callback is canceled. ^The blocked connections
  7144. ** unlock-notify callback may also be canceled by closing the blocked
  7145. ** connection using [sqlite3_close()].
  7146. **
  7147. ** The unlock-notify callback is not reentrant. If an application invokes
  7148. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7149. ** crash or deadlock may be the result.
  7150. **
  7151. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7152. ** returns SQLITE_OK.
  7153. **
  7154. ** <b>Callback Invocation Details</b>
  7155. **
  7156. ** When an unlock-notify callback is registered, the application provides a
  7157. ** single void* pointer that is passed to the callback when it is invoked.
  7158. ** However, the signature of the callback function allows SQLite to pass
  7159. ** it an array of void* context pointers. The first argument passed to
  7160. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7161. ** and the second is the number of entries in the array.
  7162. **
  7163. ** When a blocking connections transaction is concluded, there may be
  7164. ** more than one blocked connection that has registered for an unlock-notify
  7165. ** callback. ^If two or more such blocked connections have specified the
  7166. ** same callback function, then instead of invoking the callback function
  7167. ** multiple times, it is invoked once with the set of void* context pointers
  7168. ** specified by the blocked connections bundled together into an array.
  7169. ** This gives the application an opportunity to prioritize any actions
  7170. ** related to the set of unblocked database connections.
  7171. **
  7172. ** <b>Deadlock Detection</b>
  7173. **
  7174. ** Assuming that after registering for an unlock-notify callback a
  7175. ** database waits for the callback to be issued before taking any further
  7176. ** action (a reasonable assumption), then using this API may cause the
  7177. ** application to deadlock. For example, if connection X is waiting for
  7178. ** connection Y's transaction to be concluded, and similarly connection
  7179. ** Y is waiting on connection X's transaction, then neither connection
  7180. ** will proceed and the system may remain deadlocked indefinitely.
  7181. **
  7182. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7183. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7184. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7185. ** unlock-notify callback is registered. The system is said to be in
  7186. ** a deadlocked state if connection A has registered for an unlock-notify
  7187. ** callback on the conclusion of connection B's transaction, and connection
  7188. ** B has itself registered for an unlock-notify callback when connection
  7189. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7190. ** the system is also considered to be deadlocked if connection B has
  7191. ** registered for an unlock-notify callback on the conclusion of connection
  7192. ** C's transaction, where connection C is waiting on connection A. ^Any
  7193. ** number of levels of indirection are allowed.
  7194. **
  7195. ** <b>The "DROP TABLE" Exception</b>
  7196. **
  7197. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7198. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7199. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7200. ** SQLite checks if there are any currently executing SELECT statements
  7201. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7202. ** returned. In this case there is no "blocking connection", so invoking
  7203. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7204. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7205. ** or "DROP INDEX" query, an infinite loop might be the result.
  7206. **
  7207. ** One way around this problem is to check the extended error code returned
  7208. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7209. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7210. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7211. ** SQLITE_LOCKED.)^
  7212. */
  7213. SQLITE_API int sqlite3_unlock_notify(
  7214. sqlite3 *pBlocked, /* Waiting connection */
  7215. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7216. void *pNotifyArg /* Argument to pass to xNotify */
  7217. );
  7218. /*
  7219. ** CAPI3REF: String Comparison
  7220. **
  7221. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7222. ** and extensions to compare the contents of two buffers containing UTF-8
  7223. ** strings in a case-independent fashion, using the same definition of "case
  7224. ** independence" that SQLite uses internally when comparing identifiers.
  7225. */
  7226. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7227. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7228. /*
  7229. ** CAPI3REF: String Globbing
  7230. *
  7231. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7232. ** the glob pattern P, and it returns non-zero if string X does not match
  7233. ** the glob pattern P. ^The definition of glob pattern matching used in
  7234. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7235. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7236. ** sensitive.
  7237. **
  7238. ** Note that this routine returns zero on a match and non-zero if the strings
  7239. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7240. */
  7241. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  7242. /*
  7243. ** CAPI3REF: Error Logging Interface
  7244. **
  7245. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7246. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7247. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7248. ** used with [sqlite3_snprintf()] to generate the final output string.
  7249. **
  7250. ** The sqlite3_log() interface is intended for use by extensions such as
  7251. ** virtual tables, collating functions, and SQL functions. While there is
  7252. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7253. ** is considered bad form.
  7254. **
  7255. ** The zFormat string must not be NULL.
  7256. **
  7257. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7258. ** will not use dynamically allocated memory. The log message is stored in
  7259. ** a fixed-length buffer on the stack. If the log message is longer than
  7260. ** a few hundred characters, it will be truncated to the length of the
  7261. ** buffer.
  7262. */
  7263. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7264. /*
  7265. ** CAPI3REF: Write-Ahead Log Commit Hook
  7266. **
  7267. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7268. ** will be invoked each time a database connection commits data to a
  7269. ** [write-ahead log] (i.e. whenever a transaction is committed in
  7270. ** [journal_mode | journal_mode=WAL mode]).
  7271. **
  7272. ** ^The callback is invoked by SQLite after the commit has taken place and
  7273. ** the associated write-lock on the database released, so the implementation
  7274. ** may read, write or [checkpoint] the database as required.
  7275. **
  7276. ** ^The first parameter passed to the callback function when it is invoked
  7277. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7278. ** registering the callback. ^The second is a copy of the database handle.
  7279. ** ^The third parameter is the name of the database that was written to -
  7280. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7281. ** is the number of pages currently in the write-ahead log file,
  7282. ** including those that were just committed.
  7283. **
  7284. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7285. ** code is returned, that error will propagate back up through the
  7286. ** SQLite code base to cause the statement that provoked the callback
  7287. ** to report an error, though the commit will have still occurred. If the
  7288. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7289. ** that does not correspond to any valid SQLite error code, the results
  7290. ** are undefined.
  7291. **
  7292. ** A single database handle may have at most a single write-ahead log callback
  7293. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7294. ** previously registered write-ahead log callback. ^Note that the
  7295. ** [sqlite3_wal_autocheckpoint()] interface and the
  7296. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7297. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7298. */
  7299. SQLITE_API void *sqlite3_wal_hook(
  7300. sqlite3*,
  7301. int(*)(void *,sqlite3*,const char*,int),
  7302. void*
  7303. );
  7304. /*
  7305. ** CAPI3REF: Configure an auto-checkpoint
  7306. **
  7307. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7308. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7309. ** to automatically [checkpoint]
  7310. ** after committing a transaction if there are N or
  7311. ** more frames in the [write-ahead log] file. ^Passing zero or
  7312. ** a negative value as the nFrame parameter disables automatic
  7313. ** checkpoints entirely.
  7314. **
  7315. ** ^The callback registered by this function replaces any existing callback
  7316. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7317. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7318. ** configured by this function.
  7319. **
  7320. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7321. ** from SQL.
  7322. **
  7323. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7324. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7325. ** pages. The use of this interface
  7326. ** is only necessary if the default setting is found to be suboptimal
  7327. ** for a particular application.
  7328. */
  7329. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7330. /*
  7331. ** CAPI3REF: Checkpoint a database
  7332. **
  7333. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  7334. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  7335. ** empty string, then a checkpoint is run on all databases of
  7336. ** connection D. ^If the database connection D is not in
  7337. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  7338. **
  7339. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  7340. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  7341. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  7342. ** run whenever the WAL reaches a certain size threshold.
  7343. **
  7344. ** See also: [sqlite3_wal_checkpoint_v2()]
  7345. */
  7346. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7347. /*
  7348. ** CAPI3REF: Checkpoint a database
  7349. **
  7350. ** Run a checkpoint operation on WAL database zDb attached to database
  7351. ** handle db. The specific operation is determined by the value of the
  7352. ** eMode parameter:
  7353. **
  7354. ** <dl>
  7355. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7356. ** Checkpoint as many frames as possible without waiting for any database
  7357. ** readers or writers to finish. Sync the db file if all frames in the log
  7358. ** are checkpointed. This mode is the same as calling
  7359. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  7360. **
  7361. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7362. ** This mode blocks (calls the busy-handler callback) until there is no
  7363. ** database writer and all readers are reading from the most recent database
  7364. ** snapshot. It then checkpoints all frames in the log file and syncs the
  7365. ** database file. This call blocks database writers while it is running,
  7366. ** but not database readers.
  7367. **
  7368. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7369. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  7370. ** checkpointing the log file it blocks (calls the busy-handler callback)
  7371. ** until all readers are reading from the database file only. This ensures
  7372. ** that the next client to write to the database file restarts the log file
  7373. ** from the beginning. This call blocks database writers while it is running,
  7374. ** but not database readers.
  7375. ** </dl>
  7376. **
  7377. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7378. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  7379. ** the total number of checkpointed frames (including any that were already
  7380. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  7381. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  7382. ** If no values are available because of an error, they are both set to -1
  7383. ** before returning to communicate this to the caller.
  7384. **
  7385. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  7386. ** any other process is running a checkpoint operation at the same time, the
  7387. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  7388. ** busy-handler configured, it will not be invoked in this case.
  7389. **
  7390. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  7391. ** "writer" lock on the database file. If the writer lock cannot be obtained
  7392. ** immediately, and a busy-handler is configured, it is invoked and the writer
  7393. ** lock retried until either the busy-handler returns 0 or the lock is
  7394. ** successfully obtained. The busy-handler is also invoked while waiting for
  7395. ** database readers as described above. If the busy-handler returns 0 before
  7396. ** the writer lock is obtained or while waiting for database readers, the
  7397. ** checkpoint operation proceeds from that point in the same way as
  7398. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7399. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7400. **
  7401. ** If parameter zDb is NULL or points to a zero length string, then the
  7402. ** specified operation is attempted on all WAL databases. In this case the
  7403. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7404. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7405. ** attached WAL databases, the operation is still attempted on any remaining
  7406. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7407. ** error occurs while processing an attached database, processing is abandoned
  7408. ** and the error code returned to the caller immediately. If no error
  7409. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7410. ** databases, SQLITE_OK is returned.
  7411. **
  7412. ** If database zDb is the name of an attached database that is not in WAL
  7413. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7414. ** zDb is not NULL (or a zero length string) and is not the name of any
  7415. ** attached database, SQLITE_ERROR is returned to the caller.
  7416. */
  7417. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7418. sqlite3 *db, /* Database handle */
  7419. const char *zDb, /* Name of attached database (or NULL) */
  7420. int eMode, /* SQLITE_CHECKPOINT_* value */
  7421. int *pnLog, /* OUT: Size of WAL log in frames */
  7422. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7423. );
  7424. /*
  7425. ** CAPI3REF: Checkpoint operation parameters
  7426. **
  7427. ** These constants can be used as the 3rd parameter to
  7428. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7429. ** documentation for additional information about the meaning and use of
  7430. ** each of these values.
  7431. */
  7432. #define SQLITE_CHECKPOINT_PASSIVE 0
  7433. #define SQLITE_CHECKPOINT_FULL 1
  7434. #define SQLITE_CHECKPOINT_RESTART 2
  7435. /*
  7436. ** CAPI3REF: Virtual Table Interface Configuration
  7437. **
  7438. ** This function may be called by either the [xConnect] or [xCreate] method
  7439. ** of a [virtual table] implementation to configure
  7440. ** various facets of the virtual table interface.
  7441. **
  7442. ** If this interface is invoked outside the context of an xConnect or
  7443. ** xCreate virtual table method then the behavior is undefined.
  7444. **
  7445. ** At present, there is only one option that may be configured using
  7446. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7447. ** may be added in the future.
  7448. */
  7449. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7450. /*
  7451. ** CAPI3REF: Virtual Table Configuration Options
  7452. **
  7453. ** These macros define the various options to the
  7454. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7455. ** can use to customize and optimize their behavior.
  7456. **
  7457. ** <dl>
  7458. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7459. ** <dd>Calls of the form
  7460. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7461. ** where X is an integer. If X is zero, then the [virtual table] whose
  7462. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7463. ** support constraints. In this configuration (which is the default) if
  7464. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7465. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7466. ** specified as part of the users SQL statement, regardless of the actual
  7467. ** ON CONFLICT mode specified.
  7468. **
  7469. ** If X is non-zero, then the virtual table implementation guarantees
  7470. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7471. ** any modifications to internal or persistent data structures have been made.
  7472. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7473. ** is able to roll back a statement or database transaction, and abandon
  7474. ** or continue processing the current SQL statement as appropriate.
  7475. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7476. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7477. ** had been ABORT.
  7478. **
  7479. ** Virtual table implementations that are required to handle OR REPLACE
  7480. ** must do so within the [xUpdate] method. If a call to the
  7481. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7482. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7483. ** silently replace the appropriate rows within the xUpdate callback and
  7484. ** return SQLITE_OK. Or, if this is not possible, it may return
  7485. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7486. ** constraint handling.
  7487. ** </dl>
  7488. */
  7489. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7490. /*
  7491. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7492. **
  7493. ** This function may only be called from within a call to the [xUpdate] method
  7494. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7495. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7496. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7497. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7498. ** [virtual table].
  7499. */
  7500. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7501. /*
  7502. ** CAPI3REF: Conflict resolution modes
  7503. **
  7504. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7505. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7506. ** is for the SQL statement being evaluated.
  7507. **
  7508. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7509. ** return value from the [sqlite3_set_authorizer()] callback and that
  7510. ** [SQLITE_ABORT] is also a [result code].
  7511. */
  7512. #define SQLITE_ROLLBACK 1
  7513. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7514. #define SQLITE_FAIL 3
  7515. /* #define SQLITE_ABORT 4 // Also an error code */
  7516. #define SQLITE_REPLACE 5
  7517. /*
  7518. ** Undo the hack that converts floating point types to integer for
  7519. ** builds on processors without floating point support.
  7520. */
  7521. #ifdef SQLITE_OMIT_FLOATING_POINT
  7522. # undef double
  7523. #endif
  7524. #if 0
  7525. } /* End of the 'extern "C"' block */
  7526. #endif
  7527. #endif
  7528. /*
  7529. ** 2010 August 30
  7530. **
  7531. ** The author disclaims copyright to this source code. In place of
  7532. ** a legal notice, here is a blessing:
  7533. **
  7534. ** May you do good and not evil.
  7535. ** May you find forgiveness for yourself and forgive others.
  7536. ** May you share freely, never taking more than you give.
  7537. **
  7538. *************************************************************************
  7539. */
  7540. #ifndef _SQLITE3RTREE_H_
  7541. #define _SQLITE3RTREE_H_
  7542. #if 0
  7543. extern "C" {
  7544. #endif
  7545. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7546. /*
  7547. ** Register a geometry callback named zGeom that can be used as part of an
  7548. ** R-Tree geometry query as follows:
  7549. **
  7550. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7551. */
  7552. SQLITE_API int sqlite3_rtree_geometry_callback(
  7553. sqlite3 *db,
  7554. const char *zGeom,
  7555. #ifdef SQLITE_RTREE_INT_ONLY
  7556. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7557. #else
  7558. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7559. #endif
  7560. void *pContext
  7561. );
  7562. /*
  7563. ** A pointer to a structure of the following type is passed as the first
  7564. ** argument to callbacks registered using rtree_geometry_callback().
  7565. */
  7566. struct sqlite3_rtree_geometry {
  7567. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7568. int nParam; /* Size of array aParam[] */
  7569. double *aParam; /* Parameters passed to SQL geom function */
  7570. void *pUser; /* Callback implementation user data */
  7571. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7572. };
  7573. #if 0
  7574. } /* end of the 'extern "C"' block */
  7575. #endif
  7576. #endif /* ifndef _SQLITE3RTREE_H_ */
  7577. /************** End of sqlite3.h *********************************************/
  7578. /************** Continuing where we left off in sqliteInt.h ******************/
  7579. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7580. /************** Begin file hash.h ********************************************/
  7581. /*
  7582. ** 2001 September 22
  7583. **
  7584. ** The author disclaims copyright to this source code. In place of
  7585. ** a legal notice, here is a blessing:
  7586. **
  7587. ** May you do good and not evil.
  7588. ** May you find forgiveness for yourself and forgive others.
  7589. ** May you share freely, never taking more than you give.
  7590. **
  7591. *************************************************************************
  7592. ** This is the header file for the generic hash-table implementation
  7593. ** used in SQLite.
  7594. */
  7595. #ifndef _SQLITE_HASH_H_
  7596. #define _SQLITE_HASH_H_
  7597. /* Forward declarations of structures. */
  7598. typedef struct Hash Hash;
  7599. typedef struct HashElem HashElem;
  7600. /* A complete hash table is an instance of the following structure.
  7601. ** The internals of this structure are intended to be opaque -- client
  7602. ** code should not attempt to access or modify the fields of this structure
  7603. ** directly. Change this structure only by using the routines below.
  7604. ** However, some of the "procedures" and "functions" for modifying and
  7605. ** accessing this structure are really macros, so we can't really make
  7606. ** this structure opaque.
  7607. **
  7608. ** All elements of the hash table are on a single doubly-linked list.
  7609. ** Hash.first points to the head of this list.
  7610. **
  7611. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7612. ** the global doubly-linked list. The contents of the bucket are the
  7613. ** element pointed to plus the next _ht.count-1 elements in the list.
  7614. **
  7615. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7616. ** by a linear search of the global list. For small tables, the
  7617. ** Hash.ht table is never allocated because if there are few elements
  7618. ** in the table, it is faster to do a linear search than to manage
  7619. ** the hash table.
  7620. */
  7621. struct Hash {
  7622. unsigned int htsize; /* Number of buckets in the hash table */
  7623. unsigned int count; /* Number of entries in this table */
  7624. HashElem *first; /* The first element of the array */
  7625. struct _ht { /* the hash table */
  7626. int count; /* Number of entries with this hash */
  7627. HashElem *chain; /* Pointer to first entry with this hash */
  7628. } *ht;
  7629. };
  7630. /* Each element in the hash table is an instance of the following
  7631. ** structure. All elements are stored on a single doubly-linked list.
  7632. **
  7633. ** Again, this structure is intended to be opaque, but it can't really
  7634. ** be opaque because it is used by macros.
  7635. */
  7636. struct HashElem {
  7637. HashElem *next, *prev; /* Next and previous elements in the table */
  7638. void *data; /* Data associated with this element */
  7639. const char *pKey; int nKey; /* Key associated with this element */
  7640. };
  7641. /*
  7642. ** Access routines. To delete, insert a NULL pointer.
  7643. */
  7644. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7645. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7646. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7647. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7648. /*
  7649. ** Macros for looping over all elements of a hash table. The idiom is
  7650. ** like this:
  7651. **
  7652. ** Hash h;
  7653. ** HashElem *p;
  7654. ** ...
  7655. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7656. ** SomeStructure *pData = sqliteHashData(p);
  7657. ** // do something with pData
  7658. ** }
  7659. */
  7660. #define sqliteHashFirst(H) ((H)->first)
  7661. #define sqliteHashNext(E) ((E)->next)
  7662. #define sqliteHashData(E) ((E)->data)
  7663. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7664. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7665. /*
  7666. ** Number of entries in a hash table
  7667. */
  7668. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7669. #endif /* _SQLITE_HASH_H_ */
  7670. /************** End of hash.h ************************************************/
  7671. /************** Continuing where we left off in sqliteInt.h ******************/
  7672. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7673. /************** Begin file parse.h *******************************************/
  7674. #define TK_SEMI 1
  7675. #define TK_EXPLAIN 2
  7676. #define TK_QUERY 3
  7677. #define TK_PLAN 4
  7678. #define TK_BEGIN 5
  7679. #define TK_TRANSACTION 6
  7680. #define TK_DEFERRED 7
  7681. #define TK_IMMEDIATE 8
  7682. #define TK_EXCLUSIVE 9
  7683. #define TK_COMMIT 10
  7684. #define TK_END 11
  7685. #define TK_ROLLBACK 12
  7686. #define TK_SAVEPOINT 13
  7687. #define TK_RELEASE 14
  7688. #define TK_TO 15
  7689. #define TK_TABLE 16
  7690. #define TK_CREATE 17
  7691. #define TK_IF 18
  7692. #define TK_NOT 19
  7693. #define TK_EXISTS 20
  7694. #define TK_TEMP 21
  7695. #define TK_LP 22
  7696. #define TK_RP 23
  7697. #define TK_AS 24
  7698. #define TK_COMMA 25
  7699. #define TK_ID 26
  7700. #define TK_INDEXED 27
  7701. #define TK_ABORT 28
  7702. #define TK_ACTION 29
  7703. #define TK_AFTER 30
  7704. #define TK_ANALYZE 31
  7705. #define TK_ASC 32
  7706. #define TK_ATTACH 33
  7707. #define TK_BEFORE 34
  7708. #define TK_BY 35
  7709. #define TK_CASCADE 36
  7710. #define TK_CAST 37
  7711. #define TK_COLUMNKW 38
  7712. #define TK_CONFLICT 39
  7713. #define TK_DATABASE 40
  7714. #define TK_DESC 41
  7715. #define TK_DETACH 42
  7716. #define TK_EACH 43
  7717. #define TK_FAIL 44
  7718. #define TK_FOR 45
  7719. #define TK_IGNORE 46
  7720. #define TK_INITIALLY 47
  7721. #define TK_INSTEAD 48
  7722. #define TK_LIKE_KW 49
  7723. #define TK_MATCH 50
  7724. #define TK_NO 51
  7725. #define TK_KEY 52
  7726. #define TK_OF 53
  7727. #define TK_OFFSET 54
  7728. #define TK_PRAGMA 55
  7729. #define TK_RAISE 56
  7730. #define TK_REPLACE 57
  7731. #define TK_RESTRICT 58
  7732. #define TK_ROW 59
  7733. #define TK_TRIGGER 60
  7734. #define TK_VACUUM 61
  7735. #define TK_VIEW 62
  7736. #define TK_VIRTUAL 63
  7737. #define TK_REINDEX 64
  7738. #define TK_RENAME 65
  7739. #define TK_CTIME_KW 66
  7740. #define TK_ANY 67
  7741. #define TK_OR 68
  7742. #define TK_AND 69
  7743. #define TK_IS 70
  7744. #define TK_BETWEEN 71
  7745. #define TK_IN 72
  7746. #define TK_ISNULL 73
  7747. #define TK_NOTNULL 74
  7748. #define TK_NE 75
  7749. #define TK_EQ 76
  7750. #define TK_GT 77
  7751. #define TK_LE 78
  7752. #define TK_LT 79
  7753. #define TK_GE 80
  7754. #define TK_ESCAPE 81
  7755. #define TK_BITAND 82
  7756. #define TK_BITOR 83
  7757. #define TK_LSHIFT 84
  7758. #define TK_RSHIFT 85
  7759. #define TK_PLUS 86
  7760. #define TK_MINUS 87
  7761. #define TK_STAR 88
  7762. #define TK_SLASH 89
  7763. #define TK_REM 90
  7764. #define TK_CONCAT 91
  7765. #define TK_COLLATE 92
  7766. #define TK_BITNOT 93
  7767. #define TK_STRING 94
  7768. #define TK_JOIN_KW 95
  7769. #define TK_CONSTRAINT 96
  7770. #define TK_DEFAULT 97
  7771. #define TK_NULL 98
  7772. #define TK_PRIMARY 99
  7773. #define TK_UNIQUE 100
  7774. #define TK_CHECK 101
  7775. #define TK_REFERENCES 102
  7776. #define TK_AUTOINCR 103
  7777. #define TK_ON 104
  7778. #define TK_INSERT 105
  7779. #define TK_DELETE 106
  7780. #define TK_UPDATE 107
  7781. #define TK_SET 108
  7782. #define TK_DEFERRABLE 109
  7783. #define TK_FOREIGN 110
  7784. #define TK_DROP 111
  7785. #define TK_UNION 112
  7786. #define TK_ALL 113
  7787. #define TK_EXCEPT 114
  7788. #define TK_INTERSECT 115
  7789. #define TK_SELECT 116
  7790. #define TK_DISTINCT 117
  7791. #define TK_DOT 118
  7792. #define TK_FROM 119
  7793. #define TK_JOIN 120
  7794. #define TK_USING 121
  7795. #define TK_ORDER 122
  7796. #define TK_GROUP 123
  7797. #define TK_HAVING 124
  7798. #define TK_LIMIT 125
  7799. #define TK_WHERE 126
  7800. #define TK_INTO 127
  7801. #define TK_VALUES 128
  7802. #define TK_INTEGER 129
  7803. #define TK_FLOAT 130
  7804. #define TK_BLOB 131
  7805. #define TK_REGISTER 132
  7806. #define TK_VARIABLE 133
  7807. #define TK_CASE 134
  7808. #define TK_WHEN 135
  7809. #define TK_THEN 136
  7810. #define TK_ELSE 137
  7811. #define TK_INDEX 138
  7812. #define TK_ALTER 139
  7813. #define TK_ADD 140
  7814. #define TK_TO_TEXT 141
  7815. #define TK_TO_BLOB 142
  7816. #define TK_TO_NUMERIC 143
  7817. #define TK_TO_INT 144
  7818. #define TK_TO_REAL 145
  7819. #define TK_ISNOT 146
  7820. #define TK_END_OF_FILE 147
  7821. #define TK_ILLEGAL 148
  7822. #define TK_SPACE 149
  7823. #define TK_UNCLOSED_STRING 150
  7824. #define TK_FUNCTION 151
  7825. #define TK_COLUMN 152
  7826. #define TK_AGG_FUNCTION 153
  7827. #define TK_AGG_COLUMN 154
  7828. #define TK_CONST_FUNC 155
  7829. #define TK_UMINUS 156
  7830. #define TK_UPLUS 157
  7831. /************** End of parse.h ***********************************************/
  7832. /************** Continuing where we left off in sqliteInt.h ******************/
  7833. #include <stdio.h>
  7834. #include <stdlib.h>
  7835. #include <string.h>
  7836. #include <assert.h>
  7837. #include <stddef.h>
  7838. /*
  7839. ** If compiling for a processor that lacks floating point support,
  7840. ** substitute integer for floating-point
  7841. */
  7842. #ifdef SQLITE_OMIT_FLOATING_POINT
  7843. # define double sqlite_int64
  7844. # define float sqlite_int64
  7845. # define LONGDOUBLE_TYPE sqlite_int64
  7846. # ifndef SQLITE_BIG_DBL
  7847. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7848. # endif
  7849. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7850. # define SQLITE_OMIT_TRACE 1
  7851. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7852. # undef SQLITE_HAVE_ISNAN
  7853. #endif
  7854. #ifndef SQLITE_BIG_DBL
  7855. # define SQLITE_BIG_DBL (1e99)
  7856. #endif
  7857. /*
  7858. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7859. ** afterward. Having this macro allows us to cause the C compiler
  7860. ** to omit code used by TEMP tables without messy #ifndef statements.
  7861. */
  7862. #ifdef SQLITE_OMIT_TEMPDB
  7863. #define OMIT_TEMPDB 1
  7864. #else
  7865. #define OMIT_TEMPDB 0
  7866. #endif
  7867. /*
  7868. ** The "file format" number is an integer that is incremented whenever
  7869. ** the VDBE-level file format changes. The following macros define the
  7870. ** the default file format for new databases and the maximum file format
  7871. ** that the library can read.
  7872. */
  7873. #define SQLITE_MAX_FILE_FORMAT 4
  7874. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7875. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7876. #endif
  7877. /*
  7878. ** Determine whether triggers are recursive by default. This can be
  7879. ** changed at run-time using a pragma.
  7880. */
  7881. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7882. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7883. #endif
  7884. /*
  7885. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7886. ** on the command-line
  7887. */
  7888. #ifndef SQLITE_TEMP_STORE
  7889. # define SQLITE_TEMP_STORE 1
  7890. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  7891. #endif
  7892. /*
  7893. ** GCC does not define the offsetof() macro so we'll have to do it
  7894. ** ourselves.
  7895. */
  7896. #ifndef offsetof
  7897. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7898. #endif
  7899. /*
  7900. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7901. ** not, there are still machines out there that use EBCDIC.)
  7902. */
  7903. #if 'A' == '\301'
  7904. # define SQLITE_EBCDIC 1
  7905. #else
  7906. # define SQLITE_ASCII 1
  7907. #endif
  7908. /*
  7909. ** Integers of known sizes. These typedefs might change for architectures
  7910. ** where the sizes very. Preprocessor macros are available so that the
  7911. ** types can be conveniently redefined at compile-type. Like this:
  7912. **
  7913. ** cc '-DUINTPTR_TYPE=long long int' ...
  7914. */
  7915. #ifndef UINT32_TYPE
  7916. # ifdef HAVE_UINT32_T
  7917. # define UINT32_TYPE uint32_t
  7918. # else
  7919. # define UINT32_TYPE unsigned int
  7920. # endif
  7921. #endif
  7922. #ifndef UINT16_TYPE
  7923. # ifdef HAVE_UINT16_T
  7924. # define UINT16_TYPE uint16_t
  7925. # else
  7926. # define UINT16_TYPE unsigned short int
  7927. # endif
  7928. #endif
  7929. #ifndef INT16_TYPE
  7930. # ifdef HAVE_INT16_T
  7931. # define INT16_TYPE int16_t
  7932. # else
  7933. # define INT16_TYPE short int
  7934. # endif
  7935. #endif
  7936. #ifndef UINT8_TYPE
  7937. # ifdef HAVE_UINT8_T
  7938. # define UINT8_TYPE uint8_t
  7939. # else
  7940. # define UINT8_TYPE unsigned char
  7941. # endif
  7942. #endif
  7943. #ifndef INT8_TYPE
  7944. # ifdef HAVE_INT8_T
  7945. # define INT8_TYPE int8_t
  7946. # else
  7947. # define INT8_TYPE signed char
  7948. # endif
  7949. #endif
  7950. #ifndef LONGDOUBLE_TYPE
  7951. # define LONGDOUBLE_TYPE long double
  7952. #endif
  7953. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7954. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7955. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7956. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7957. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7958. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7959. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7960. /*
  7961. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7962. ** that can be stored in a u32 without loss of data. The value
  7963. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  7964. ** have to specify the value in the less intuitive manner shown:
  7965. */
  7966. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  7967. /*
  7968. ** The datatype used to store estimates of the number of rows in a
  7969. ** table or index. This is an unsigned integer type. For 99.9% of
  7970. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  7971. ** can be used at compile-time if desired.
  7972. */
  7973. #ifdef SQLITE_64BIT_STATS
  7974. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  7975. #else
  7976. typedef u32 tRowcnt; /* 32-bit is the default */
  7977. #endif
  7978. /*
  7979. ** Macros to determine whether the machine is big or little endian,
  7980. ** evaluated at runtime.
  7981. */
  7982. #ifdef SQLITE_AMALGAMATION
  7983. SQLITE_PRIVATE const int sqlite3one = 1;
  7984. #else
  7985. SQLITE_PRIVATE const int sqlite3one;
  7986. #endif
  7987. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  7988. || defined(__x86_64) || defined(__x86_64__)
  7989. # define SQLITE_BIGENDIAN 0
  7990. # define SQLITE_LITTLEENDIAN 1
  7991. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  7992. #else
  7993. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  7994. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  7995. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  7996. #endif
  7997. /*
  7998. ** Constants for the largest and smallest possible 64-bit signed integers.
  7999. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8000. ** compilers.
  8001. */
  8002. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8003. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8004. /*
  8005. ** Round up a number to the next larger multiple of 8. This is used
  8006. ** to force 8-byte alignment on 64-bit architectures.
  8007. */
  8008. #define ROUND8(x) (((x)+7)&~7)
  8009. /*
  8010. ** Round down to the nearest multiple of 8
  8011. */
  8012. #define ROUNDDOWN8(x) ((x)&~7)
  8013. /*
  8014. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8015. ** macro is used only within assert() to verify that the code gets
  8016. ** all alignment restrictions correct.
  8017. **
  8018. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8019. ** underlying malloc() implemention might return us 4-byte aligned
  8020. ** pointers. In that case, only verify 4-byte alignment.
  8021. */
  8022. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8023. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8024. #else
  8025. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8026. #endif
  8027. /*
  8028. ** Disable MMAP on platforms where it is known to not work
  8029. */
  8030. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8031. # undef SQLITE_MAX_MMAP_SIZE
  8032. # define SQLITE_MAX_MMAP_SIZE 0
  8033. #endif
  8034. /*
  8035. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8036. */
  8037. #ifdef __APPLE__
  8038. # include <TargetConditionals.h>
  8039. # if TARGET_OS_IPHONE
  8040. # undef SQLITE_MAX_MMAP_SIZE
  8041. # define SQLITE_MAX_MMAP_SIZE 0
  8042. # endif
  8043. #endif
  8044. #ifndef SQLITE_MAX_MMAP_SIZE
  8045. # if defined(__linux__) \
  8046. || defined(_WIN32) \
  8047. || (defined(__APPLE__) && defined(__MACH__)) \
  8048. || defined(__sun)
  8049. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8050. # else
  8051. # define SQLITE_MAX_MMAP_SIZE 0
  8052. # endif
  8053. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8054. #endif
  8055. /*
  8056. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8057. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8058. ** not exceed the maximum mmap size.
  8059. */
  8060. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8061. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8062. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8063. #endif
  8064. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8065. # undef SQLITE_DEFAULT_MMAP_SIZE
  8066. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8067. #endif
  8068. /*
  8069. ** An instance of the following structure is used to store the busy-handler
  8070. ** callback for a given sqlite handle.
  8071. **
  8072. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8073. ** callback for the database handle. Each pager opened via the sqlite
  8074. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8075. ** callback is currently invoked only from within pager.c.
  8076. */
  8077. typedef struct BusyHandler BusyHandler;
  8078. struct BusyHandler {
  8079. int (*xFunc)(void *,int); /* The busy callback */
  8080. void *pArg; /* First arg to busy callback */
  8081. int nBusy; /* Incremented with each busy call */
  8082. };
  8083. /*
  8084. ** Name of the master database table. The master database table
  8085. ** is a special table that holds the names and attributes of all
  8086. ** user tables and indices.
  8087. */
  8088. #define MASTER_NAME "sqlite_master"
  8089. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8090. /*
  8091. ** The root-page of the master database table.
  8092. */
  8093. #define MASTER_ROOT 1
  8094. /*
  8095. ** The name of the schema table.
  8096. */
  8097. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8098. /*
  8099. ** A convenience macro that returns the number of elements in
  8100. ** an array.
  8101. */
  8102. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8103. /*
  8104. ** Determine if the argument is a power of two
  8105. */
  8106. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8107. /*
  8108. ** The following value as a destructor means to use sqlite3DbFree().
  8109. ** The sqlite3DbFree() routine requires two parameters instead of the
  8110. ** one parameter that destructors normally want. So we have to introduce
  8111. ** this magic value that the code knows to handle differently. Any
  8112. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8113. ** and SQLITE_TRANSIENT.
  8114. */
  8115. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8116. /*
  8117. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8118. ** not support Writable Static Data (WSD) such as global and static variables.
  8119. ** All variables must either be on the stack or dynamically allocated from
  8120. ** the heap. When WSD is unsupported, the variable declarations scattered
  8121. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8122. ** macro is used for this purpose. And instead of referencing the variable
  8123. ** directly, we use its constant as a key to lookup the run-time allocated
  8124. ** buffer that holds real variable. The constant is also the initializer
  8125. ** for the run-time allocated buffer.
  8126. **
  8127. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8128. ** macros become no-ops and have zero performance impact.
  8129. */
  8130. #ifdef SQLITE_OMIT_WSD
  8131. #define SQLITE_WSD const
  8132. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8133. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8134. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8135. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8136. #else
  8137. #define SQLITE_WSD
  8138. #define GLOBAL(t,v) v
  8139. #define sqlite3GlobalConfig sqlite3Config
  8140. #endif
  8141. /*
  8142. ** The following macros are used to suppress compiler warnings and to
  8143. ** make it clear to human readers when a function parameter is deliberately
  8144. ** left unused within the body of a function. This usually happens when
  8145. ** a function is called via a function pointer. For example the
  8146. ** implementation of an SQL aggregate step callback may not use the
  8147. ** parameter indicating the number of arguments passed to the aggregate,
  8148. ** if it knows that this is enforced elsewhere.
  8149. **
  8150. ** When a function parameter is not used at all within the body of a function,
  8151. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8152. ** However, these macros may also be used to suppress warnings related to
  8153. ** parameters that may or may not be used depending on compilation options.
  8154. ** For example those parameters only used in assert() statements. In these
  8155. ** cases the parameters are named as per the usual conventions.
  8156. */
  8157. #define UNUSED_PARAMETER(x) (void)(x)
  8158. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8159. /*
  8160. ** Forward references to structures
  8161. */
  8162. typedef struct AggInfo AggInfo;
  8163. typedef struct AuthContext AuthContext;
  8164. typedef struct AutoincInfo AutoincInfo;
  8165. typedef struct Bitvec Bitvec;
  8166. typedef struct CollSeq CollSeq;
  8167. typedef struct Column Column;
  8168. typedef struct Db Db;
  8169. typedef struct Schema Schema;
  8170. typedef struct Expr Expr;
  8171. typedef struct ExprList ExprList;
  8172. typedef struct ExprSpan ExprSpan;
  8173. typedef struct FKey FKey;
  8174. typedef struct FuncDestructor FuncDestructor;
  8175. typedef struct FuncDef FuncDef;
  8176. typedef struct FuncDefHash FuncDefHash;
  8177. typedef struct IdList IdList;
  8178. typedef struct Index Index;
  8179. typedef struct IndexSample IndexSample;
  8180. typedef struct KeyClass KeyClass;
  8181. typedef struct KeyInfo KeyInfo;
  8182. typedef struct Lookaside Lookaside;
  8183. typedef struct LookasideSlot LookasideSlot;
  8184. typedef struct Module Module;
  8185. typedef struct NameContext NameContext;
  8186. typedef struct Parse Parse;
  8187. typedef struct RowSet RowSet;
  8188. typedef struct Savepoint Savepoint;
  8189. typedef struct Select Select;
  8190. typedef struct SelectDest SelectDest;
  8191. typedef struct SrcList SrcList;
  8192. typedef struct StrAccum StrAccum;
  8193. typedef struct Table Table;
  8194. typedef struct TableLock TableLock;
  8195. typedef struct Token Token;
  8196. typedef struct Trigger Trigger;
  8197. typedef struct TriggerPrg TriggerPrg;
  8198. typedef struct TriggerStep TriggerStep;
  8199. typedef struct UnpackedRecord UnpackedRecord;
  8200. typedef struct VTable VTable;
  8201. typedef struct VtabCtx VtabCtx;
  8202. typedef struct Walker Walker;
  8203. typedef struct WherePlan WherePlan;
  8204. typedef struct WhereInfo WhereInfo;
  8205. typedef struct WhereLevel WhereLevel;
  8206. /*
  8207. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8208. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8209. ** pointer types (i.e. FuncDef) defined above.
  8210. */
  8211. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8212. /************** Begin file btree.h *******************************************/
  8213. /*
  8214. ** 2001 September 15
  8215. **
  8216. ** The author disclaims copyright to this source code. In place of
  8217. ** a legal notice, here is a blessing:
  8218. **
  8219. ** May you do good and not evil.
  8220. ** May you find forgiveness for yourself and forgive others.
  8221. ** May you share freely, never taking more than you give.
  8222. **
  8223. *************************************************************************
  8224. ** This header file defines the interface that the sqlite B-Tree file
  8225. ** subsystem. See comments in the source code for a detailed description
  8226. ** of what each interface routine does.
  8227. */
  8228. #ifndef _BTREE_H_
  8229. #define _BTREE_H_
  8230. /* TODO: This definition is just included so other modules compile. It
  8231. ** needs to be revisited.
  8232. */
  8233. #define SQLITE_N_BTREE_META 10
  8234. /*
  8235. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8236. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8237. */
  8238. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8239. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8240. #endif
  8241. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8242. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8243. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8244. /*
  8245. ** Forward declarations of structure
  8246. */
  8247. typedef struct Btree Btree;
  8248. typedef struct BtCursor BtCursor;
  8249. typedef struct BtShared BtShared;
  8250. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8251. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8252. const char *zFilename, /* Name of database file to open */
  8253. sqlite3 *db, /* Associated database connection */
  8254. Btree **ppBtree, /* Return open Btree* here */
  8255. int flags, /* Flags */
  8256. int vfsFlags /* Flags passed through to VFS open */
  8257. );
  8258. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8259. ** following values.
  8260. **
  8261. ** NOTE: These values must match the corresponding PAGER_ values in
  8262. ** pager.h.
  8263. */
  8264. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8265. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8266. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8267. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8268. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8269. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8270. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8271. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
  8272. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8273. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8274. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8275. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8276. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8277. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8278. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8279. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8280. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8281. #endif
  8282. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8283. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8284. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8285. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8286. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8287. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8288. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8289. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8290. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8291. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8292. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8293. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8294. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8295. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8296. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8297. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8298. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8299. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8300. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8301. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8302. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8303. ** of the flags shown below.
  8304. **
  8305. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8306. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8307. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8308. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8309. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8310. ** indices.)
  8311. */
  8312. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8313. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8314. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8315. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8316. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8317. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8318. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8319. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8320. /*
  8321. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8322. ** should be one of the following values. The integer values are assigned
  8323. ** to constants so that the offset of the corresponding field in an
  8324. ** SQLite database header may be found using the following formula:
  8325. **
  8326. ** offset = 36 + (idx * 4)
  8327. **
  8328. ** For example, the free-page-count field is located at byte offset 36 of
  8329. ** the database file header. The incr-vacuum-flag field is located at
  8330. ** byte offset 64 (== 36+4*7).
  8331. */
  8332. #define BTREE_FREE_PAGE_COUNT 0
  8333. #define BTREE_SCHEMA_VERSION 1
  8334. #define BTREE_FILE_FORMAT 2
  8335. #define BTREE_DEFAULT_CACHE_SIZE 3
  8336. #define BTREE_LARGEST_ROOT_PAGE 4
  8337. #define BTREE_TEXT_ENCODING 5
  8338. #define BTREE_USER_VERSION 6
  8339. #define BTREE_INCR_VACUUM 7
  8340. #define BTREE_APPLICATION_ID 8
  8341. /*
  8342. ** Values that may be OR'd together to form the second argument of an
  8343. ** sqlite3BtreeCursorHints() call.
  8344. */
  8345. #define BTREE_BULKLOAD 0x00000001
  8346. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8347. Btree*, /* BTree containing table to open */
  8348. int iTable, /* Index of root page */
  8349. int wrFlag, /* 1 for writing. 0 for read-only */
  8350. struct KeyInfo*, /* First argument to compare function */
  8351. BtCursor *pCursor /* Space to write cursor structure */
  8352. );
  8353. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8354. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8355. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8356. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8357. BtCursor*,
  8358. UnpackedRecord *pUnKey,
  8359. i64 intKey,
  8360. int bias,
  8361. int *pRes
  8362. );
  8363. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8364. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8365. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8366. const void *pData, int nData,
  8367. int nZero, int bias, int seekResult);
  8368. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8369. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8370. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8371. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8372. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8373. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8374. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8375. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8376. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8377. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8378. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8379. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8380. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8381. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8382. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8383. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8384. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8385. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8386. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8387. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8388. #ifndef NDEBUG
  8389. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8390. #endif
  8391. #ifndef SQLITE_OMIT_BTREECOUNT
  8392. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8393. #endif
  8394. #ifdef SQLITE_TEST
  8395. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8396. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8397. #endif
  8398. #ifndef SQLITE_OMIT_WAL
  8399. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8400. #endif
  8401. /*
  8402. ** If we are not using shared cache, then there is no need to
  8403. ** use mutexes to access the BtShared structures. So make the
  8404. ** Enter and Leave procedures no-ops.
  8405. */
  8406. #ifndef SQLITE_OMIT_SHARED_CACHE
  8407. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8408. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8409. #else
  8410. # define sqlite3BtreeEnter(X)
  8411. # define sqlite3BtreeEnterAll(X)
  8412. #endif
  8413. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8414. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8415. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8416. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8417. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8418. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8419. #ifndef NDEBUG
  8420. /* These routines are used inside assert() statements only. */
  8421. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8422. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8423. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8424. #endif
  8425. #else
  8426. # define sqlite3BtreeSharable(X) 0
  8427. # define sqlite3BtreeLeave(X)
  8428. # define sqlite3BtreeEnterCursor(X)
  8429. # define sqlite3BtreeLeaveCursor(X)
  8430. # define sqlite3BtreeLeaveAll(X)
  8431. # define sqlite3BtreeHoldsMutex(X) 1
  8432. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8433. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8434. #endif
  8435. #endif /* _BTREE_H_ */
  8436. /************** End of btree.h ***********************************************/
  8437. /************** Continuing where we left off in sqliteInt.h ******************/
  8438. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8439. /************** Begin file vdbe.h ********************************************/
  8440. /*
  8441. ** 2001 September 15
  8442. **
  8443. ** The author disclaims copyright to this source code. In place of
  8444. ** a legal notice, here is a blessing:
  8445. **
  8446. ** May you do good and not evil.
  8447. ** May you find forgiveness for yourself and forgive others.
  8448. ** May you share freely, never taking more than you give.
  8449. **
  8450. *************************************************************************
  8451. ** Header file for the Virtual DataBase Engine (VDBE)
  8452. **
  8453. ** This header defines the interface to the virtual database engine
  8454. ** or VDBE. The VDBE implements an abstract machine that runs a
  8455. ** simple program to access and modify the underlying database.
  8456. */
  8457. #ifndef _SQLITE_VDBE_H_
  8458. #define _SQLITE_VDBE_H_
  8459. /* #include <stdio.h> */
  8460. /*
  8461. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8462. ** in the source file sqliteVdbe.c are allowed to see the insides
  8463. ** of this structure.
  8464. */
  8465. typedef struct Vdbe Vdbe;
  8466. /*
  8467. ** The names of the following types declared in vdbeInt.h are required
  8468. ** for the VdbeOp definition.
  8469. */
  8470. typedef struct VdbeFunc VdbeFunc;
  8471. typedef struct Mem Mem;
  8472. typedef struct SubProgram SubProgram;
  8473. /*
  8474. ** A single instruction of the virtual machine has an opcode
  8475. ** and as many as three operands. The instruction is recorded
  8476. ** as an instance of the following structure:
  8477. */
  8478. struct VdbeOp {
  8479. u8 opcode; /* What operation to perform */
  8480. signed char p4type; /* One of the P4_xxx constants for p4 */
  8481. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8482. u8 p5; /* Fifth parameter is an unsigned character */
  8483. int p1; /* First operand */
  8484. int p2; /* Second parameter (often the jump destination) */
  8485. int p3; /* The third parameter */
  8486. union { /* fourth parameter */
  8487. int i; /* Integer value if p4type==P4_INT32 */
  8488. void *p; /* Generic pointer */
  8489. char *z; /* Pointer to data for string (char array) types */
  8490. i64 *pI64; /* Used when p4type is P4_INT64 */
  8491. double *pReal; /* Used when p4type is P4_REAL */
  8492. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8493. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  8494. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8495. Mem *pMem; /* Used when p4type is P4_MEM */
  8496. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8497. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8498. int *ai; /* Used when p4type is P4_INTARRAY */
  8499. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8500. int (*xAdvance)(BtCursor *, int *);
  8501. } p4;
  8502. #ifdef SQLITE_DEBUG
  8503. char *zComment; /* Comment to improve readability */
  8504. #endif
  8505. #ifdef VDBE_PROFILE
  8506. int cnt; /* Number of times this instruction was executed */
  8507. u64 cycles; /* Total time spent executing this instruction */
  8508. #endif
  8509. };
  8510. typedef struct VdbeOp VdbeOp;
  8511. /*
  8512. ** A sub-routine used to implement a trigger program.
  8513. */
  8514. struct SubProgram {
  8515. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8516. int nOp; /* Elements in aOp[] */
  8517. int nMem; /* Number of memory cells required */
  8518. int nCsr; /* Number of cursors required */
  8519. int nOnce; /* Number of OP_Once instructions */
  8520. void *token; /* id that may be used to recursive triggers */
  8521. SubProgram *pNext; /* Next sub-program already visited */
  8522. };
  8523. /*
  8524. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8525. ** it takes up less space.
  8526. */
  8527. struct VdbeOpList {
  8528. u8 opcode; /* What operation to perform */
  8529. signed char p1; /* First operand */
  8530. signed char p2; /* Second parameter (often the jump destination) */
  8531. signed char p3; /* Third parameter */
  8532. };
  8533. typedef struct VdbeOpList VdbeOpList;
  8534. /*
  8535. ** Allowed values of VdbeOp.p4type
  8536. */
  8537. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8538. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8539. #define P4_STATIC (-2) /* Pointer to a static string */
  8540. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8541. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8542. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8543. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  8544. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8545. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8546. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8547. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8548. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8549. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8550. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8551. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8552. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8553. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8554. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8555. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8556. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8557. ** gets freed when the Vdbe is finalized so it still should be obtained
  8558. ** from a single sqliteMalloc(). But no copy is made and the calling
  8559. ** function should *not* try to free the KeyInfo.
  8560. */
  8561. #define P4_KEYINFO_HANDOFF (-16)
  8562. #define P4_KEYINFO_STATIC (-17)
  8563. /*
  8564. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8565. ** number of columns of data returned by the statement.
  8566. */
  8567. #define COLNAME_NAME 0
  8568. #define COLNAME_DECLTYPE 1
  8569. #define COLNAME_DATABASE 2
  8570. #define COLNAME_TABLE 3
  8571. #define COLNAME_COLUMN 4
  8572. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8573. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8574. #else
  8575. # ifdef SQLITE_OMIT_DECLTYPE
  8576. # define COLNAME_N 1 /* Store only the name */
  8577. # else
  8578. # define COLNAME_N 2 /* Store the name and decltype */
  8579. # endif
  8580. #endif
  8581. /*
  8582. ** The following macro converts a relative address in the p2 field
  8583. ** of a VdbeOp structure into a negative number so that
  8584. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8585. ** the macro again restores the address.
  8586. */
  8587. #define ADDR(X) (-1-(X))
  8588. /*
  8589. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8590. ** header file that defines a number for each opcode used by the VDBE.
  8591. */
  8592. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8593. /************** Begin file opcodes.h *****************************************/
  8594. /* Automatically generated. Do not edit */
  8595. /* See the mkopcodeh.awk script for details */
  8596. #define OP_Goto 1
  8597. #define OP_Gosub 2
  8598. #define OP_Return 3
  8599. #define OP_Yield 4
  8600. #define OP_HaltIfNull 5
  8601. #define OP_Halt 6
  8602. #define OP_Integer 7
  8603. #define OP_Int64 8
  8604. #define OP_Real 130 /* same as TK_FLOAT */
  8605. #define OP_String8 94 /* same as TK_STRING */
  8606. #define OP_String 9
  8607. #define OP_Null 10
  8608. #define OP_Blob 11
  8609. #define OP_Variable 12
  8610. #define OP_Move 13
  8611. #define OP_Copy 14
  8612. #define OP_SCopy 15
  8613. #define OP_ResultRow 16
  8614. #define OP_Concat 91 /* same as TK_CONCAT */
  8615. #define OP_Add 86 /* same as TK_PLUS */
  8616. #define OP_Subtract 87 /* same as TK_MINUS */
  8617. #define OP_Multiply 88 /* same as TK_STAR */
  8618. #define OP_Divide 89 /* same as TK_SLASH */
  8619. #define OP_Remainder 90 /* same as TK_REM */
  8620. #define OP_CollSeq 17
  8621. #define OP_Function 18
  8622. #define OP_BitAnd 82 /* same as TK_BITAND */
  8623. #define OP_BitOr 83 /* same as TK_BITOR */
  8624. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8625. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8626. #define OP_AddImm 20
  8627. #define OP_MustBeInt 21
  8628. #define OP_RealAffinity 22
  8629. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8630. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8631. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8632. #define OP_ToInt 144 /* same as TK_TO_INT */
  8633. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8634. #define OP_Eq 76 /* same as TK_EQ */
  8635. #define OP_Ne 75 /* same as TK_NE */
  8636. #define OP_Lt 79 /* same as TK_LT */
  8637. #define OP_Le 78 /* same as TK_LE */
  8638. #define OP_Gt 77 /* same as TK_GT */
  8639. #define OP_Ge 80 /* same as TK_GE */
  8640. #define OP_Permutation 23
  8641. #define OP_Compare 24
  8642. #define OP_Jump 25
  8643. #define OP_And 69 /* same as TK_AND */
  8644. #define OP_Or 68 /* same as TK_OR */
  8645. #define OP_Not 19 /* same as TK_NOT */
  8646. #define OP_BitNot 93 /* same as TK_BITNOT */
  8647. #define OP_Once 26
  8648. #define OP_If 27
  8649. #define OP_IfNot 28
  8650. #define OP_IsNull 73 /* same as TK_ISNULL */
  8651. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8652. #define OP_Column 29
  8653. #define OP_Affinity 30
  8654. #define OP_MakeRecord 31
  8655. #define OP_Count 32
  8656. #define OP_Savepoint 33
  8657. #define OP_AutoCommit 34
  8658. #define OP_Transaction 35
  8659. #define OP_ReadCookie 36
  8660. #define OP_SetCookie 37
  8661. #define OP_VerifyCookie 38
  8662. #define OP_OpenRead 39
  8663. #define OP_OpenWrite 40
  8664. #define OP_OpenAutoindex 41
  8665. #define OP_OpenEphemeral 42
  8666. #define OP_SorterOpen 43
  8667. #define OP_OpenPseudo 44
  8668. #define OP_Close 45
  8669. #define OP_SeekLt 46
  8670. #define OP_SeekLe 47
  8671. #define OP_SeekGe 48
  8672. #define OP_SeekGt 49
  8673. #define OP_Seek 50
  8674. #define OP_NotFound 51
  8675. #define OP_Found 52
  8676. #define OP_IsUnique 53
  8677. #define OP_NotExists 54
  8678. #define OP_Sequence 55
  8679. #define OP_NewRowid 56
  8680. #define OP_Insert 57
  8681. #define OP_InsertInt 58
  8682. #define OP_Delete 59
  8683. #define OP_ResetCount 60
  8684. #define OP_SorterCompare 61
  8685. #define OP_SorterData 62
  8686. #define OP_RowKey 63
  8687. #define OP_RowData 64
  8688. #define OP_Rowid 65
  8689. #define OP_NullRow 66
  8690. #define OP_Last 67
  8691. #define OP_SorterSort 70
  8692. #define OP_Sort 71
  8693. #define OP_Rewind 72
  8694. #define OP_SorterNext 81
  8695. #define OP_Prev 92
  8696. #define OP_Next 95
  8697. #define OP_SorterInsert 96
  8698. #define OP_IdxInsert 97
  8699. #define OP_IdxDelete 98
  8700. #define OP_IdxRowid 99
  8701. #define OP_IdxLT 100
  8702. #define OP_IdxGE 101
  8703. #define OP_Destroy 102
  8704. #define OP_Clear 103
  8705. #define OP_CreateIndex 104
  8706. #define OP_CreateTable 105
  8707. #define OP_ParseSchema 106
  8708. #define OP_LoadAnalysis 107
  8709. #define OP_DropTable 108
  8710. #define OP_DropIndex 109
  8711. #define OP_DropTrigger 110
  8712. #define OP_IntegrityCk 111
  8713. #define OP_RowSetAdd 112
  8714. #define OP_RowSetRead 113
  8715. #define OP_RowSetTest 114
  8716. #define OP_Program 115
  8717. #define OP_Param 116
  8718. #define OP_FkCounter 117
  8719. #define OP_FkIfZero 118
  8720. #define OP_MemMax 119
  8721. #define OP_IfPos 120
  8722. #define OP_IfNeg 121
  8723. #define OP_IfZero 122
  8724. #define OP_AggStep 123
  8725. #define OP_AggFinal 124
  8726. #define OP_Checkpoint 125
  8727. #define OP_JournalMode 126
  8728. #define OP_Vacuum 127
  8729. #define OP_IncrVacuum 128
  8730. #define OP_Expire 129
  8731. #define OP_TableLock 131
  8732. #define OP_VBegin 132
  8733. #define OP_VCreate 133
  8734. #define OP_VDestroy 134
  8735. #define OP_VOpen 135
  8736. #define OP_VFilter 136
  8737. #define OP_VColumn 137
  8738. #define OP_VNext 138
  8739. #define OP_VRename 139
  8740. #define OP_VUpdate 140
  8741. #define OP_Pagecount 146
  8742. #define OP_MaxPgcnt 147
  8743. #define OP_Trace 148
  8744. #define OP_Noop 149
  8745. #define OP_Explain 150
  8746. /* Properties such as "out2" or "jump" that are specified in
  8747. ** comments following the "case" for each opcode in the vdbe.c
  8748. ** are encoded into bitvectors as follows:
  8749. */
  8750. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8751. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8752. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8753. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8754. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8755. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8756. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8757. #define OPFLG_INITIALIZER {\
  8758. /* 0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
  8759. /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
  8760. /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
  8761. /* 24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
  8762. /* 32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
  8763. /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
  8764. /* 48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
  8765. /* 56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8766. /* 64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
  8767. /* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8768. /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8769. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
  8770. /* 96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
  8771. /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8772. /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
  8773. /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
  8774. /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8775. /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
  8776. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8777. /************** End of opcodes.h *********************************************/
  8778. /************** Continuing where we left off in vdbe.h ***********************/
  8779. /*
  8780. ** Prototypes for the VDBE interface. See comments on the implementation
  8781. ** for a description of what each of these routines does.
  8782. */
  8783. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8784. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8785. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8786. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8787. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8788. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8789. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8790. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8791. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8792. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8793. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8794. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8795. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8796. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8797. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8798. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8799. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8800. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8801. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8802. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8803. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8804. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8805. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8806. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8807. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8808. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8809. #ifdef SQLITE_DEBUG
  8810. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8811. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8812. #endif
  8813. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8814. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8815. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8816. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8817. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8818. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8819. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8820. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8821. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8822. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8823. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
  8824. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8825. #ifndef SQLITE_OMIT_TRACE
  8826. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8827. #endif
  8828. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8829. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8830. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8831. #ifndef SQLITE_OMIT_TRIGGER
  8832. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8833. #endif
  8834. #ifndef NDEBUG
  8835. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8836. # define VdbeComment(X) sqlite3VdbeComment X
  8837. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8838. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8839. #else
  8840. # define VdbeComment(X)
  8841. # define VdbeNoopComment(X)
  8842. #endif
  8843. #endif
  8844. /************** End of vdbe.h ************************************************/
  8845. /************** Continuing where we left off in sqliteInt.h ******************/
  8846. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8847. /************** Begin file pager.h *******************************************/
  8848. /*
  8849. ** 2001 September 15
  8850. **
  8851. ** The author disclaims copyright to this source code. In place of
  8852. ** a legal notice, here is a blessing:
  8853. **
  8854. ** May you do good and not evil.
  8855. ** May you find forgiveness for yourself and forgive others.
  8856. ** May you share freely, never taking more than you give.
  8857. **
  8858. *************************************************************************
  8859. ** This header file defines the interface that the sqlite page cache
  8860. ** subsystem. The page cache subsystem reads and writes a file a page
  8861. ** at a time and provides a journal for rollback.
  8862. */
  8863. #ifndef _PAGER_H_
  8864. #define _PAGER_H_
  8865. /*
  8866. ** Default maximum size for persistent journal files. A negative
  8867. ** value means no limit. This value may be overridden using the
  8868. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8869. */
  8870. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8871. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8872. #endif
  8873. /*
  8874. ** The type used to represent a page number. The first page in a file
  8875. ** is called page 1. 0 is used to represent "not a page".
  8876. */
  8877. typedef u32 Pgno;
  8878. /*
  8879. ** Each open file is managed by a separate instance of the "Pager" structure.
  8880. */
  8881. typedef struct Pager Pager;
  8882. /*
  8883. ** Handle type for pages.
  8884. */
  8885. typedef struct PgHdr DbPage;
  8886. /*
  8887. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8888. ** reserved for working around a windows/posix incompatibility). It is
  8889. ** used in the journal to signify that the remainder of the journal file
  8890. ** is devoted to storing a master journal name - there are no more pages to
  8891. ** roll back. See comments for function writeMasterJournal() in pager.c
  8892. ** for details.
  8893. */
  8894. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8895. /*
  8896. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8897. **
  8898. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8899. */
  8900. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8901. #define PAGER_MEMORY 0x0002 /* In-memory database */
  8902. /*
  8903. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8904. */
  8905. #define PAGER_LOCKINGMODE_QUERY -1
  8906. #define PAGER_LOCKINGMODE_NORMAL 0
  8907. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8908. /*
  8909. ** Numeric constants that encode the journalmode.
  8910. */
  8911. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8912. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8913. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8914. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8915. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8916. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8917. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8918. /*
  8919. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  8920. */
  8921. #define PAGER_ACQUIRE_NOCONTENT 0x01 /* Do not load data from disk */
  8922. #define PAGER_ACQUIRE_READONLY 0x02 /* Read-only page is acceptable */
  8923. /*
  8924. ** The remainder of this file contains the declarations of the functions
  8925. ** that make up the Pager sub-system API. See source code comments for
  8926. ** a detailed description of each routine.
  8927. */
  8928. /* Open and close a Pager connection. */
  8929. SQLITE_PRIVATE int sqlite3PagerOpen(
  8930. sqlite3_vfs*,
  8931. Pager **ppPager,
  8932. const char*,
  8933. int,
  8934. int,
  8935. int,
  8936. void(*)(DbPage*)
  8937. );
  8938. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  8939. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  8940. /* Functions used to configure a Pager object. */
  8941. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  8942. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  8943. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  8944. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  8945. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  8946. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  8947. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
  8948. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  8949. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  8950. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  8951. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  8952. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  8953. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  8954. /* Functions used to obtain and release page references. */
  8955. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  8956. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  8957. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  8958. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  8959. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  8960. /* Operations on page references. */
  8961. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  8962. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  8963. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  8964. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  8965. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  8966. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  8967. /* Functions used to manage pager transactions and savepoints. */
  8968. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  8969. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  8970. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  8971. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  8972. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  8973. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  8974. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  8975. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  8976. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  8977. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  8978. #ifndef SQLITE_OMIT_WAL
  8979. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  8980. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  8981. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  8982. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  8983. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  8984. #endif
  8985. #ifdef SQLITE_ENABLE_ZIPVFS
  8986. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  8987. #endif
  8988. /* Functions used to query pager state and configuration. */
  8989. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  8990. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  8991. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  8992. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  8993. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  8994. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  8995. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  8996. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  8997. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  8998. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  8999. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9000. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9001. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9002. /* Functions used to truncate the database file. */
  9003. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9004. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9005. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9006. #endif
  9007. /* Functions to support testing and debugging. */
  9008. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9009. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9010. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9011. #endif
  9012. #ifdef SQLITE_TEST
  9013. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9014. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9015. void disable_simulated_io_errors(void);
  9016. void enable_simulated_io_errors(void);
  9017. #else
  9018. # define disable_simulated_io_errors()
  9019. # define enable_simulated_io_errors()
  9020. #endif
  9021. #endif /* _PAGER_H_ */
  9022. /************** End of pager.h ***********************************************/
  9023. /************** Continuing where we left off in sqliteInt.h ******************/
  9024. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9025. /************** Begin file pcache.h ******************************************/
  9026. /*
  9027. ** 2008 August 05
  9028. **
  9029. ** The author disclaims copyright to this source code. In place of
  9030. ** a legal notice, here is a blessing:
  9031. **
  9032. ** May you do good and not evil.
  9033. ** May you find forgiveness for yourself and forgive others.
  9034. ** May you share freely, never taking more than you give.
  9035. **
  9036. *************************************************************************
  9037. ** This header file defines the interface that the sqlite page cache
  9038. ** subsystem.
  9039. */
  9040. #ifndef _PCACHE_H_
  9041. typedef struct PgHdr PgHdr;
  9042. typedef struct PCache PCache;
  9043. /*
  9044. ** Every page in the cache is controlled by an instance of the following
  9045. ** structure.
  9046. */
  9047. struct PgHdr {
  9048. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9049. void *pData; /* Page data */
  9050. void *pExtra; /* Extra content */
  9051. PgHdr *pDirty; /* Transient list of dirty pages */
  9052. Pager *pPager; /* The pager this page is part of */
  9053. Pgno pgno; /* Page number for this page */
  9054. #ifdef SQLITE_CHECK_PAGES
  9055. u32 pageHash; /* Hash of page content */
  9056. #endif
  9057. u16 flags; /* PGHDR flags defined below */
  9058. /**********************************************************************
  9059. ** Elements above are public. All that follows is private to pcache.c
  9060. ** and should not be accessed by other modules.
  9061. */
  9062. i16 nRef; /* Number of users of this page */
  9063. PCache *pCache; /* Cache that owns this page */
  9064. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9065. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9066. };
  9067. /* Bit values for PgHdr.flags */
  9068. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9069. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9070. ** writing this page to the database */
  9071. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9072. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9073. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9074. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9075. /* Initialize and shutdown the page cache subsystem */
  9076. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9077. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9078. /* Page cache buffer management:
  9079. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9080. */
  9081. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9082. /* Create a new pager cache.
  9083. ** Under memory stress, invoke xStress to try to make pages clean.
  9084. ** Only clean and unpinned pages can be reclaimed.
  9085. */
  9086. SQLITE_PRIVATE void sqlite3PcacheOpen(
  9087. int szPage, /* Size of every page */
  9088. int szExtra, /* Extra space associated with each page */
  9089. int bPurgeable, /* True if pages are on backing store */
  9090. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9091. void *pStress, /* Argument to xStress */
  9092. PCache *pToInit /* Preallocated space for the PCache */
  9093. );
  9094. /* Modify the page-size after the cache has been created. */
  9095. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  9096. /* Return the size in bytes of a PCache object. Used to preallocate
  9097. ** storage space.
  9098. */
  9099. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9100. /* One release per successful fetch. Page is pinned until released.
  9101. ** Reference counted.
  9102. */
  9103. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  9104. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9105. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9106. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9107. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9108. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9109. /* Change a page number. Used by incr-vacuum. */
  9110. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9111. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9112. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9113. /* Get a list of all dirty pages in the cache, sorted by page number */
  9114. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9115. /* Reset and close the cache object */
  9116. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9117. /* Clear flags from pages of the page cache */
  9118. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9119. /* Discard the contents of the cache */
  9120. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9121. /* Return the total number of outstanding page references */
  9122. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9123. /* Increment the reference count of an existing page */
  9124. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9125. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9126. /* Return the total number of pages stored in the cache */
  9127. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9128. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9129. /* Iterate through all dirty pages currently stored in the cache. This
  9130. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9131. ** library is built.
  9132. */
  9133. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9134. #endif
  9135. /* Set and get the suggested cache-size for the specified pager-cache.
  9136. **
  9137. ** If no global maximum is configured, then the system attempts to limit
  9138. ** the total number of pages cached by purgeable pager-caches to the sum
  9139. ** of the suggested cache-sizes.
  9140. */
  9141. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9142. #ifdef SQLITE_TEST
  9143. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9144. #endif
  9145. /* Free up as much memory as possible from the page cache */
  9146. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9147. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9148. /* Try to return memory used by the pcache module to the main memory heap */
  9149. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9150. #endif
  9151. #ifdef SQLITE_TEST
  9152. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9153. #endif
  9154. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9155. #endif /* _PCACHE_H_ */
  9156. /************** End of pcache.h **********************************************/
  9157. /************** Continuing where we left off in sqliteInt.h ******************/
  9158. /************** Include os.h in the middle of sqliteInt.h ********************/
  9159. /************** Begin file os.h **********************************************/
  9160. /*
  9161. ** 2001 September 16
  9162. **
  9163. ** The author disclaims copyright to this source code. In place of
  9164. ** a legal notice, here is a blessing:
  9165. **
  9166. ** May you do good and not evil.
  9167. ** May you find forgiveness for yourself and forgive others.
  9168. ** May you share freely, never taking more than you give.
  9169. **
  9170. ******************************************************************************
  9171. **
  9172. ** This header file (together with is companion C source-code file
  9173. ** "os.c") attempt to abstract the underlying operating system so that
  9174. ** the SQLite library will work on both POSIX and windows systems.
  9175. **
  9176. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9177. ** being included by every source file.
  9178. */
  9179. #ifndef _SQLITE_OS_H_
  9180. #define _SQLITE_OS_H_
  9181. /*
  9182. ** Figure out if we are dealing with Unix, Windows, or some other
  9183. ** operating system. After the following block of preprocess macros,
  9184. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9185. ** will defined to either 1 or 0. One of the four will be 1. The other
  9186. ** three will be 0.
  9187. */
  9188. #if defined(SQLITE_OS_OTHER)
  9189. # if SQLITE_OS_OTHER==1
  9190. # undef SQLITE_OS_UNIX
  9191. # define SQLITE_OS_UNIX 0
  9192. # undef SQLITE_OS_WIN
  9193. # define SQLITE_OS_WIN 0
  9194. # else
  9195. # undef SQLITE_OS_OTHER
  9196. # endif
  9197. #endif
  9198. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9199. # define SQLITE_OS_OTHER 0
  9200. # ifndef SQLITE_OS_WIN
  9201. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9202. # define SQLITE_OS_WIN 1
  9203. # define SQLITE_OS_UNIX 0
  9204. # else
  9205. # define SQLITE_OS_WIN 0
  9206. # define SQLITE_OS_UNIX 1
  9207. # endif
  9208. # else
  9209. # define SQLITE_OS_UNIX 0
  9210. # endif
  9211. #else
  9212. # ifndef SQLITE_OS_WIN
  9213. # define SQLITE_OS_WIN 0
  9214. # endif
  9215. #endif
  9216. #if SQLITE_OS_WIN
  9217. # include <windows.h>
  9218. #endif
  9219. /*
  9220. ** Determine if we are dealing with Windows NT.
  9221. **
  9222. ** We ought to be able to determine if we are compiling for win98 or winNT
  9223. ** using the _WIN32_WINNT macro as follows:
  9224. **
  9225. ** #if defined(_WIN32_WINNT)
  9226. ** # define SQLITE_OS_WINNT 1
  9227. ** #else
  9228. ** # define SQLITE_OS_WINNT 0
  9229. ** #endif
  9230. **
  9231. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9232. ** so the above test does not work. We'll just assume that everything is
  9233. ** winNT unless the programmer explicitly says otherwise by setting
  9234. ** SQLITE_OS_WINNT to 0.
  9235. */
  9236. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9237. # define SQLITE_OS_WINNT 1
  9238. #endif
  9239. /*
  9240. ** Determine if we are dealing with WindowsCE - which has a much
  9241. ** reduced API.
  9242. */
  9243. #if defined(_WIN32_WCE)
  9244. # define SQLITE_OS_WINCE 1
  9245. #else
  9246. # define SQLITE_OS_WINCE 0
  9247. #endif
  9248. /*
  9249. ** Determine if we are dealing with WinRT, which provides only a subset of
  9250. ** the full Win32 API.
  9251. */
  9252. #if !defined(SQLITE_OS_WINRT)
  9253. # define SQLITE_OS_WINRT 0
  9254. #endif
  9255. /* If the SET_FULLSYNC macro is not defined above, then make it
  9256. ** a no-op
  9257. */
  9258. #ifndef SET_FULLSYNC
  9259. # define SET_FULLSYNC(x,y)
  9260. #endif
  9261. /*
  9262. ** The default size of a disk sector
  9263. */
  9264. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9265. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9266. #endif
  9267. /*
  9268. ** Temporary files are named starting with this prefix followed by 16 random
  9269. ** alphanumeric characters, and no file extension. They are stored in the
  9270. ** OS's standard temporary file directory, and are deleted prior to exit.
  9271. ** If sqlite is being embedded in another program, you may wish to change the
  9272. ** prefix to reflect your program's name, so that if your program exits
  9273. ** prematurely, old temporary files can be easily identified. This can be done
  9274. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9275. **
  9276. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9277. ** Mcafee started using SQLite in their anti-virus product and it
  9278. ** started putting files with the "sqlite" name in the c:/temp folder.
  9279. ** This annoyed many windows users. Those users would then do a
  9280. ** Google search for "sqlite", find the telephone numbers of the
  9281. ** developers and call to wake them up at night and complain.
  9282. ** For this reason, the default name prefix is changed to be "sqlite"
  9283. ** spelled backwards. So the temp files are still identified, but
  9284. ** anybody smart enough to figure out the code is also likely smart
  9285. ** enough to know that calling the developer will not help get rid
  9286. ** of the file.
  9287. */
  9288. #ifndef SQLITE_TEMP_FILE_PREFIX
  9289. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9290. #endif
  9291. /*
  9292. ** The following values may be passed as the second argument to
  9293. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9294. **
  9295. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9296. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9297. ** any time. Other processes may hold and obtain new SHARED locks.
  9298. ** PENDING: A single process may hold a PENDING lock on a file at
  9299. ** any one time. Existing SHARED locks may persist, but no new
  9300. ** SHARED locks may be obtained by other processes.
  9301. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9302. **
  9303. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9304. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9305. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9306. ** sqlite3OsLock().
  9307. */
  9308. #define NO_LOCK 0
  9309. #define SHARED_LOCK 1
  9310. #define RESERVED_LOCK 2
  9311. #define PENDING_LOCK 3
  9312. #define EXCLUSIVE_LOCK 4
  9313. /*
  9314. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9315. **
  9316. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9317. ** those functions are not available. So we use only LockFile() and
  9318. ** UnlockFile().
  9319. **
  9320. ** LockFile() prevents not just writing but also reading by other processes.
  9321. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9322. ** byte out of a specific range of bytes. The lock byte is obtained at
  9323. ** random so two separate readers can probably access the file at the
  9324. ** same time, unless they are unlucky and choose the same lock byte.
  9325. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9326. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9327. ** a single byte of the file that is designated as the reserved lock byte.
  9328. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9329. ** the RESERVED_LOCK byte.
  9330. **
  9331. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9332. ** which means we can use reader/writer locks. When reader/writer locks
  9333. ** are used, the lock is placed on the same range of bytes that is used
  9334. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9335. ** will support two or more Win95 readers or two or more WinNT readers.
  9336. ** But a single Win95 reader will lock out all WinNT readers and a single
  9337. ** WinNT reader will lock out all other Win95 readers.
  9338. **
  9339. ** The following #defines specify the range of bytes used for locking.
  9340. ** SHARED_SIZE is the number of bytes available in the pool from which
  9341. ** a random byte is selected for a shared lock. The pool of bytes for
  9342. ** shared locks begins at SHARED_FIRST.
  9343. **
  9344. ** The same locking strategy and
  9345. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9346. ** clients on win95, winNT, and unix all talking to the same shared file
  9347. ** and all locking correctly. To do so would require that samba (or whatever
  9348. ** tool is being used for file sharing) implements locks correctly between
  9349. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9350. ** using the same locking range we are at least open to the possibility.
  9351. **
  9352. ** Locking in windows is manditory. For this reason, we cannot store
  9353. ** actual data in the bytes used for locking. The pager never allocates
  9354. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9355. ** that all locks will fit on a single page even at the minimum page size.
  9356. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9357. ** is set high so that we don't have to allocate an unused page except
  9358. ** for very large databases. But one should test the page skipping logic
  9359. ** by setting PENDING_BYTE low and running the entire regression suite.
  9360. **
  9361. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9362. ** file format. Depending on how it is changed, you might not notice
  9363. ** the incompatibility right away, even running a full regression test.
  9364. ** The default location of PENDING_BYTE is the first byte past the
  9365. ** 1GB boundary.
  9366. **
  9367. */
  9368. #ifdef SQLITE_OMIT_WSD
  9369. # define PENDING_BYTE (0x40000000)
  9370. #else
  9371. # define PENDING_BYTE sqlite3PendingByte
  9372. #endif
  9373. #define RESERVED_BYTE (PENDING_BYTE+1)
  9374. #define SHARED_FIRST (PENDING_BYTE+2)
  9375. #define SHARED_SIZE 510
  9376. /*
  9377. ** Wrapper around OS specific sqlite3_os_init() function.
  9378. */
  9379. SQLITE_PRIVATE int sqlite3OsInit(void);
  9380. /*
  9381. ** Functions for accessing sqlite3_file methods
  9382. */
  9383. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9384. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9385. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9386. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9387. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9388. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9389. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9390. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9391. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9392. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9393. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9394. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9395. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9396. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9397. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9398. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9399. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9400. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9401. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9402. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9403. /*
  9404. ** Functions for accessing sqlite3_vfs methods
  9405. */
  9406. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9407. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9408. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9409. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9410. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9411. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9412. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9413. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9414. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9415. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9416. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9417. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9418. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9419. /*
  9420. ** Convenience functions for opening and closing files using
  9421. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9422. */
  9423. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9424. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9425. #endif /* _SQLITE_OS_H_ */
  9426. /************** End of os.h **************************************************/
  9427. /************** Continuing where we left off in sqliteInt.h ******************/
  9428. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9429. /************** Begin file mutex.h *******************************************/
  9430. /*
  9431. ** 2007 August 28
  9432. **
  9433. ** The author disclaims copyright to this source code. In place of
  9434. ** a legal notice, here is a blessing:
  9435. **
  9436. ** May you do good and not evil.
  9437. ** May you find forgiveness for yourself and forgive others.
  9438. ** May you share freely, never taking more than you give.
  9439. **
  9440. *************************************************************************
  9441. **
  9442. ** This file contains the common header for all mutex implementations.
  9443. ** The sqliteInt.h header #includes this file so that it is available
  9444. ** to all source files. We break it out in an effort to keep the code
  9445. ** better organized.
  9446. **
  9447. ** NOTE: source files should *not* #include this header file directly.
  9448. ** Source files should #include the sqliteInt.h file and let that file
  9449. ** include this one indirectly.
  9450. */
  9451. /*
  9452. ** Figure out what version of the code to use. The choices are
  9453. **
  9454. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9455. ** mutexes implemention cannot be overridden
  9456. ** at start-time.
  9457. **
  9458. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9459. ** mutual exclusion is provided. But this
  9460. ** implementation can be overridden at
  9461. ** start-time.
  9462. **
  9463. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9464. **
  9465. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9466. */
  9467. #if !SQLITE_THREADSAFE
  9468. # define SQLITE_MUTEX_OMIT
  9469. #endif
  9470. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9471. # if SQLITE_OS_UNIX
  9472. # define SQLITE_MUTEX_PTHREADS
  9473. # elif SQLITE_OS_WIN
  9474. # define SQLITE_MUTEX_W32
  9475. # else
  9476. # define SQLITE_MUTEX_NOOP
  9477. # endif
  9478. #endif
  9479. #ifdef SQLITE_MUTEX_OMIT
  9480. /*
  9481. ** If this is a no-op implementation, implement everything as macros.
  9482. */
  9483. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9484. #define sqlite3_mutex_free(X)
  9485. #define sqlite3_mutex_enter(X)
  9486. #define sqlite3_mutex_try(X) SQLITE_OK
  9487. #define sqlite3_mutex_leave(X)
  9488. #define sqlite3_mutex_held(X) ((void)(X),1)
  9489. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9490. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9491. #define sqlite3MutexInit() SQLITE_OK
  9492. #define sqlite3MutexEnd()
  9493. #define MUTEX_LOGIC(X)
  9494. #else
  9495. #define MUTEX_LOGIC(X) X
  9496. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9497. /************** End of mutex.h ***********************************************/
  9498. /************** Continuing where we left off in sqliteInt.h ******************/
  9499. /*
  9500. ** Each database file to be accessed by the system is an instance
  9501. ** of the following structure. There are normally two of these structures
  9502. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9503. ** aDb[1] is the database file used to hold temporary tables. Additional
  9504. ** databases may be attached.
  9505. */
  9506. struct Db {
  9507. char *zName; /* Name of this database */
  9508. Btree *pBt; /* The B*Tree structure for this database file */
  9509. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  9510. u8 safety_level; /* How aggressive at syncing data to disk */
  9511. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9512. };
  9513. /*
  9514. ** An instance of the following structure stores a database schema.
  9515. **
  9516. ** Most Schema objects are associated with a Btree. The exception is
  9517. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9518. ** In shared cache mode, a single Schema object can be shared by multiple
  9519. ** Btrees that refer to the same underlying BtShared object.
  9520. **
  9521. ** Schema objects are automatically deallocated when the last Btree that
  9522. ** references them is destroyed. The TEMP Schema is manually freed by
  9523. ** sqlite3_close().
  9524. *
  9525. ** A thread must be holding a mutex on the corresponding Btree in order
  9526. ** to access Schema content. This implies that the thread must also be
  9527. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9528. ** For a TEMP Schema, only the connection mutex is required.
  9529. */
  9530. struct Schema {
  9531. int schema_cookie; /* Database schema version number for this file */
  9532. int iGeneration; /* Generation counter. Incremented with each change */
  9533. Hash tblHash; /* All tables indexed by name */
  9534. Hash idxHash; /* All (named) indices indexed by name */
  9535. Hash trigHash; /* All triggers indexed by name */
  9536. Hash fkeyHash; /* All foreign keys by referenced table name */
  9537. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9538. u8 file_format; /* Schema format version for this file */
  9539. u8 enc; /* Text encoding used by this database */
  9540. u16 flags; /* Flags associated with this schema */
  9541. int cache_size; /* Number of pages to use in the cache */
  9542. };
  9543. /*
  9544. ** These macros can be used to test, set, or clear bits in the
  9545. ** Db.pSchema->flags field.
  9546. */
  9547. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9548. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9549. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9550. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9551. /*
  9552. ** Allowed values for the DB.pSchema->flags field.
  9553. **
  9554. ** The DB_SchemaLoaded flag is set after the database schema has been
  9555. ** read into internal hash tables.
  9556. **
  9557. ** DB_UnresetViews means that one or more views have column names that
  9558. ** have been filled out. If the schema changes, these column names might
  9559. ** changes and so the view will need to be reset.
  9560. */
  9561. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9562. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9563. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9564. /*
  9565. ** The number of different kinds of things that can be limited
  9566. ** using the sqlite3_limit() interface.
  9567. */
  9568. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9569. /*
  9570. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9571. ** to satisfy small transient memory allocation requests for objects
  9572. ** associated with a particular database connection. The use of
  9573. ** lookaside malloc provides a significant performance enhancement
  9574. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9575. ** SQL statements.
  9576. **
  9577. ** The Lookaside structure holds configuration information about the
  9578. ** lookaside malloc subsystem. Each available memory allocation in
  9579. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9580. ** objects.
  9581. **
  9582. ** Lookaside allocations are only allowed for objects that are associated
  9583. ** with a particular database connection. Hence, schema information cannot
  9584. ** be stored in lookaside because in shared cache mode the schema information
  9585. ** is shared by multiple database connections. Therefore, while parsing
  9586. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9587. ** lookaside allocations are not used to construct the schema objects.
  9588. */
  9589. struct Lookaside {
  9590. u16 sz; /* Size of each buffer in bytes */
  9591. u8 bEnabled; /* False to disable new lookaside allocations */
  9592. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9593. int nOut; /* Number of buffers currently checked out */
  9594. int mxOut; /* Highwater mark for nOut */
  9595. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9596. LookasideSlot *pFree; /* List of available buffers */
  9597. void *pStart; /* First byte of available memory space */
  9598. void *pEnd; /* First byte past end of available space */
  9599. };
  9600. struct LookasideSlot {
  9601. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9602. };
  9603. /*
  9604. ** A hash table for function definitions.
  9605. **
  9606. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9607. ** Collisions are on the FuncDef.pHash chain.
  9608. */
  9609. struct FuncDefHash {
  9610. FuncDef *a[23]; /* Hash table for functions */
  9611. };
  9612. /*
  9613. ** Each database connection is an instance of the following structure.
  9614. */
  9615. struct sqlite3 {
  9616. sqlite3_vfs *pVfs; /* OS Interface */
  9617. struct Vdbe *pVdbe; /* List of active virtual machines */
  9618. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9619. sqlite3_mutex *mutex; /* Connection mutex */
  9620. Db *aDb; /* All backends */
  9621. int nDb; /* Number of backends currently in use */
  9622. int flags; /* Miscellaneous flags. See below */
  9623. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9624. i64 szMmap; /* Default mmap_size setting */
  9625. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9626. int errCode; /* Most recent error code (SQLITE_*) */
  9627. int errMask; /* & result codes with this before returning */
  9628. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9629. u8 autoCommit; /* The auto-commit flag. */
  9630. u8 temp_store; /* 1: file 2: memory 0: default */
  9631. u8 mallocFailed; /* True if we have seen a malloc failure */
  9632. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9633. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9634. u8 suppressErr; /* Do not issue error messages if true */
  9635. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9636. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9637. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9638. u32 magic; /* Magic number for detect library misuse */
  9639. int nChange; /* Value returned by sqlite3_changes() */
  9640. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9641. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9642. struct sqlite3InitInfo { /* Information used during initialization */
  9643. int newTnum; /* Rootpage of table being initialized */
  9644. u8 iDb; /* Which db file is being initialized */
  9645. u8 busy; /* TRUE if currently initializing */
  9646. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9647. } init;
  9648. int activeVdbeCnt; /* Number of VDBEs currently executing */
  9649. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  9650. int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
  9651. int nExtension; /* Number of loaded extensions */
  9652. void **aExtension; /* Array of shared library handles */
  9653. void (*xTrace)(void*,const char*); /* Trace function */
  9654. void *pTraceArg; /* Argument to the trace function */
  9655. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9656. void *pProfileArg; /* Argument to profile function */
  9657. void *pCommitArg; /* Argument to xCommitCallback() */
  9658. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9659. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9660. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9661. void *pUpdateArg;
  9662. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9663. #ifndef SQLITE_OMIT_WAL
  9664. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9665. void *pWalArg;
  9666. #endif
  9667. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9668. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9669. void *pCollNeededArg;
  9670. sqlite3_value *pErr; /* Most recent error message */
  9671. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  9672. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  9673. union {
  9674. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9675. double notUsed1; /* Spacer */
  9676. } u1;
  9677. Lookaside lookaside; /* Lookaside malloc configuration */
  9678. #ifndef SQLITE_OMIT_AUTHORIZATION
  9679. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9680. /* Access authorization function */
  9681. void *pAuthArg; /* 1st argument to the access auth function */
  9682. #endif
  9683. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9684. int (*xProgress)(void *); /* The progress callback */
  9685. void *pProgressArg; /* Argument to the progress callback */
  9686. int nProgressOps; /* Number of opcodes for progress callback */
  9687. #endif
  9688. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9689. int nVTrans; /* Allocated size of aVTrans */
  9690. Hash aModule; /* populated by sqlite3_create_module() */
  9691. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9692. VTable **aVTrans; /* Virtual tables with open transactions */
  9693. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9694. #endif
  9695. FuncDefHash aFunc; /* Hash table of connection functions */
  9696. Hash aCollSeq; /* All collating sequences */
  9697. BusyHandler busyHandler; /* Busy callback */
  9698. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9699. Savepoint *pSavepoint; /* List of active savepoints */
  9700. int busyTimeout; /* Busy handler timeout, in msec */
  9701. int nSavepoint; /* Number of non-transaction savepoints */
  9702. int nStatement; /* Number of nested statement-transactions */
  9703. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9704. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9705. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9706. /* The following variables are all protected by the STATIC_MASTER
  9707. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9708. **
  9709. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9710. ** unlock so that it can proceed.
  9711. **
  9712. ** When X.pBlockingConnection==Y, that means that something that X tried
  9713. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9714. ** held by Y.
  9715. */
  9716. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9717. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9718. void *pUnlockArg; /* Argument to xUnlockNotify */
  9719. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9720. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9721. #endif
  9722. };
  9723. /*
  9724. ** A macro to discover the encoding of a database.
  9725. */
  9726. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9727. /*
  9728. ** Possible values for the sqlite3.flags.
  9729. */
  9730. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9731. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9732. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  9733. #define SQLITE_ShortColNames 0x00000008 /* Show short columns names */
  9734. #define SQLITE_CountRows 0x00000010 /* Count rows changed by INSERT, */
  9735. /* DELETE, or UPDATE and return */
  9736. /* the count using a callback. */
  9737. #define SQLITE_NullCallback 0x00000020 /* Invoke the callback once if the */
  9738. /* result set is empty */
  9739. #define SQLITE_SqlTrace 0x00000040 /* Debug print SQL as it executes */
  9740. #define SQLITE_VdbeListing 0x00000080 /* Debug listings of VDBE programs */
  9741. #define SQLITE_WriteSchema 0x00000100 /* OK to update SQLITE_MASTER */
  9742. #define SQLITE_VdbeAddopTrace 0x00000200 /* Trace sqlite3VdbeAddOp() calls */
  9743. #define SQLITE_IgnoreChecks 0x00000400 /* Do not enforce check constraints */
  9744. #define SQLITE_ReadUncommitted 0x0000800 /* For shared-cache mode */
  9745. #define SQLITE_LegacyFileFmt 0x00001000 /* Create new databases in format 1 */
  9746. #define SQLITE_FullFSync 0x00002000 /* Use full fsync on the backend */
  9747. #define SQLITE_CkptFullFSync 0x00004000 /* Use full fsync for checkpoint */
  9748. #define SQLITE_RecoveryMode 0x00008000 /* Ignore schema errors */
  9749. #define SQLITE_ReverseOrder 0x00010000 /* Reverse unordered SELECTs */
  9750. #define SQLITE_RecTriggers 0x00020000 /* Enable recursive triggers */
  9751. #define SQLITE_ForeignKeys 0x00040000 /* Enforce foreign key constraints */
  9752. #define SQLITE_AutoIndex 0x00080000 /* Enable automatic indexes */
  9753. #define SQLITE_PreferBuiltin 0x00100000 /* Preference to built-in funcs */
  9754. #define SQLITE_LoadExtension 0x00200000 /* Enable load_extension */
  9755. #define SQLITE_EnableTrigger 0x00400000 /* True to enable triggers */
  9756. /*
  9757. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9758. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9759. ** selectively disable various optimizations.
  9760. */
  9761. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9762. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9763. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9764. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9765. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9766. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9767. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9768. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9769. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9770. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  9771. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9772. /*
  9773. ** Macros for testing whether or not optimizations are enabled or disabled.
  9774. */
  9775. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9776. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9777. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9778. #else
  9779. #define OptimizationDisabled(db, mask) 0
  9780. #define OptimizationEnabled(db, mask) 1
  9781. #endif
  9782. /*
  9783. ** Possible values for the sqlite.magic field.
  9784. ** The numbers are obtained at random and have no special meaning, other
  9785. ** than being distinct from one another.
  9786. */
  9787. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9788. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9789. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9790. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9791. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9792. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9793. /*
  9794. ** Each SQL function is defined by an instance of the following
  9795. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9796. ** hash table. When multiple functions have the same name, the hash table
  9797. ** points to a linked list of these structures.
  9798. */
  9799. struct FuncDef {
  9800. i16 nArg; /* Number of arguments. -1 means unlimited */
  9801. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  9802. u8 flags; /* Some combination of SQLITE_FUNC_* */
  9803. void *pUserData; /* User data parameter */
  9804. FuncDef *pNext; /* Next function with same name */
  9805. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9806. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9807. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9808. char *zName; /* SQL name of the function. */
  9809. FuncDef *pHash; /* Next with a different name but the same hash */
  9810. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9811. };
  9812. /*
  9813. ** This structure encapsulates a user-function destructor callback (as
  9814. ** configured using create_function_v2()) and a reference counter. When
  9815. ** create_function_v2() is called to create a function with a destructor,
  9816. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9817. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9818. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9819. ** member of each of the new FuncDef objects is set to point to the allocated
  9820. ** FuncDestructor.
  9821. **
  9822. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9823. ** count on this object is decremented. When it reaches 0, the destructor
  9824. ** is invoked and the FuncDestructor structure freed.
  9825. */
  9826. struct FuncDestructor {
  9827. int nRef;
  9828. void (*xDestroy)(void *);
  9829. void *pUserData;
  9830. };
  9831. /*
  9832. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9833. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9834. ** are assert() statements in the code to verify this.
  9835. */
  9836. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  9837. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  9838. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  9839. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  9840. #define SQLITE_FUNC_COUNT 0x10 /* Built-in count(*) aggregate */
  9841. #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
  9842. #define SQLITE_FUNC_LENGTH 0x40 /* Built-in length() function */
  9843. #define SQLITE_FUNC_TYPEOF 0x80 /* Built-in typeof() function */
  9844. /*
  9845. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9846. ** used to create the initializers for the FuncDef structures.
  9847. **
  9848. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9849. ** Used to create a scalar function definition of a function zName
  9850. ** implemented by C function xFunc that accepts nArg arguments. The
  9851. ** value passed as iArg is cast to a (void*) and made available
  9852. ** as the user-data (sqlite3_user_data()) for the function. If
  9853. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9854. **
  9855. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9856. ** Used to create an aggregate function definition implemented by
  9857. ** the C functions xStep and xFinal. The first four parameters
  9858. ** are interpreted in the same way as the first 4 parameters to
  9859. ** FUNCTION().
  9860. **
  9861. ** LIKEFUNC(zName, nArg, pArg, flags)
  9862. ** Used to create a scalar function definition of a function zName
  9863. ** that accepts nArg arguments and is implemented by a call to C
  9864. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9865. ** available as the function user-data (sqlite3_user_data()). The
  9866. ** FuncDef.flags variable is set to the value passed as the flags
  9867. ** parameter.
  9868. */
  9869. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9870. {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
  9871. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9872. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  9873. {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  9874. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9875. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9876. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  9877. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9878. #define LIKEFUNC(zName, nArg, arg, flags) \
  9879. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9880. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9881. {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
  9882. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9883. /*
  9884. ** All current savepoints are stored in a linked list starting at
  9885. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9886. ** opened savepoint. Savepoints are added to the list by the vdbe
  9887. ** OP_Savepoint instruction.
  9888. */
  9889. struct Savepoint {
  9890. char *zName; /* Savepoint name (nul-terminated) */
  9891. i64 nDeferredCons; /* Number of deferred fk violations */
  9892. Savepoint *pNext; /* Parent savepoint (if any) */
  9893. };
  9894. /*
  9895. ** The following are used as the second parameter to sqlite3Savepoint(),
  9896. ** and as the P1 argument to the OP_Savepoint instruction.
  9897. */
  9898. #define SAVEPOINT_BEGIN 0
  9899. #define SAVEPOINT_RELEASE 1
  9900. #define SAVEPOINT_ROLLBACK 2
  9901. /*
  9902. ** Each SQLite module (virtual table definition) is defined by an
  9903. ** instance of the following structure, stored in the sqlite3.aModule
  9904. ** hash table.
  9905. */
  9906. struct Module {
  9907. const sqlite3_module *pModule; /* Callback pointers */
  9908. const char *zName; /* Name passed to create_module() */
  9909. void *pAux; /* pAux passed to create_module() */
  9910. void (*xDestroy)(void *); /* Module destructor function */
  9911. };
  9912. /*
  9913. ** information about each column of an SQL table is held in an instance
  9914. ** of this structure.
  9915. */
  9916. struct Column {
  9917. char *zName; /* Name of this column */
  9918. Expr *pDflt; /* Default value of this column */
  9919. char *zDflt; /* Original text of the default value */
  9920. char *zType; /* Data type for this column */
  9921. char *zColl; /* Collating sequence. If NULL, use the default */
  9922. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  9923. char affinity; /* One of the SQLITE_AFF_... values */
  9924. u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  9925. };
  9926. /* Allowed values for Column.colFlags:
  9927. */
  9928. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  9929. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  9930. /*
  9931. ** A "Collating Sequence" is defined by an instance of the following
  9932. ** structure. Conceptually, a collating sequence consists of a name and
  9933. ** a comparison routine that defines the order of that sequence.
  9934. **
  9935. ** If CollSeq.xCmp is NULL, it means that the
  9936. ** collating sequence is undefined. Indices built on an undefined
  9937. ** collating sequence may not be read or written.
  9938. */
  9939. struct CollSeq {
  9940. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  9941. u8 enc; /* Text encoding handled by xCmp() */
  9942. void *pUser; /* First argument to xCmp() */
  9943. int (*xCmp)(void*,int, const void*, int, const void*);
  9944. void (*xDel)(void*); /* Destructor for pUser */
  9945. };
  9946. /*
  9947. ** A sort order can be either ASC or DESC.
  9948. */
  9949. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  9950. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  9951. /*
  9952. ** Column affinity types.
  9953. **
  9954. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  9955. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  9956. ** the speed a little by numbering the values consecutively.
  9957. **
  9958. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  9959. ** when multiple affinity types are concatenated into a string and
  9960. ** used as the P4 operand, they will be more readable.
  9961. **
  9962. ** Note also that the numeric types are grouped together so that testing
  9963. ** for a numeric type is a single comparison.
  9964. */
  9965. #define SQLITE_AFF_TEXT 'a'
  9966. #define SQLITE_AFF_NONE 'b'
  9967. #define SQLITE_AFF_NUMERIC 'c'
  9968. #define SQLITE_AFF_INTEGER 'd'
  9969. #define SQLITE_AFF_REAL 'e'
  9970. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  9971. /*
  9972. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  9973. ** affinity value.
  9974. */
  9975. #define SQLITE_AFF_MASK 0x67
  9976. /*
  9977. ** Additional bit values that can be ORed with an affinity without
  9978. ** changing the affinity.
  9979. */
  9980. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  9981. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  9982. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  9983. /*
  9984. ** An object of this type is created for each virtual table present in
  9985. ** the database schema.
  9986. **
  9987. ** If the database schema is shared, then there is one instance of this
  9988. ** structure for each database connection (sqlite3*) that uses the shared
  9989. ** schema. This is because each database connection requires its own unique
  9990. ** instance of the sqlite3_vtab* handle used to access the virtual table
  9991. ** implementation. sqlite3_vtab* handles can not be shared between
  9992. ** database connections, even when the rest of the in-memory database
  9993. ** schema is shared, as the implementation often stores the database
  9994. ** connection handle passed to it via the xConnect() or xCreate() method
  9995. ** during initialization internally. This database connection handle may
  9996. ** then be used by the virtual table implementation to access real tables
  9997. ** within the database. So that they appear as part of the callers
  9998. ** transaction, these accesses need to be made via the same database
  9999. ** connection as that used to execute SQL operations on the virtual table.
  10000. **
  10001. ** All VTable objects that correspond to a single table in a shared
  10002. ** database schema are initially stored in a linked-list pointed to by
  10003. ** the Table.pVTable member variable of the corresponding Table object.
  10004. ** When an sqlite3_prepare() operation is required to access the virtual
  10005. ** table, it searches the list for the VTable that corresponds to the
  10006. ** database connection doing the preparing so as to use the correct
  10007. ** sqlite3_vtab* handle in the compiled query.
  10008. **
  10009. ** When an in-memory Table object is deleted (for example when the
  10010. ** schema is being reloaded for some reason), the VTable objects are not
  10011. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10012. ** immediately. Instead, they are moved from the Table.pVTable list to
  10013. ** another linked list headed by the sqlite3.pDisconnect member of the
  10014. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10015. ** next time a statement is prepared using said sqlite3*. This is done
  10016. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10017. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10018. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10019. ** list without holding the corresponding sqlite3.mutex mutex.
  10020. **
  10021. ** The memory for objects of this type is always allocated by
  10022. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10023. ** the first argument.
  10024. */
  10025. struct VTable {
  10026. sqlite3 *db; /* Database connection associated with this table */
  10027. Module *pMod; /* Pointer to module implementation */
  10028. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10029. int nRef; /* Number of pointers to this structure */
  10030. u8 bConstraint; /* True if constraints are supported */
  10031. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10032. VTable *pNext; /* Next in linked list (see above) */
  10033. };
  10034. /*
  10035. ** Each SQL table is represented in memory by an instance of the
  10036. ** following structure.
  10037. **
  10038. ** Table.zName is the name of the table. The case of the original
  10039. ** CREATE TABLE statement is stored, but case is not significant for
  10040. ** comparisons.
  10041. **
  10042. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10043. ** pointer to an array of Column structures, one for each column.
  10044. **
  10045. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10046. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10047. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10048. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10049. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10050. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10051. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10052. **
  10053. ** Table.tnum is the page number for the root BTree page of the table in the
  10054. ** database file. If Table.iDb is the index of the database table backend
  10055. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10056. ** holds temporary tables and indices. If TF_Ephemeral is set
  10057. ** then the table is stored in a file that is automatically deleted
  10058. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10059. ** refers VDBE cursor number that holds the table open, not to the root
  10060. ** page number. Transient tables are used to hold the results of a
  10061. ** sub-query that appears instead of a real table name in the FROM clause
  10062. ** of a SELECT statement.
  10063. */
  10064. struct Table {
  10065. char *zName; /* Name of the table or view */
  10066. Column *aCol; /* Information about each column */
  10067. Index *pIndex; /* List of SQL indexes on this table. */
  10068. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10069. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10070. char *zColAff; /* String defining the affinity of each column */
  10071. #ifndef SQLITE_OMIT_CHECK
  10072. ExprList *pCheck; /* All CHECK constraints */
  10073. #endif
  10074. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  10075. int tnum; /* Root BTree node for this table (see note above) */
  10076. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10077. i16 nCol; /* Number of columns in this table */
  10078. u16 nRef; /* Number of pointers to this Table */
  10079. u8 tabFlags; /* Mask of TF_* values */
  10080. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10081. #ifndef SQLITE_OMIT_ALTERTABLE
  10082. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10083. #endif
  10084. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10085. int nModuleArg; /* Number of arguments to the module */
  10086. char **azModuleArg; /* Text of all module args. [0] is module name */
  10087. VTable *pVTable; /* List of VTable objects. */
  10088. #endif
  10089. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10090. Schema *pSchema; /* Schema that contains this table */
  10091. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10092. };
  10093. /*
  10094. ** Allowed values for Tabe.tabFlags.
  10095. */
  10096. #define TF_Readonly 0x01 /* Read-only system table */
  10097. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10098. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10099. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10100. #define TF_Virtual 0x10 /* Is a virtual table */
  10101. /*
  10102. ** Test to see whether or not a table is a virtual table. This is
  10103. ** done as a macro so that it will be optimized out when virtual
  10104. ** table support is omitted from the build.
  10105. */
  10106. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10107. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10108. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10109. #else
  10110. # define IsVirtual(X) 0
  10111. # define IsHiddenColumn(X) 0
  10112. #endif
  10113. /*
  10114. ** Each foreign key constraint is an instance of the following structure.
  10115. **
  10116. ** A foreign key is associated with two tables. The "from" table is
  10117. ** the table that contains the REFERENCES clause that creates the foreign
  10118. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10119. ** Consider this example:
  10120. **
  10121. ** CREATE TABLE ex1(
  10122. ** a INTEGER PRIMARY KEY,
  10123. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10124. ** );
  10125. **
  10126. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10127. **
  10128. ** Each REFERENCES clause generates an instance of the following structure
  10129. ** which is attached to the from-table. The to-table need not exist when
  10130. ** the from-table is created. The existence of the to-table is not checked.
  10131. */
  10132. struct FKey {
  10133. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10134. FKey *pNextFrom; /* Next foreign key in pFrom */
  10135. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10136. FKey *pNextTo; /* Next foreign key on table named zTo */
  10137. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  10138. int nCol; /* Number of columns in this key */
  10139. /* EV: R-30323-21917 */
  10140. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10141. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10142. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10143. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10144. int iFrom; /* Index of column in pFrom */
  10145. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10146. } aCol[1]; /* One entry for each of nCol column s */
  10147. };
  10148. /*
  10149. ** SQLite supports many different ways to resolve a constraint
  10150. ** error. ROLLBACK processing means that a constraint violation
  10151. ** causes the operation in process to fail and for the current transaction
  10152. ** to be rolled back. ABORT processing means the operation in process
  10153. ** fails and any prior changes from that one operation are backed out,
  10154. ** but the transaction is not rolled back. FAIL processing means that
  10155. ** the operation in progress stops and returns an error code. But prior
  10156. ** changes due to the same operation are not backed out and no rollback
  10157. ** occurs. IGNORE means that the particular row that caused the constraint
  10158. ** error is not inserted or updated. Processing continues and no error
  10159. ** is returned. REPLACE means that preexisting database rows that caused
  10160. ** a UNIQUE constraint violation are removed so that the new insert or
  10161. ** update can proceed. Processing continues and no error is reported.
  10162. **
  10163. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10164. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10165. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10166. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10167. ** referenced table row is propagated into the row that holds the
  10168. ** foreign key.
  10169. **
  10170. ** The following symbolic values are used to record which type
  10171. ** of action to take.
  10172. */
  10173. #define OE_None 0 /* There is no constraint to check */
  10174. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10175. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10176. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10177. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10178. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10179. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10180. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10181. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10182. #define OE_Cascade 9 /* Cascade the changes */
  10183. #define OE_Default 99 /* Do whatever the default action is */
  10184. /*
  10185. ** An instance of the following structure is passed as the first
  10186. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10187. ** comparison of the two index keys.
  10188. */
  10189. struct KeyInfo {
  10190. sqlite3 *db; /* The database connection */
  10191. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10192. u16 nField; /* Number of entries in aColl[] */
  10193. u8 *aSortOrder; /* Sort order for each column. May be NULL */
  10194. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10195. };
  10196. /*
  10197. ** An instance of the following structure holds information about a
  10198. ** single index record that has already been parsed out into individual
  10199. ** values.
  10200. **
  10201. ** A record is an object that contains one or more fields of data.
  10202. ** Records are used to store the content of a table row and to store
  10203. ** the key of an index. A blob encoding of a record is created by
  10204. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10205. ** OP_Column opcode.
  10206. **
  10207. ** This structure holds a record that has already been disassembled
  10208. ** into its constituent fields.
  10209. */
  10210. struct UnpackedRecord {
  10211. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10212. u16 nField; /* Number of entries in apMem[] */
  10213. u8 flags; /* Boolean settings. UNPACKED_... below */
  10214. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10215. Mem *aMem; /* Values */
  10216. };
  10217. /*
  10218. ** Allowed values of UnpackedRecord.flags
  10219. */
  10220. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10221. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10222. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10223. /*
  10224. ** Each SQL index is represented in memory by an
  10225. ** instance of the following structure.
  10226. **
  10227. ** The columns of the table that are to be indexed are described
  10228. ** by the aiColumn[] field of this structure. For example, suppose
  10229. ** we have the following table and index:
  10230. **
  10231. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10232. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10233. **
  10234. ** In the Table structure describing Ex1, nCol==3 because there are
  10235. ** three columns in the table. In the Index structure describing
  10236. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10237. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10238. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10239. ** The second column to be indexed (c1) has an index of 0 in
  10240. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10241. **
  10242. ** The Index.onError field determines whether or not the indexed columns
  10243. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10244. ** it means this is not a unique index. Otherwise it is a unique index
  10245. ** and the value of Index.onError indicate the which conflict resolution
  10246. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10247. ** element.
  10248. */
  10249. struct Index {
  10250. char *zName; /* Name of this index */
  10251. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10252. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  10253. Table *pTable; /* The SQL table being indexed */
  10254. char *zColAff; /* String defining the affinity of each column */
  10255. Index *pNext; /* The next index associated with the same table */
  10256. Schema *pSchema; /* Schema containing this index */
  10257. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10258. char **azColl; /* Array of collation sequence names for index */
  10259. int tnum; /* DB Page containing root of this index */
  10260. u16 nColumn; /* Number of columns in table used by this index */
  10261. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10262. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10263. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10264. #ifdef SQLITE_ENABLE_STAT3
  10265. int nSample; /* Number of elements in aSample[] */
  10266. tRowcnt avgEq; /* Average nEq value for key values not in aSample */
  10267. IndexSample *aSample; /* Samples of the left-most key */
  10268. #endif
  10269. };
  10270. /*
  10271. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10272. ** using a structure of this type. See documentation at the top of the
  10273. ** analyze.c source file for additional information.
  10274. */
  10275. struct IndexSample {
  10276. union {
  10277. char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
  10278. double r; /* Value if eType is SQLITE_FLOAT */
  10279. i64 i; /* Value if eType is SQLITE_INTEGER */
  10280. } u;
  10281. u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
  10282. int nByte; /* Size in byte of text or blob. */
  10283. tRowcnt nEq; /* Est. number of rows where the key equals this sample */
  10284. tRowcnt nLt; /* Est. number of rows where key is less than this sample */
  10285. tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
  10286. };
  10287. /*
  10288. ** Each token coming out of the lexer is an instance of
  10289. ** this structure. Tokens are also used as part of an expression.
  10290. **
  10291. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10292. ** may contain random values. Do not make any assumptions about Token.dyn
  10293. ** and Token.n when Token.z==0.
  10294. */
  10295. struct Token {
  10296. const char *z; /* Text of the token. Not NULL-terminated! */
  10297. unsigned int n; /* Number of characters in this token */
  10298. };
  10299. /*
  10300. ** An instance of this structure contains information needed to generate
  10301. ** code for a SELECT that contains aggregate functions.
  10302. **
  10303. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10304. ** pointer to this structure. The Expr.iColumn field is the index in
  10305. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10306. ** code for that node.
  10307. **
  10308. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10309. ** original Select structure that describes the SELECT statement. These
  10310. ** fields do not need to be freed when deallocating the AggInfo structure.
  10311. */
  10312. struct AggInfo {
  10313. u8 directMode; /* Direct rendering mode means take data directly
  10314. ** from source tables rather than from accumulators */
  10315. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10316. ** than the source table */
  10317. int sortingIdx; /* Cursor number of the sorting index */
  10318. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10319. int nSortingColumn; /* Number of columns in the sorting index */
  10320. ExprList *pGroupBy; /* The group by clause */
  10321. struct AggInfo_col { /* For each column used in source tables */
  10322. Table *pTab; /* Source table */
  10323. int iTable; /* Cursor number of the source table */
  10324. int iColumn; /* Column number within the source table */
  10325. int iSorterColumn; /* Column number in the sorting index */
  10326. int iMem; /* Memory location that acts as accumulator */
  10327. Expr *pExpr; /* The original expression */
  10328. } *aCol;
  10329. int nColumn; /* Number of used entries in aCol[] */
  10330. int nAccumulator; /* Number of columns that show through to the output.
  10331. ** Additional columns are used only as parameters to
  10332. ** aggregate functions */
  10333. struct AggInfo_func { /* For each aggregate function */
  10334. Expr *pExpr; /* Expression encoding the function */
  10335. FuncDef *pFunc; /* The aggregate function implementation */
  10336. int iMem; /* Memory location that acts as accumulator */
  10337. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10338. } *aFunc;
  10339. int nFunc; /* Number of entries in aFunc[] */
  10340. };
  10341. /*
  10342. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10343. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10344. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10345. ** it uses less memory in the Expr object, which is a big memory user
  10346. ** in systems with lots of prepared statements. And few applications
  10347. ** need more than about 10 or 20 variables. But some extreme users want
  10348. ** to have prepared statements with over 32767 variables, and for them
  10349. ** the option is available (at compile-time).
  10350. */
  10351. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10352. typedef i16 ynVar;
  10353. #else
  10354. typedef int ynVar;
  10355. #endif
  10356. /*
  10357. ** Each node of an expression in the parse tree is an instance
  10358. ** of this structure.
  10359. **
  10360. ** Expr.op is the opcode. The integer parser token codes are reused
  10361. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10362. ** code representing the ">=" operator. This same integer code is reused
  10363. ** to represent the greater-than-or-equal-to operator in the expression
  10364. ** tree.
  10365. **
  10366. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10367. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10368. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10369. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10370. ** then Expr.token contains the name of the function.
  10371. **
  10372. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10373. ** binary operator. Either or both may be NULL.
  10374. **
  10375. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10376. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10377. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10378. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10379. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10380. ** valid.
  10381. **
  10382. ** An expression of the form ID or ID.ID refers to a column in a table.
  10383. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10384. ** the integer cursor number of a VDBE cursor pointing to that table and
  10385. ** Expr.iColumn is the column number for the specific column. If the
  10386. ** expression is used as a result in an aggregate SELECT, then the
  10387. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10388. ** it can be accessed after all aggregates are computed.
  10389. **
  10390. ** If the expression is an unbound variable marker (a question mark
  10391. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10392. ** number for that variable.
  10393. **
  10394. ** If the expression is a subquery then Expr.iColumn holds an integer
  10395. ** register number containing the result of the subquery. If the
  10396. ** subquery gives a constant result, then iTable is -1. If the subquery
  10397. ** gives a different answer at different times during statement processing
  10398. ** then iTable is the address of a subroutine that computes the subquery.
  10399. **
  10400. ** If the Expr is of type OP_Column, and the table it is selecting from
  10401. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10402. ** corresponding table definition.
  10403. **
  10404. ** ALLOCATION NOTES:
  10405. **
  10406. ** Expr objects can use a lot of memory space in database schema. To
  10407. ** help reduce memory requirements, sometimes an Expr object will be
  10408. ** truncated. And to reduce the number of memory allocations, sometimes
  10409. ** two or more Expr objects will be stored in a single memory allocation,
  10410. ** together with Expr.zToken strings.
  10411. **
  10412. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10413. ** an Expr object is truncated. When EP_Reduced is set, then all
  10414. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10415. ** are contained within the same memory allocation. Note, however, that
  10416. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10417. ** allocated, regardless of whether or not EP_Reduced is set.
  10418. */
  10419. struct Expr {
  10420. u8 op; /* Operation performed by this node */
  10421. char affinity; /* The affinity of the column or 0 if not a column */
  10422. u16 flags; /* Various flags. EP_* See below */
  10423. union {
  10424. char *zToken; /* Token value. Zero terminated and dequoted */
  10425. int iValue; /* Non-negative integer value if EP_IntValue */
  10426. } u;
  10427. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10428. ** space is allocated for the fields below this point. An attempt to
  10429. ** access them will result in a segfault or malfunction.
  10430. *********************************************************************/
  10431. Expr *pLeft; /* Left subnode */
  10432. Expr *pRight; /* Right subnode */
  10433. union {
  10434. ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
  10435. Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
  10436. } x;
  10437. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10438. ** space is allocated for the fields below this point. An attempt to
  10439. ** access them will result in a segfault or malfunction.
  10440. *********************************************************************/
  10441. #if SQLITE_MAX_EXPR_DEPTH>0
  10442. int nHeight; /* Height of the tree headed by this node */
  10443. #endif
  10444. int iTable; /* TK_COLUMN: cursor number of table holding column
  10445. ** TK_REGISTER: register number
  10446. ** TK_TRIGGER: 1 -> new, 0 -> old */
  10447. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10448. ** TK_VARIABLE: variable number (always >= 1). */
  10449. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10450. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10451. u8 flags2; /* Second set of flags. EP2_... */
  10452. u8 op2; /* TK_REGISTER: original value of Expr.op
  10453. ** TK_COLUMN: the value of p5 for OP_Column
  10454. ** TK_AGG_FUNCTION: nesting depth */
  10455. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10456. Table *pTab; /* Table for TK_COLUMN expressions. */
  10457. };
  10458. /*
  10459. ** The following are the meanings of bits in the Expr.flags field.
  10460. */
  10461. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  10462. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  10463. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  10464. #define EP_Error 0x0008 /* Expression contains one or more errors */
  10465. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  10466. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  10467. #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
  10468. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  10469. #define EP_Collate 0x0100 /* Tree contains a TK_COLLATE opeartor */
  10470. #define EP_FixedDest 0x0200 /* Result needed in a specific register */
  10471. #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
  10472. #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
  10473. #define EP_Hint 0x1000 /* Not used */
  10474. #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
  10475. #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
  10476. #define EP_Static 0x8000 /* Held in memory not obtained from malloc() */
  10477. /*
  10478. ** The following are the meanings of bits in the Expr.flags2 field.
  10479. */
  10480. #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
  10481. #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
  10482. /*
  10483. ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
  10484. ** flag on an expression structure. This flag is used for VV&A only. The
  10485. ** routine is implemented as a macro that only works when in debugging mode,
  10486. ** so as not to burden production code.
  10487. */
  10488. #ifdef SQLITE_DEBUG
  10489. # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
  10490. #else
  10491. # define ExprSetIrreducible(X)
  10492. #endif
  10493. /*
  10494. ** These macros can be used to test, set, or clear bits in the
  10495. ** Expr.flags field.
  10496. */
  10497. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  10498. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  10499. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10500. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10501. /*
  10502. ** Macros to determine the number of bytes required by a normal Expr
  10503. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10504. ** and an Expr struct with the EP_TokenOnly flag set.
  10505. */
  10506. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10507. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10508. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10509. /*
  10510. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10511. ** above sqlite3ExprDup() for details.
  10512. */
  10513. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10514. /*
  10515. ** A list of expressions. Each expression may optionally have a
  10516. ** name. An expr/name combination can be used in several ways, such
  10517. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10518. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10519. ** also be used as the argument to a function, in which case the a.zName
  10520. ** field is not used.
  10521. **
  10522. ** By default the Expr.zSpan field holds a human-readable description of
  10523. ** the expression that is used in the generation of error messages and
  10524. ** column labels. In this case, Expr.zSpan is typically the text of a
  10525. ** column expression as it exists in a SELECT statement. However, if
  10526. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  10527. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  10528. ** form is used for name resolution with nested FROM clauses.
  10529. */
  10530. struct ExprList {
  10531. int nExpr; /* Number of expressions on the list */
  10532. int iECursor; /* VDBE Cursor associated with this ExprList */
  10533. struct ExprList_item { /* For each expression in the list */
  10534. Expr *pExpr; /* The list of expressions */
  10535. char *zName; /* Token associated with this expression */
  10536. char *zSpan; /* Original text of the expression */
  10537. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10538. unsigned done :1; /* A flag to indicate when processing is finished */
  10539. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  10540. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10541. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10542. } *a; /* Alloc a power of two greater or equal to nExpr */
  10543. };
  10544. /*
  10545. ** An instance of this structure is used by the parser to record both
  10546. ** the parse tree for an expression and the span of input text for an
  10547. ** expression.
  10548. */
  10549. struct ExprSpan {
  10550. Expr *pExpr; /* The expression parse tree */
  10551. const char *zStart; /* First character of input text */
  10552. const char *zEnd; /* One character past the end of input text */
  10553. };
  10554. /*
  10555. ** An instance of this structure can hold a simple list of identifiers,
  10556. ** such as the list "a,b,c" in the following statements:
  10557. **
  10558. ** INSERT INTO t(a,b,c) VALUES ...;
  10559. ** CREATE INDEX idx ON t(a,b,c);
  10560. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10561. **
  10562. ** The IdList.a.idx field is used when the IdList represents the list of
  10563. ** column names after a table name in an INSERT statement. In the statement
  10564. **
  10565. ** INSERT INTO t(a,b,c) ...
  10566. **
  10567. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10568. */
  10569. struct IdList {
  10570. struct IdList_item {
  10571. char *zName; /* Name of the identifier */
  10572. int idx; /* Index in some Table.aCol[] of a column named zName */
  10573. } *a;
  10574. int nId; /* Number of identifiers on the list */
  10575. };
  10576. /*
  10577. ** The bitmask datatype defined below is used for various optimizations.
  10578. **
  10579. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10580. ** tables in a join to 32 instead of 64. But it also reduces the size
  10581. ** of the library by 738 bytes on ix86.
  10582. */
  10583. typedef u64 Bitmask;
  10584. /*
  10585. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10586. */
  10587. #define BMS ((int)(sizeof(Bitmask)*8))
  10588. /*
  10589. ** The following structure describes the FROM clause of a SELECT statement.
  10590. ** Each table or subquery in the FROM clause is a separate element of
  10591. ** the SrcList.a[] array.
  10592. **
  10593. ** With the addition of multiple database support, the following structure
  10594. ** can also be used to describe a particular table such as the table that
  10595. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10596. ** such a table must be a simple name: ID. But in SQLite, the table can
  10597. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10598. **
  10599. ** The jointype starts out showing the join type between the current table
  10600. ** and the next table on the list. The parser builds the list this way.
  10601. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10602. ** jointype expresses the join between the table and the previous table.
  10603. **
  10604. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10605. ** contains more than 63 columns and the 64-th or later column is used.
  10606. */
  10607. struct SrcList {
  10608. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  10609. i16 nAlloc; /* Number of entries allocated in a[] below */
  10610. struct SrcList_item {
  10611. Schema *pSchema; /* Schema to which this item is fixed */
  10612. char *zDatabase; /* Name of database holding this table */
  10613. char *zName; /* Name of the table */
  10614. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10615. Table *pTab; /* An SQL table corresponding to zName */
  10616. Select *pSelect; /* A SELECT statement used in place of a table name */
  10617. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10618. int regReturn; /* Register holding return address of addrFillSub */
  10619. u8 jointype; /* Type of join between this able and the previous */
  10620. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10621. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10622. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10623. #ifndef SQLITE_OMIT_EXPLAIN
  10624. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10625. #endif
  10626. int iCursor; /* The VDBE cursor number used to access this table */
  10627. Expr *pOn; /* The ON clause of a join */
  10628. IdList *pUsing; /* The USING clause of a join */
  10629. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10630. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10631. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10632. } a[1]; /* One entry for each identifier on the list */
  10633. };
  10634. /*
  10635. ** Permitted values of the SrcList.a.jointype field
  10636. */
  10637. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10638. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10639. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10640. #define JT_LEFT 0x0008 /* Left outer join */
  10641. #define JT_RIGHT 0x0010 /* Right outer join */
  10642. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10643. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10644. /*
  10645. ** A WherePlan object holds information that describes a lookup
  10646. ** strategy.
  10647. **
  10648. ** This object is intended to be opaque outside of the where.c module.
  10649. ** It is included here only so that that compiler will know how big it
  10650. ** is. None of the fields in this object should be used outside of
  10651. ** the where.c module.
  10652. **
  10653. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  10654. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  10655. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  10656. ** case that more than one of these conditions is true.
  10657. */
  10658. struct WherePlan {
  10659. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  10660. u16 nEq; /* Number of == constraints */
  10661. u16 nOBSat; /* Number of ORDER BY terms satisfied */
  10662. double nRow; /* Estimated number of rows (for EQP) */
  10663. union {
  10664. Index *pIdx; /* Index when WHERE_INDEXED is true */
  10665. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  10666. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  10667. } u;
  10668. };
  10669. /*
  10670. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  10671. ** structure contains a single instance of this structure. This structure
  10672. ** is intended to be private to the where.c module and should not be
  10673. ** access or modified by other modules.
  10674. **
  10675. ** The pIdxInfo field is used to help pick the best index on a
  10676. ** virtual table. The pIdxInfo pointer contains indexing
  10677. ** information for the i-th table in the FROM clause before reordering.
  10678. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  10679. ** All other information in the i-th WhereLevel object for the i-th table
  10680. ** after FROM clause ordering.
  10681. */
  10682. struct WhereLevel {
  10683. WherePlan plan; /* query plan for this element of the FROM clause */
  10684. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  10685. int iTabCur; /* The VDBE cursor used to access the table */
  10686. int iIdxCur; /* The VDBE cursor used to access pIdx */
  10687. int addrBrk; /* Jump here to break out of the loop */
  10688. int addrNxt; /* Jump here to start the next IN combination */
  10689. int addrCont; /* Jump here to continue with the next loop cycle */
  10690. int addrFirst; /* First instruction of interior of the loop */
  10691. u8 iFrom; /* Which entry in the FROM clause */
  10692. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  10693. int p1, p2; /* Operands of the opcode used to ends the loop */
  10694. union { /* Information that depends on plan.wsFlags */
  10695. struct {
  10696. int nIn; /* Number of entries in aInLoop[] */
  10697. struct InLoop {
  10698. int iCur; /* The VDBE cursor used by this IN operator */
  10699. int addrInTop; /* Top of the IN loop */
  10700. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  10701. } *aInLoop; /* Information about each nested IN operator */
  10702. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  10703. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  10704. } u;
  10705. double rOptCost; /* "Optimal" cost for this level */
  10706. /* The following field is really not part of the current level. But
  10707. ** we need a place to cache virtual table index information for each
  10708. ** virtual table in the FROM clause and the WhereLevel structure is
  10709. ** a convenient place since there is one WhereLevel for each FROM clause
  10710. ** element.
  10711. */
  10712. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  10713. };
  10714. /*
  10715. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10716. ** and the WhereInfo.wctrlFlags member.
  10717. */
  10718. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10719. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10720. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10721. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10722. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10723. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10724. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10725. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10726. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10727. /*
  10728. ** The WHERE clause processing routine has two halves. The
  10729. ** first part does the start of the WHERE loop and the second
  10730. ** half does the tail of the WHERE loop. An instance of
  10731. ** this structure is returned by the first half and passed
  10732. ** into the second half to give some continuity.
  10733. */
  10734. struct WhereInfo {
  10735. Parse *pParse; /* Parsing and code generating context */
  10736. SrcList *pTabList; /* List of tables in the join */
  10737. u16 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  10738. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  10739. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  10740. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  10741. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  10742. int iTop; /* The very beginning of the WHERE loop */
  10743. int iContinue; /* Jump here to continue with next record */
  10744. int iBreak; /* Jump here to break out of the loop */
  10745. int nLevel; /* Number of nested loop */
  10746. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  10747. double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  10748. double nRowOut; /* Estimated number of output rows */
  10749. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  10750. };
  10751. /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
  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 named expressions */
  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_AsMaybe 0x10 /* Resolve to AS terms of the result set only
  10795. ** if no other resolution is available */
  10796. /*
  10797. ** An instance of the following structure contains all information
  10798. ** needed to generate code for a single SELECT statement.
  10799. **
  10800. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10801. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10802. ** limit and nOffset to the value of the offset (or 0 if there is not
  10803. ** offset). But later on, nLimit and nOffset become the memory locations
  10804. ** in the VDBE that record the limit and offset counters.
  10805. **
  10806. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10807. ** These addresses must be stored so that we can go back and fill in
  10808. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10809. ** the number of columns in P2 can be computed at the same time
  10810. ** as the OP_OpenEphm instruction is coded because not
  10811. ** enough information about the compound query is known at that point.
  10812. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10813. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10814. ** sequences for the ORDER BY clause.
  10815. */
  10816. struct Select {
  10817. ExprList *pEList; /* The fields of the result */
  10818. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10819. u16 selFlags; /* Various SF_* values */
  10820. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10821. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10822. double nSelectRow; /* Estimated number of result rows */
  10823. SrcList *pSrc; /* The FROM clause */
  10824. Expr *pWhere; /* The WHERE clause */
  10825. ExprList *pGroupBy; /* The GROUP BY clause */
  10826. Expr *pHaving; /* The HAVING clause */
  10827. ExprList *pOrderBy; /* The ORDER BY clause */
  10828. Select *pPrior; /* Prior select in a compound select statement */
  10829. Select *pNext; /* Next select to the left in a compound */
  10830. Select *pRightmost; /* Right-most select in a compound select statement */
  10831. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10832. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10833. };
  10834. /*
  10835. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10836. ** "Select Flag".
  10837. */
  10838. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10839. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10840. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10841. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10842. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10843. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10844. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10845. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10846. #define SF_Materialize 0x0100 /* Force materialization of views */
  10847. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  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. int aTempReg[8]; /* Holding area for temporary registers */
  10960. int nRangeReg; /* Size of the temporary register block */
  10961. int iRangeReg; /* First register in temporary register block */
  10962. int nErr; /* Number of errors seen */
  10963. int nTab; /* Number of previously allocated VDBE cursors */
  10964. int nMem; /* Number of memory cells used so far */
  10965. int nSet; /* Number of sets used so far */
  10966. int nOnce; /* Number of OP_Once instructions so far */
  10967. int ckBase; /* Base register of data during check constraints */
  10968. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10969. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10970. struct yColCache {
  10971. int iTable; /* Table cursor number */
  10972. int iColumn; /* Table column number */
  10973. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10974. int iLevel; /* Nesting level */
  10975. int iReg; /* Reg with value of this column. 0 means none. */
  10976. int lru; /* Least recently used entry has the smallest value */
  10977. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10978. yDbMask writeMask; /* Start a write transaction on these databases */
  10979. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10980. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10981. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10982. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10983. int regRoot; /* Register holding root page number for new objects */
  10984. int nMaxArg; /* Max args passed to user function by sub-program */
  10985. Token constraintName;/* Name of the constraint currently being parsed */
  10986. #ifndef SQLITE_OMIT_SHARED_CACHE
  10987. int nTableLock; /* Number of locks in aTableLock */
  10988. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  10989. #endif
  10990. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  10991. /* Information used while coding trigger programs. */
  10992. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  10993. Table *pTriggerTab; /* Table triggers are being coded for */
  10994. double nQueryLoop; /* Estimated number of iterations of a query */
  10995. u32 oldmask; /* Mask of old.* columns referenced */
  10996. u32 newmask; /* Mask of new.* columns referenced */
  10997. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  10998. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  10999. u8 disableTriggers; /* True to disable triggers */
  11000. /* Above is constant between recursions. Below is reset before and after
  11001. ** each recursion */
  11002. int nVar; /* Number of '?' variables seen in the SQL so far */
  11003. int nzVar; /* Number of available slots in azVar[] */
  11004. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11005. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11006. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11007. int nVtabLock; /* Number of virtual tables to lock */
  11008. #endif
  11009. int nAlias; /* Number of aliased result set columns */
  11010. int nHeight; /* Expression tree height of current sub-select */
  11011. #ifndef SQLITE_OMIT_EXPLAIN
  11012. int iSelectId; /* ID of current select for EXPLAIN output */
  11013. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11014. #endif
  11015. char **azVar; /* Pointers to names of parameters */
  11016. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11017. int *aAlias; /* Register used to hold aliased result */
  11018. const char *zTail; /* All SQL text past the last semicolon parsed */
  11019. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11020. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11021. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11022. Token sNameToken; /* Token with unqualified schema object name */
  11023. Token sLastToken; /* The last token parsed */
  11024. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11025. Token sArg; /* Complete text of a module argument */
  11026. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11027. #endif
  11028. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11029. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11030. };
  11031. /*
  11032. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11033. */
  11034. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11035. #define IN_DECLARE_VTAB 0
  11036. #else
  11037. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11038. #endif
  11039. /*
  11040. ** An instance of the following structure can be declared on a stack and used
  11041. ** to save the Parse.zAuthContext value so that it can be restored later.
  11042. */
  11043. struct AuthContext {
  11044. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11045. Parse *pParse; /* The Parse structure */
  11046. };
  11047. /*
  11048. ** Bitfield flags for P5 value in various opcodes.
  11049. */
  11050. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11051. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11052. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11053. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11054. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11055. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  11056. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11057. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11058. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11059. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11060. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11061. /*
  11062. * Each trigger present in the database schema is stored as an instance of
  11063. * struct Trigger.
  11064. *
  11065. * Pointers to instances of struct Trigger are stored in two ways.
  11066. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11067. * database). This allows Trigger structures to be retrieved by name.
  11068. * 2. All triggers associated with a single table form a linked list, using the
  11069. * pNext member of struct Trigger. A pointer to the first element of the
  11070. * linked list is stored as the "pTrigger" member of the associated
  11071. * struct Table.
  11072. *
  11073. * The "step_list" member points to the first element of a linked list
  11074. * containing the SQL statements specified as the trigger program.
  11075. */
  11076. struct Trigger {
  11077. char *zName; /* The name of the trigger */
  11078. char *table; /* The table or view to which the trigger applies */
  11079. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11080. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11081. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11082. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11083. the <column-list> is stored here */
  11084. Schema *pSchema; /* Schema containing the trigger */
  11085. Schema *pTabSchema; /* Schema containing the table */
  11086. TriggerStep *step_list; /* Link list of trigger program steps */
  11087. Trigger *pNext; /* Next trigger associated with the table */
  11088. };
  11089. /*
  11090. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11091. ** determine which.
  11092. **
  11093. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11094. ** In that cases, the constants below can be ORed together.
  11095. */
  11096. #define TRIGGER_BEFORE 1
  11097. #define TRIGGER_AFTER 2
  11098. /*
  11099. * An instance of struct TriggerStep is used to store a single SQL statement
  11100. * that is a part of a trigger-program.
  11101. *
  11102. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11103. * using the "pNext" member) referenced by the "step_list" member of the
  11104. * associated struct Trigger instance. The first element of the linked list is
  11105. * the first step of the trigger-program.
  11106. *
  11107. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11108. * "SELECT" statement. The meanings of the other members is determined by the
  11109. * value of "op" as follows:
  11110. *
  11111. * (op == TK_INSERT)
  11112. * orconf -> stores the ON CONFLICT algorithm
  11113. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11114. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11115. * target -> A token holding the quoted name of the table to insert into.
  11116. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11117. * this stores values to be inserted. Otherwise NULL.
  11118. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11119. * statement, then this stores the column-names to be
  11120. * inserted into.
  11121. *
  11122. * (op == TK_DELETE)
  11123. * target -> A token holding the quoted name of the table to delete from.
  11124. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11125. * Otherwise NULL.
  11126. *
  11127. * (op == TK_UPDATE)
  11128. * target -> A token holding the quoted name of the table to update rows of.
  11129. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11130. * Otherwise NULL.
  11131. * pExprList -> A list of the columns to update and the expressions to update
  11132. * them to. See sqlite3Update() documentation of "pChanges"
  11133. * argument.
  11134. *
  11135. */
  11136. struct TriggerStep {
  11137. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11138. u8 orconf; /* OE_Rollback etc. */
  11139. Trigger *pTrig; /* The trigger that this step is a part of */
  11140. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11141. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11142. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11143. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  11144. IdList *pIdList; /* Column names for INSERT */
  11145. TriggerStep *pNext; /* Next in the link-list */
  11146. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11147. };
  11148. /*
  11149. ** The following structure contains information used by the sqliteFix...
  11150. ** routines as they walk the parse tree to make database references
  11151. ** explicit.
  11152. */
  11153. typedef struct DbFixer DbFixer;
  11154. struct DbFixer {
  11155. Parse *pParse; /* The parsing context. Error messages written here */
  11156. Schema *pSchema; /* Fix items to this schema */
  11157. const char *zDb; /* Make sure all objects are contained in this database */
  11158. const char *zType; /* Type of the container - used for error messages */
  11159. const Token *pName; /* Name of the container - used for error messages */
  11160. };
  11161. /*
  11162. ** An objected used to accumulate the text of a string where we
  11163. ** do not necessarily know how big the string will be in the end.
  11164. */
  11165. struct StrAccum {
  11166. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11167. char *zBase; /* A base allocation. Not from malloc. */
  11168. char *zText; /* The string collected so far */
  11169. int nChar; /* Length of the string so far */
  11170. int nAlloc; /* Amount of space allocated in zText */
  11171. int mxAlloc; /* Maximum allowed string length */
  11172. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  11173. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11174. u8 tooBig; /* Becomes true if string size exceeds limits */
  11175. };
  11176. /*
  11177. ** A pointer to this structure is used to communicate information
  11178. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11179. */
  11180. typedef struct {
  11181. sqlite3 *db; /* The database being initialized */
  11182. char **pzErrMsg; /* Error message stored here */
  11183. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11184. int rc; /* Result code stored here */
  11185. } InitData;
  11186. /*
  11187. ** Structure containing global configuration data for the SQLite library.
  11188. **
  11189. ** This structure also contains some state information.
  11190. */
  11191. struct Sqlite3Config {
  11192. int bMemstat; /* True to enable memory status */
  11193. int bCoreMutex; /* True to enable core mutexing */
  11194. int bFullMutex; /* True to enable full mutexing */
  11195. int bOpenUri; /* True to interpret filenames as URIs */
  11196. int bUseCis; /* Use covering indices for full-scans */
  11197. int mxStrlen; /* Maximum string length */
  11198. int szLookaside; /* Default lookaside buffer size */
  11199. int nLookaside; /* Default lookaside buffer count */
  11200. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11201. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11202. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11203. void *pHeap; /* Heap storage space */
  11204. int nHeap; /* Size of pHeap[] */
  11205. int mnReq, mxReq; /* Min and max heap requests sizes */
  11206. sqlite3_int64 szMmap; /* mmap() space per open file */
  11207. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11208. void *pScratch; /* Scratch memory */
  11209. int szScratch; /* Size of each scratch buffer */
  11210. int nScratch; /* Number of scratch buffers */
  11211. void *pPage; /* Page cache memory */
  11212. int szPage; /* Size of each page in pPage[] */
  11213. int nPage; /* Number of pages in pPage[] */
  11214. int mxParserStack; /* maximum depth of the parser stack */
  11215. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11216. /* The above might be initialized to non-zero. The following need to always
  11217. ** initially be zero, however. */
  11218. int isInit; /* True after initialization has finished */
  11219. int inProgress; /* True while initialization in progress */
  11220. int isMutexInit; /* True after mutexes are initialized */
  11221. int isMallocInit; /* True after malloc is initialized */
  11222. int isPCacheInit; /* True after malloc is initialized */
  11223. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11224. int nRefInitMutex; /* Number of users of pInitMutex */
  11225. void (*xLog)(void*,int,const char*); /* Function for logging */
  11226. void *pLogArg; /* First argument to xLog() */
  11227. int bLocaltimeFault; /* True to fail localtime() calls */
  11228. #ifdef SQLITE_ENABLE_SQLLOG
  11229. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11230. void *pSqllogArg;
  11231. #endif
  11232. };
  11233. /*
  11234. ** Context pointer passed down through the tree-walk.
  11235. */
  11236. struct Walker {
  11237. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11238. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11239. Parse *pParse; /* Parser context. */
  11240. int walkerDepth; /* Number of subqueries */
  11241. u8 bSelectDepthFirst; /* Do subqueries first */
  11242. union { /* Extra data for callback */
  11243. NameContext *pNC; /* Naming context */
  11244. int i; /* Integer value */
  11245. SrcList *pSrcList; /* FROM clause */
  11246. struct SrcCount *pSrcCount; /* Counting column references */
  11247. } u;
  11248. };
  11249. /* Forward declarations */
  11250. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11251. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11252. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11253. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11254. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11255. /*
  11256. ** Return code from the parse-tree walking primitives and their
  11257. ** callbacks.
  11258. */
  11259. #define WRC_Continue 0 /* Continue down into children */
  11260. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11261. #define WRC_Abort 2 /* Abandon the tree walk */
  11262. /*
  11263. ** Assuming zIn points to the first byte of a UTF-8 character,
  11264. ** advance zIn to point to the first byte of the next UTF-8 character.
  11265. */
  11266. #define SQLITE_SKIP_UTF8(zIn) { \
  11267. if( (*(zIn++))>=0xc0 ){ \
  11268. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11269. } \
  11270. }
  11271. /*
  11272. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11273. ** the same name but without the _BKPT suffix. These macros invoke
  11274. ** routines that report the line-number on which the error originated
  11275. ** using sqlite3_log(). The routines also provide a convenient place
  11276. ** to set a debugger breakpoint.
  11277. */
  11278. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11279. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11280. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11281. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11282. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11283. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11284. /*
  11285. ** FTS4 is really an extension for FTS3. It is enabled using the
  11286. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11287. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11288. */
  11289. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11290. # define SQLITE_ENABLE_FTS3
  11291. #endif
  11292. /*
  11293. ** The ctype.h header is needed for non-ASCII systems. It is also
  11294. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11295. */
  11296. #if !defined(SQLITE_ASCII) || \
  11297. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11298. # include <ctype.h>
  11299. #endif
  11300. /*
  11301. ** The following macros mimic the standard library functions toupper(),
  11302. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11303. ** sqlite versions only work for ASCII characters, regardless of locale.
  11304. */
  11305. #ifdef SQLITE_ASCII
  11306. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11307. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11308. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11309. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11310. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11311. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11312. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11313. #else
  11314. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11315. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11316. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11317. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11318. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11319. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11320. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11321. #endif
  11322. /*
  11323. ** Internal function prototypes
  11324. */
  11325. #define sqlite3StrICmp sqlite3_stricmp
  11326. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11327. #define sqlite3StrNICmp sqlite3_strnicmp
  11328. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11329. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11330. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11331. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11332. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11333. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11334. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11335. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11336. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11337. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11338. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11339. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11340. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11341. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11342. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11343. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11344. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11345. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11346. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11347. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11348. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11349. /*
  11350. ** On systems with ample stack space and that support alloca(), make
  11351. ** use of alloca() to obtain space for large automatic objects. By default,
  11352. ** obtain space from malloc().
  11353. **
  11354. ** The alloca() routine never returns NULL. This will cause code paths
  11355. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11356. */
  11357. #ifdef SQLITE_USE_ALLOCA
  11358. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11359. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11360. # define sqlite3StackFree(D,P)
  11361. #else
  11362. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11363. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11364. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11365. #endif
  11366. #ifdef SQLITE_ENABLE_MEMSYS3
  11367. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11368. #endif
  11369. #ifdef SQLITE_ENABLE_MEMSYS5
  11370. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11371. #endif
  11372. #ifndef SQLITE_MUTEX_OMIT
  11373. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11374. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11375. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11376. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11377. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11378. #endif
  11379. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11380. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11381. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11382. #ifndef SQLITE_OMIT_FLOATING_POINT
  11383. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11384. #else
  11385. # define sqlite3IsNaN(X) 0
  11386. #endif
  11387. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11388. #ifndef SQLITE_OMIT_TRACE
  11389. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11390. #endif
  11391. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11392. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11393. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11394. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11395. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11396. #endif
  11397. #if defined(SQLITE_TEST)
  11398. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11399. #endif
  11400. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11401. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11402. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11403. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11404. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11405. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11406. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11407. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11408. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11409. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11410. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11411. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11412. #else
  11413. # define sqlite3ExplainBegin(X)
  11414. # define sqlite3ExplainSelect(A,B)
  11415. # define sqlite3ExplainExpr(A,B)
  11416. # define sqlite3ExplainExprList(A,B)
  11417. # define sqlite3ExplainFinish(X)
  11418. # define sqlite3VdbeExplanation(X) 0
  11419. #endif
  11420. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11421. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11422. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11423. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11424. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11425. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11426. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11427. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11428. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11429. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11430. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11431. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11432. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11433. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11434. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11435. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11436. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11437. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11438. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11439. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11440. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11441. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11442. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11443. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11444. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11445. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11446. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11447. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11448. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11449. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11450. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11451. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11452. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11453. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11454. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11455. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11456. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11457. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11458. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11459. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11460. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11461. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11462. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11463. sqlite3_vfs**,char**,char **);
  11464. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11465. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11466. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11467. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11468. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11469. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11470. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11471. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11472. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11473. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11474. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11475. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11476. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11477. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11478. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11479. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11480. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11481. #else
  11482. # define sqlite3ViewGetColumnNames(A,B) 0
  11483. #endif
  11484. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11485. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11486. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11487. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11488. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11489. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11490. #else
  11491. # define sqlite3AutoincrementBegin(X)
  11492. # define sqlite3AutoincrementEnd(X)
  11493. #endif
  11494. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11495. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11496. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11497. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11498. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11499. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11500. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11501. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11502. Token*, Select*, Expr*, IdList*);
  11503. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11504. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11505. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11506. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11507. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11508. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11509. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11510. Token*, int, int);
  11511. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11512. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11513. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11514. Expr*,ExprList*,u16,Expr*,Expr*);
  11515. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11516. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11517. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11518. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11519. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11520. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  11521. #endif
  11522. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11523. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11524. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11525. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11526. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11527. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11528. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11529. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11530. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11531. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11532. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11533. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11534. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11535. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11536. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11537. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11538. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11539. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11540. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11541. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11542. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11543. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11544. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11545. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11546. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11547. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11548. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11549. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11550. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11551. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11552. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  11553. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
  11554. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11555. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11556. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11557. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11558. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11559. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11560. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11561. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11562. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11563. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11564. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11565. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11566. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11567. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11568. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11569. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11570. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11571. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11572. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11573. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11574. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11575. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11576. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11577. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11578. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11579. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11580. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  11581. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11582. int*,int,int,int,int,int*);
  11583. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11584. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11585. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11586. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11587. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11588. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  11589. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11590. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11591. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11592. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11593. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11594. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11595. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11596. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11597. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11598. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11599. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11600. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11601. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11602. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11603. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11604. #endif
  11605. #ifndef SQLITE_OMIT_TRIGGER
  11606. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11607. Expr*,int, int);
  11608. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11609. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11610. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11611. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11612. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11613. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11614. int, int, int);
  11615. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11616. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11617. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11618. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11619. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11620. ExprList*,Select*,u8);
  11621. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11622. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11623. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11624. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11625. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11626. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11627. #else
  11628. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11629. # define sqlite3DeleteTrigger(A,B)
  11630. # define sqlite3DropTriggerPtr(A,B)
  11631. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11632. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11633. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11634. # define sqlite3TriggerList(X, Y) 0
  11635. # define sqlite3ParseToplevel(p) p
  11636. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11637. #endif
  11638. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11639. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11640. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11641. #ifndef SQLITE_OMIT_AUTHORIZATION
  11642. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11643. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11644. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11645. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11646. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11647. #else
  11648. # define sqlite3AuthRead(a,b,c,d)
  11649. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11650. # define sqlite3AuthContextPush(a,b,c)
  11651. # define sqlite3AuthContextPop(a) ((void)(a))
  11652. #endif
  11653. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11654. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11655. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11656. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11657. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11658. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11659. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11660. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11661. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11662. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11663. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11664. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11665. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11666. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11667. /*
  11668. ** Routines to read and write variable-length integers. These used to
  11669. ** be defined locally, but now we use the varint routines in the util.c
  11670. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11671. ** are coded to assume the single byte case is already handled (which
  11672. ** the MACRO form does).
  11673. */
  11674. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11675. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11676. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11677. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11678. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11679. /*
  11680. ** The header of a record consists of a sequence variable-length integers.
  11681. ** These integers are almost always small and are encoded as a single byte.
  11682. ** The following macros take advantage this fact to provide a fast encode
  11683. ** and decode of the integers in a record header. It is faster for the common
  11684. ** case where the integer is a single byte. It is a little slower when the
  11685. ** integer is two or more bytes. But overall it is faster.
  11686. **
  11687. ** The following expressions are equivalent:
  11688. **
  11689. ** x = sqlite3GetVarint32( A, &B );
  11690. ** x = sqlite3PutVarint32( A, B );
  11691. **
  11692. ** x = getVarint32( A, B );
  11693. ** x = putVarint32( A, B );
  11694. **
  11695. */
  11696. #define getVarint32(A,B) \
  11697. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  11698. #define putVarint32(A,B) \
  11699. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  11700. sqlite3PutVarint32((A),(B)))
  11701. #define getVarint sqlite3GetVarint
  11702. #define putVarint sqlite3PutVarint
  11703. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11704. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11705. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11706. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11707. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11708. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11709. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11710. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11711. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11712. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11713. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  11714. defined(SQLITE_DEBUG_OS_TRACE)
  11715. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  11716. #endif
  11717. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11718. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11719. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11720. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11721. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11722. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11723. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11724. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11725. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11726. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11727. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11728. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11729. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11730. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11731. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11732. #ifdef SQLITE_ENABLE_8_3_NAMES
  11733. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11734. #else
  11735. # define sqlite3FileSuffix3(X,Y)
  11736. #endif
  11737. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11738. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11739. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11740. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11741. void(*)(void*));
  11742. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11743. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11744. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11745. #ifdef SQLITE_ENABLE_STAT3
  11746. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
  11747. #endif
  11748. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11749. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11750. #ifndef SQLITE_AMALGAMATION
  11751. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11752. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11753. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11754. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11755. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11756. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11757. #ifndef SQLITE_OMIT_WSD
  11758. SQLITE_PRIVATE int sqlite3PendingByte;
  11759. #endif
  11760. #endif
  11761. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11762. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11763. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11764. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11765. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11766. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11767. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11768. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11769. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11770. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  11771. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11772. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11773. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11774. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11775. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11776. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11777. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11778. SQLITE_PRIVATE char sqlite3AffinityType(const char*);
  11779. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11780. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11781. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11782. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11783. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11784. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11785. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11786. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11787. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11788. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11789. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11790. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11791. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11792. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11793. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11794. void (*)(sqlite3_context*,int,sqlite3_value **),
  11795. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11796. FuncDestructor *pDestructor
  11797. );
  11798. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11799. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11800. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11801. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11802. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11803. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11804. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11805. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11806. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11807. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11808. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11809. /*
  11810. ** The interface to the LEMON-generated parser
  11811. */
  11812. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11813. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11814. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11815. #ifdef YYTRACKMAXSTACKDEPTH
  11816. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11817. #endif
  11818. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11819. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11820. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11821. #else
  11822. # define sqlite3CloseExtensions(X)
  11823. #endif
  11824. #ifndef SQLITE_OMIT_SHARED_CACHE
  11825. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11826. #else
  11827. #define sqlite3TableLock(v,w,x,y,z)
  11828. #endif
  11829. #ifdef SQLITE_TEST
  11830. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11831. #endif
  11832. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11833. # define sqlite3VtabClear(Y)
  11834. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11835. # define sqlite3VtabRollback(X)
  11836. # define sqlite3VtabCommit(X)
  11837. # define sqlite3VtabInSync(db) 0
  11838. # define sqlite3VtabLock(X)
  11839. # define sqlite3VtabUnlock(X)
  11840. # define sqlite3VtabUnlockList(X)
  11841. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11842. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11843. #else
  11844. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11845. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11846. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  11847. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11848. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11849. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11850. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11851. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11852. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11853. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11854. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11855. #endif
  11856. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11857. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11858. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11859. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11860. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11861. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11862. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11863. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11864. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11865. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11866. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11867. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11868. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11869. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11870. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11871. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11872. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11873. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11874. #ifndef SQLITE_OMIT_WAL
  11875. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11876. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11877. #endif
  11878. /* Declarations for functions in fkey.c. All of these are replaced by
  11879. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11880. ** key functionality is available. If OMIT_TRIGGER is defined but
  11881. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11882. ** this case foreign keys are parsed, but no other functionality is
  11883. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11884. */
  11885. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11886. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
  11887. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11888. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
  11889. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11890. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11891. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11892. #else
  11893. #define sqlite3FkActions(a,b,c,d)
  11894. #define sqlite3FkCheck(a,b,c,d)
  11895. #define sqlite3FkDropTable(a,b,c)
  11896. #define sqlite3FkOldmask(a,b) 0
  11897. #define sqlite3FkRequired(a,b,c,d) 0
  11898. #endif
  11899. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11900. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11901. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  11902. #else
  11903. #define sqlite3FkDelete(a,b)
  11904. #define sqlite3FkLocateIndex(a,b,c,d,e)
  11905. #endif
  11906. /*
  11907. ** Available fault injectors. Should be numbered beginning with 0.
  11908. */
  11909. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11910. #define SQLITE_FAULTINJECTOR_COUNT 1
  11911. /*
  11912. ** The interface to the code in fault.c used for identifying "benign"
  11913. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11914. ** is not defined.
  11915. */
  11916. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11917. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11918. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11919. #else
  11920. #define sqlite3BeginBenignMalloc()
  11921. #define sqlite3EndBenignMalloc()
  11922. #endif
  11923. #define IN_INDEX_ROWID 1
  11924. #define IN_INDEX_EPH 2
  11925. #define IN_INDEX_INDEX_ASC 3
  11926. #define IN_INDEX_INDEX_DESC 4
  11927. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11928. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11929. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11930. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11931. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11932. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  11933. #else
  11934. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11935. #define sqlite3JournalExists(p) 1
  11936. #endif
  11937. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11938. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11939. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11940. #if SQLITE_MAX_EXPR_DEPTH>0
  11941. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11942. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11943. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11944. #else
  11945. #define sqlite3ExprSetHeight(x,y)
  11946. #define sqlite3SelectExprHeight(x) 0
  11947. #define sqlite3ExprCheckHeight(x,y)
  11948. #endif
  11949. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11950. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11951. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11952. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11953. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11954. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11955. #else
  11956. #define sqlite3ConnectionBlocked(x,y)
  11957. #define sqlite3ConnectionUnlocked(x)
  11958. #define sqlite3ConnectionClosed(x)
  11959. #endif
  11960. #ifdef SQLITE_DEBUG
  11961. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11962. #endif
  11963. /*
  11964. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11965. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11966. ** print I/O tracing messages.
  11967. */
  11968. #ifdef SQLITE_ENABLE_IOTRACE
  11969. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  11970. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  11971. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  11972. #else
  11973. # define IOTRACE(A)
  11974. # define sqlite3VdbeIOTraceSql(X)
  11975. #endif
  11976. /*
  11977. ** These routines are available for the mem2.c debugging memory allocator
  11978. ** only. They are used to verify that different "types" of memory
  11979. ** allocations are properly tracked by the system.
  11980. **
  11981. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  11982. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  11983. ** a single bit set.
  11984. **
  11985. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  11986. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11987. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  11988. **
  11989. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  11990. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11991. **
  11992. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  11993. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  11994. ** it might have been allocated by lookaside, except the allocation was
  11995. ** too large or lookaside was already full. It is important to verify
  11996. ** that allocations that might have been satisfied by lookaside are not
  11997. ** passed back to non-lookaside free() routines. Asserts such as the
  11998. ** example above are placed on the non-lookaside free() routines to verify
  11999. ** this constraint.
  12000. **
  12001. ** All of this is no-op for a production build. It only comes into
  12002. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12003. */
  12004. #ifdef SQLITE_MEMDEBUG
  12005. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12006. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12007. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12008. #else
  12009. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12010. # define sqlite3MemdebugHasType(X,Y) 1
  12011. # define sqlite3MemdebugNoType(X,Y) 1
  12012. #endif
  12013. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12014. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  12015. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12016. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12017. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  12018. #endif /* _SQLITEINT_H_ */
  12019. /************** End of sqliteInt.h *******************************************/
  12020. /************** Begin file global.c ******************************************/
  12021. /*
  12022. ** 2008 June 13
  12023. **
  12024. ** The author disclaims copyright to this source code. In place of
  12025. ** a legal notice, here is a blessing:
  12026. **
  12027. ** May you do good and not evil.
  12028. ** May you find forgiveness for yourself and forgive others.
  12029. ** May you share freely, never taking more than you give.
  12030. **
  12031. *************************************************************************
  12032. **
  12033. ** This file contains definitions of global variables and contants.
  12034. */
  12035. /* An array to map all upper-case characters into their corresponding
  12036. ** lower-case character.
  12037. **
  12038. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12039. ** handle case conversions for the UTF character set since the tables
  12040. ** involved are nearly as big or bigger than SQLite itself.
  12041. */
  12042. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12043. #ifdef SQLITE_ASCII
  12044. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12045. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12046. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12047. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12048. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12049. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12050. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12051. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12052. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12053. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12054. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12055. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12056. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12057. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12058. 252,253,254,255
  12059. #endif
  12060. #ifdef SQLITE_EBCDIC
  12061. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12062. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12063. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12064. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12065. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12066. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12067. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12068. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12069. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12070. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12071. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12072. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12073. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12074. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12075. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12076. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12077. #endif
  12078. };
  12079. /*
  12080. ** The following 256 byte lookup table is used to support SQLites built-in
  12081. ** equivalents to the following standard library functions:
  12082. **
  12083. ** isspace() 0x01
  12084. ** isalpha() 0x02
  12085. ** isdigit() 0x04
  12086. ** isalnum() 0x06
  12087. ** isxdigit() 0x08
  12088. ** toupper() 0x20
  12089. ** SQLite identifier character 0x40
  12090. **
  12091. ** Bit 0x20 is set if the mapped character requires translation to upper
  12092. ** case. i.e. if the character is a lower-case ASCII character.
  12093. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12094. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12095. **
  12096. ** (x & ~(map[x]&0x20))
  12097. **
  12098. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12099. ** array. tolower() is used more often than toupper() by SQLite.
  12100. **
  12101. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12102. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12103. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12104. ** part of an identifier is 0x46.
  12105. **
  12106. ** SQLite's versions are identical to the standard versions assuming a
  12107. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12108. */
  12109. #ifdef SQLITE_ASCII
  12110. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12111. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12112. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12113. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12114. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12115. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12116. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12117. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12118. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12119. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12120. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12121. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12122. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12123. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12124. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12125. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12126. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12127. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12128. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12129. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12130. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12131. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12132. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12133. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12134. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12135. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12136. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12137. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12138. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12139. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12140. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12141. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12142. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12143. };
  12144. #endif
  12145. #ifndef SQLITE_USE_URI
  12146. # define SQLITE_USE_URI 0
  12147. #endif
  12148. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12149. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12150. #endif
  12151. /*
  12152. ** The following singleton contains the global configuration for
  12153. ** the SQLite library.
  12154. */
  12155. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12156. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12157. 1, /* bCoreMutex */
  12158. SQLITE_THREADSAFE==1, /* bFullMutex */
  12159. SQLITE_USE_URI, /* bOpenUri */
  12160. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12161. 0x7ffffffe, /* mxStrlen */
  12162. 128, /* szLookaside */
  12163. 500, /* nLookaside */
  12164. {0,0,0,0,0,0,0,0}, /* m */
  12165. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12166. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12167. (void*)0, /* pHeap */
  12168. 0, /* nHeap */
  12169. 0, 0, /* mnHeap, mxHeap */
  12170. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12171. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12172. (void*)0, /* pScratch */
  12173. 0, /* szScratch */
  12174. 0, /* nScratch */
  12175. (void*)0, /* pPage */
  12176. 0, /* szPage */
  12177. 0, /* nPage */
  12178. 0, /* mxParserStack */
  12179. 0, /* sharedCacheEnabled */
  12180. /* All the rest should always be initialized to zero */
  12181. 0, /* isInit */
  12182. 0, /* inProgress */
  12183. 0, /* isMutexInit */
  12184. 0, /* isMallocInit */
  12185. 0, /* isPCacheInit */
  12186. 0, /* pInitMutex */
  12187. 0, /* nRefInitMutex */
  12188. 0, /* xLog */
  12189. 0, /* pLogArg */
  12190. 0, /* bLocaltimeFault */
  12191. #ifdef SQLITE_ENABLE_SQLLOG
  12192. 0, /* xSqllog */
  12193. 0 /* pSqllogArg */
  12194. #endif
  12195. };
  12196. /*
  12197. ** Hash table for global functions - functions common to all
  12198. ** database connections. After initialization, this table is
  12199. ** read-only.
  12200. */
  12201. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12202. /*
  12203. ** Constant tokens for values 0 and 1.
  12204. */
  12205. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12206. { "0", 1 },
  12207. { "1", 1 }
  12208. };
  12209. /*
  12210. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12211. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12212. ** the database page that contains the pending byte. It never attempts
  12213. ** to read or write that page. The pending byte page is set assign
  12214. ** for use by the VFS layers as space for managing file locks.
  12215. **
  12216. ** During testing, it is often desirable to move the pending byte to
  12217. ** a different position in the file. This allows code that has to
  12218. ** deal with the pending byte to run on files that are much smaller
  12219. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12220. ** move the pending byte.
  12221. **
  12222. ** IMPORTANT: Changing the pending byte to any value other than
  12223. ** 0x40000000 results in an incompatible database file format!
  12224. ** Changing the pending byte during operating results in undefined
  12225. ** and dileterious behavior.
  12226. */
  12227. #ifndef SQLITE_OMIT_WSD
  12228. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12229. #endif
  12230. /*
  12231. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12232. ** created by mkopcodeh.awk during compilation. Data is obtained
  12233. ** from the comments following the "case OP_xxxx:" statements in
  12234. ** the vdbe.c file.
  12235. */
  12236. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12237. /************** End of global.c **********************************************/
  12238. /************** Begin file ctime.c *******************************************/
  12239. /*
  12240. ** 2010 February 23
  12241. **
  12242. ** The author disclaims copyright to this source code. In place of
  12243. ** a legal notice, here is a blessing:
  12244. **
  12245. ** May you do good and not evil.
  12246. ** May you find forgiveness for yourself and forgive others.
  12247. ** May you share freely, never taking more than you give.
  12248. **
  12249. *************************************************************************
  12250. **
  12251. ** This file implements routines used to report what compile-time options
  12252. ** SQLite was built with.
  12253. */
  12254. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12255. /*
  12256. ** An array of names of all compile-time options. This array should
  12257. ** be sorted A-Z.
  12258. **
  12259. ** This array looks large, but in a typical installation actually uses
  12260. ** only a handful of compile-time options, so most times this array is usually
  12261. ** rather short and uses little memory space.
  12262. */
  12263. static const char * const azCompileOpt[] = {
  12264. /* These macros are provided to "stringify" the value of the define
  12265. ** for those options in which the value is meaningful. */
  12266. #define CTIMEOPT_VAL_(opt) #opt
  12267. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12268. #ifdef SQLITE_32BIT_ROWID
  12269. "32BIT_ROWID",
  12270. #endif
  12271. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12272. "4_BYTE_ALIGNED_MALLOC",
  12273. #endif
  12274. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12275. "CASE_SENSITIVE_LIKE",
  12276. #endif
  12277. #ifdef SQLITE_CHECK_PAGES
  12278. "CHECK_PAGES",
  12279. #endif
  12280. #ifdef SQLITE_COVERAGE_TEST
  12281. "COVERAGE_TEST",
  12282. #endif
  12283. #ifdef SQLITE_DEBUG
  12284. "DEBUG",
  12285. #endif
  12286. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12287. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12288. #endif
  12289. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  12290. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  12291. #endif
  12292. #ifdef SQLITE_DISABLE_DIRSYNC
  12293. "DISABLE_DIRSYNC",
  12294. #endif
  12295. #ifdef SQLITE_DISABLE_LFS
  12296. "DISABLE_LFS",
  12297. #endif
  12298. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12299. "ENABLE_ATOMIC_WRITE",
  12300. #endif
  12301. #ifdef SQLITE_ENABLE_CEROD
  12302. "ENABLE_CEROD",
  12303. #endif
  12304. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12305. "ENABLE_COLUMN_METADATA",
  12306. #endif
  12307. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12308. "ENABLE_EXPENSIVE_ASSERT",
  12309. #endif
  12310. #ifdef SQLITE_ENABLE_FTS1
  12311. "ENABLE_FTS1",
  12312. #endif
  12313. #ifdef SQLITE_ENABLE_FTS2
  12314. "ENABLE_FTS2",
  12315. #endif
  12316. #ifdef SQLITE_ENABLE_FTS3
  12317. "ENABLE_FTS3",
  12318. #endif
  12319. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12320. "ENABLE_FTS3_PARENTHESIS",
  12321. #endif
  12322. #ifdef SQLITE_ENABLE_FTS4
  12323. "ENABLE_FTS4",
  12324. #endif
  12325. #ifdef SQLITE_ENABLE_ICU
  12326. "ENABLE_ICU",
  12327. #endif
  12328. #ifdef SQLITE_ENABLE_IOTRACE
  12329. "ENABLE_IOTRACE",
  12330. #endif
  12331. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12332. "ENABLE_LOAD_EXTENSION",
  12333. #endif
  12334. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12335. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12336. #endif
  12337. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12338. "ENABLE_MEMORY_MANAGEMENT",
  12339. #endif
  12340. #ifdef SQLITE_ENABLE_MEMSYS3
  12341. "ENABLE_MEMSYS3",
  12342. #endif
  12343. #ifdef SQLITE_ENABLE_MEMSYS5
  12344. "ENABLE_MEMSYS5",
  12345. #endif
  12346. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12347. "ENABLE_OVERSIZE_CELL_CHECK",
  12348. #endif
  12349. #ifdef SQLITE_ENABLE_RTREE
  12350. "ENABLE_RTREE",
  12351. #endif
  12352. #ifdef SQLITE_ENABLE_STAT3
  12353. "ENABLE_STAT3",
  12354. #endif
  12355. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12356. "ENABLE_UNLOCK_NOTIFY",
  12357. #endif
  12358. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12359. "ENABLE_UPDATE_DELETE_LIMIT",
  12360. #endif
  12361. #ifdef SQLITE_HAS_CODEC
  12362. "HAS_CODEC",
  12363. #endif
  12364. #ifdef SQLITE_HAVE_ISNAN
  12365. "HAVE_ISNAN",
  12366. #endif
  12367. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12368. "HOMEGROWN_RECURSIVE_MUTEX",
  12369. #endif
  12370. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12371. "IGNORE_AFP_LOCK_ERRORS",
  12372. #endif
  12373. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12374. "IGNORE_FLOCK_LOCK_ERRORS",
  12375. #endif
  12376. #ifdef SQLITE_INT64_TYPE
  12377. "INT64_TYPE",
  12378. #endif
  12379. #ifdef SQLITE_LOCK_TRACE
  12380. "LOCK_TRACE",
  12381. #endif
  12382. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  12383. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  12384. #endif
  12385. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12386. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12387. #endif
  12388. #ifdef SQLITE_MEMDEBUG
  12389. "MEMDEBUG",
  12390. #endif
  12391. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12392. "MIXED_ENDIAN_64BIT_FLOAT",
  12393. #endif
  12394. #ifdef SQLITE_NO_SYNC
  12395. "NO_SYNC",
  12396. #endif
  12397. #ifdef SQLITE_OMIT_ALTERTABLE
  12398. "OMIT_ALTERTABLE",
  12399. #endif
  12400. #ifdef SQLITE_OMIT_ANALYZE
  12401. "OMIT_ANALYZE",
  12402. #endif
  12403. #ifdef SQLITE_OMIT_ATTACH
  12404. "OMIT_ATTACH",
  12405. #endif
  12406. #ifdef SQLITE_OMIT_AUTHORIZATION
  12407. "OMIT_AUTHORIZATION",
  12408. #endif
  12409. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12410. "OMIT_AUTOINCREMENT",
  12411. #endif
  12412. #ifdef SQLITE_OMIT_AUTOINIT
  12413. "OMIT_AUTOINIT",
  12414. #endif
  12415. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12416. "OMIT_AUTOMATIC_INDEX",
  12417. #endif
  12418. #ifdef SQLITE_OMIT_AUTORESET
  12419. "OMIT_AUTORESET",
  12420. #endif
  12421. #ifdef SQLITE_OMIT_AUTOVACUUM
  12422. "OMIT_AUTOVACUUM",
  12423. #endif
  12424. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12425. "OMIT_BETWEEN_OPTIMIZATION",
  12426. #endif
  12427. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12428. "OMIT_BLOB_LITERAL",
  12429. #endif
  12430. #ifdef SQLITE_OMIT_BTREECOUNT
  12431. "OMIT_BTREECOUNT",
  12432. #endif
  12433. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12434. "OMIT_BUILTIN_TEST",
  12435. #endif
  12436. #ifdef SQLITE_OMIT_CAST
  12437. "OMIT_CAST",
  12438. #endif
  12439. #ifdef SQLITE_OMIT_CHECK
  12440. "OMIT_CHECK",
  12441. #endif
  12442. #ifdef SQLITE_OMIT_COMPLETE
  12443. "OMIT_COMPLETE",
  12444. #endif
  12445. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12446. "OMIT_COMPOUND_SELECT",
  12447. #endif
  12448. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12449. "OMIT_DATETIME_FUNCS",
  12450. #endif
  12451. #ifdef SQLITE_OMIT_DECLTYPE
  12452. "OMIT_DECLTYPE",
  12453. #endif
  12454. #ifdef SQLITE_OMIT_DEPRECATED
  12455. "OMIT_DEPRECATED",
  12456. #endif
  12457. #ifdef SQLITE_OMIT_DISKIO
  12458. "OMIT_DISKIO",
  12459. #endif
  12460. #ifdef SQLITE_OMIT_EXPLAIN
  12461. "OMIT_EXPLAIN",
  12462. #endif
  12463. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12464. "OMIT_FLAG_PRAGMAS",
  12465. #endif
  12466. #ifdef SQLITE_OMIT_FLOATING_POINT
  12467. "OMIT_FLOATING_POINT",
  12468. #endif
  12469. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12470. "OMIT_FOREIGN_KEY",
  12471. #endif
  12472. #ifdef SQLITE_OMIT_GET_TABLE
  12473. "OMIT_GET_TABLE",
  12474. #endif
  12475. #ifdef SQLITE_OMIT_INCRBLOB
  12476. "OMIT_INCRBLOB",
  12477. #endif
  12478. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12479. "OMIT_INTEGRITY_CHECK",
  12480. #endif
  12481. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12482. "OMIT_LIKE_OPTIMIZATION",
  12483. #endif
  12484. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12485. "OMIT_LOAD_EXTENSION",
  12486. #endif
  12487. #ifdef SQLITE_OMIT_LOCALTIME
  12488. "OMIT_LOCALTIME",
  12489. #endif
  12490. #ifdef SQLITE_OMIT_LOOKASIDE
  12491. "OMIT_LOOKASIDE",
  12492. #endif
  12493. #ifdef SQLITE_OMIT_MEMORYDB
  12494. "OMIT_MEMORYDB",
  12495. #endif
  12496. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12497. "OMIT_OR_OPTIMIZATION",
  12498. #endif
  12499. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12500. "OMIT_PAGER_PRAGMAS",
  12501. #endif
  12502. #ifdef SQLITE_OMIT_PRAGMA
  12503. "OMIT_PRAGMA",
  12504. #endif
  12505. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12506. "OMIT_PROGRESS_CALLBACK",
  12507. #endif
  12508. #ifdef SQLITE_OMIT_QUICKBALANCE
  12509. "OMIT_QUICKBALANCE",
  12510. #endif
  12511. #ifdef SQLITE_OMIT_REINDEX
  12512. "OMIT_REINDEX",
  12513. #endif
  12514. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12515. "OMIT_SCHEMA_PRAGMAS",
  12516. #endif
  12517. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12518. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12519. #endif
  12520. #ifdef SQLITE_OMIT_SHARED_CACHE
  12521. "OMIT_SHARED_CACHE",
  12522. #endif
  12523. #ifdef SQLITE_OMIT_SUBQUERY
  12524. "OMIT_SUBQUERY",
  12525. #endif
  12526. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12527. "OMIT_TCL_VARIABLE",
  12528. #endif
  12529. #ifdef SQLITE_OMIT_TEMPDB
  12530. "OMIT_TEMPDB",
  12531. #endif
  12532. #ifdef SQLITE_OMIT_TRACE
  12533. "OMIT_TRACE",
  12534. #endif
  12535. #ifdef SQLITE_OMIT_TRIGGER
  12536. "OMIT_TRIGGER",
  12537. #endif
  12538. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12539. "OMIT_TRUNCATE_OPTIMIZATION",
  12540. #endif
  12541. #ifdef SQLITE_OMIT_UTF16
  12542. "OMIT_UTF16",
  12543. #endif
  12544. #ifdef SQLITE_OMIT_VACUUM
  12545. "OMIT_VACUUM",
  12546. #endif
  12547. #ifdef SQLITE_OMIT_VIEW
  12548. "OMIT_VIEW",
  12549. #endif
  12550. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12551. "OMIT_VIRTUALTABLE",
  12552. #endif
  12553. #ifdef SQLITE_OMIT_WAL
  12554. "OMIT_WAL",
  12555. #endif
  12556. #ifdef SQLITE_OMIT_WSD
  12557. "OMIT_WSD",
  12558. #endif
  12559. #ifdef SQLITE_OMIT_XFER_OPT
  12560. "OMIT_XFER_OPT",
  12561. #endif
  12562. #ifdef SQLITE_PERFORMANCE_TRACE
  12563. "PERFORMANCE_TRACE",
  12564. #endif
  12565. #ifdef SQLITE_PROXY_DEBUG
  12566. "PROXY_DEBUG",
  12567. #endif
  12568. #ifdef SQLITE_RTREE_INT_ONLY
  12569. "RTREE_INT_ONLY",
  12570. #endif
  12571. #ifdef SQLITE_SECURE_DELETE
  12572. "SECURE_DELETE",
  12573. #endif
  12574. #ifdef SQLITE_SMALL_STACK
  12575. "SMALL_STACK",
  12576. #endif
  12577. #ifdef SQLITE_SOUNDEX
  12578. "SOUNDEX",
  12579. #endif
  12580. #ifdef SQLITE_TCL
  12581. "TCL",
  12582. #endif
  12583. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  12584. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12585. #endif
  12586. #ifdef SQLITE_TEST
  12587. "TEST",
  12588. #endif
  12589. #if defined(SQLITE_THREADSAFE)
  12590. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12591. #endif
  12592. #ifdef SQLITE_USE_ALLOCA
  12593. "USE_ALLOCA",
  12594. #endif
  12595. #ifdef SQLITE_ZERO_MALLOC
  12596. "ZERO_MALLOC"
  12597. #endif
  12598. };
  12599. /*
  12600. ** Given the name of a compile-time option, return true if that option
  12601. ** was used and false if not.
  12602. **
  12603. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12604. ** is not required for a match.
  12605. */
  12606. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12607. int i, n;
  12608. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12609. n = sqlite3Strlen30(zOptName);
  12610. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12611. ** linear search is adequate. No need for a binary search. */
  12612. for(i=0; i<ArraySize(azCompileOpt); i++){
  12613. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  12614. && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
  12615. ){
  12616. return 1;
  12617. }
  12618. }
  12619. return 0;
  12620. }
  12621. /*
  12622. ** Return the N-th compile-time option string. If N is out of range,
  12623. ** return a NULL pointer.
  12624. */
  12625. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12626. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12627. return azCompileOpt[N];
  12628. }
  12629. return 0;
  12630. }
  12631. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12632. /************** End of ctime.c ***********************************************/
  12633. /************** Begin file status.c ******************************************/
  12634. /*
  12635. ** 2008 June 18
  12636. **
  12637. ** The author disclaims copyright to this source code. In place of
  12638. ** a legal notice, here is a blessing:
  12639. **
  12640. ** May you do good and not evil.
  12641. ** May you find forgiveness for yourself and forgive others.
  12642. ** May you share freely, never taking more than you give.
  12643. **
  12644. *************************************************************************
  12645. **
  12646. ** This module implements the sqlite3_status() interface and related
  12647. ** functionality.
  12648. */
  12649. /************** Include vdbeInt.h in the middle of status.c ******************/
  12650. /************** Begin file vdbeInt.h *****************************************/
  12651. /*
  12652. ** 2003 September 6
  12653. **
  12654. ** The author disclaims copyright to this source code. In place of
  12655. ** a legal notice, here is a blessing:
  12656. **
  12657. ** May you do good and not evil.
  12658. ** May you find forgiveness for yourself and forgive others.
  12659. ** May you share freely, never taking more than you give.
  12660. **
  12661. *************************************************************************
  12662. ** This is the header file for information that is private to the
  12663. ** VDBE. This information used to all be at the top of the single
  12664. ** source code file "vdbe.c". When that file became too big (over
  12665. ** 6000 lines long) it was split up into several smaller files and
  12666. ** this header information was factored out.
  12667. */
  12668. #ifndef _VDBEINT_H_
  12669. #define _VDBEINT_H_
  12670. /*
  12671. ** The maximum number of times that a statement will try to reparse
  12672. ** itself before giving up and returning SQLITE_SCHEMA.
  12673. */
  12674. #ifndef SQLITE_MAX_SCHEMA_RETRY
  12675. # define SQLITE_MAX_SCHEMA_RETRY 50
  12676. #endif
  12677. /*
  12678. ** SQL is translated into a sequence of instructions to be
  12679. ** executed by a virtual machine. Each instruction is an instance
  12680. ** of the following structure.
  12681. */
  12682. typedef struct VdbeOp Op;
  12683. /*
  12684. ** Boolean values
  12685. */
  12686. typedef unsigned char Bool;
  12687. /* Opaque type used by code in vdbesort.c */
  12688. typedef struct VdbeSorter VdbeSorter;
  12689. /* Opaque type used by the explainer */
  12690. typedef struct Explain Explain;
  12691. /*
  12692. ** A cursor is a pointer into a single BTree within a database file.
  12693. ** The cursor can seek to a BTree entry with a particular key, or
  12694. ** loop over all entries of the Btree. You can also insert new BTree
  12695. ** entries or retrieve the key or data from the entry that the cursor
  12696. ** is currently pointing to.
  12697. **
  12698. ** Every cursor that the virtual machine has open is represented by an
  12699. ** instance of the following structure.
  12700. */
  12701. struct VdbeCursor {
  12702. BtCursor *pCursor; /* The cursor structure of the backend */
  12703. Btree *pBt; /* Separate file holding temporary table */
  12704. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12705. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12706. int pseudoTableReg; /* Register holding pseudotable content. */
  12707. int nField; /* Number of fields in the header */
  12708. Bool zeroed; /* True if zeroed out and ready for reuse */
  12709. Bool rowidIsValid; /* True if lastRowid is valid */
  12710. Bool atFirst; /* True if pointing to first entry */
  12711. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12712. Bool nullRow; /* True if pointing to a row with no data */
  12713. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12714. Bool isTable; /* True if a table requiring integer keys */
  12715. Bool isIndex; /* True if an index containing keys only - no data */
  12716. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12717. Bool isSorter; /* True if a new-style sorter */
  12718. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12719. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12720. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12721. i64 seqCount; /* Sequence counter */
  12722. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12723. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12724. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12725. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12726. ** OP_IsUnique opcode on this cursor. */
  12727. int seekResult;
  12728. /* Cached information about the header for the data record that the
  12729. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12730. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12731. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12732. ** the cache is out of date.
  12733. **
  12734. ** aRow might point to (ephemeral) data for the current row, or it might
  12735. ** be NULL.
  12736. */
  12737. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12738. int payloadSize; /* Total number of bytes in the record */
  12739. u32 *aType; /* Type values for all entries in the record */
  12740. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12741. u8 *aRow; /* Data for the current row, if all on one page */
  12742. };
  12743. typedef struct VdbeCursor VdbeCursor;
  12744. /*
  12745. ** When a sub-program is executed (OP_Program), a structure of this type
  12746. ** is allocated to store the current value of the program counter, as
  12747. ** well as the current memory cell array and various other frame specific
  12748. ** values stored in the Vdbe struct. When the sub-program is finished,
  12749. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12750. ** restoring the state of the VM to as it was before the sub-program
  12751. ** began executing.
  12752. **
  12753. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12754. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12755. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12756. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12757. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12758. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12759. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12760. ** child frame are released.
  12761. **
  12762. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12763. ** set to NULL if the currently executing frame is the main program.
  12764. */
  12765. typedef struct VdbeFrame VdbeFrame;
  12766. struct VdbeFrame {
  12767. Vdbe *v; /* VM this frame belongs to */
  12768. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12769. Op *aOp; /* Program instructions for parent frame */
  12770. Mem *aMem; /* Array of memory cells for parent frame */
  12771. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12772. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12773. void *token; /* Copy of SubProgram.token */
  12774. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12775. int nCursor; /* Number of entries in apCsr */
  12776. int pc; /* Program Counter in parent (calling) frame */
  12777. int nOp; /* Size of aOp array */
  12778. int nMem; /* Number of entries in aMem */
  12779. int nOnceFlag; /* Number of entries in aOnceFlag */
  12780. int nChildMem; /* Number of memory cells for child frame */
  12781. int nChildCsr; /* Number of cursors for child frame */
  12782. int nChange; /* Statement changes (Vdbe.nChanges) */
  12783. };
  12784. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12785. /*
  12786. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12787. */
  12788. #define CACHE_STALE 0
  12789. /*
  12790. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12791. ** structures. Each Mem struct may cache multiple representations (string,
  12792. ** integer etc.) of the same value.
  12793. */
  12794. struct Mem {
  12795. sqlite3 *db; /* The associated database connection */
  12796. char *z; /* String or BLOB value */
  12797. double r; /* Real value */
  12798. union {
  12799. i64 i; /* Integer value used when MEM_Int is set in flags */
  12800. int nZero; /* Used when bit MEM_Zero is set in flags */
  12801. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12802. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12803. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12804. } u;
  12805. int n; /* Number of characters in string value, excluding '\0' */
  12806. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12807. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12808. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12809. #ifdef SQLITE_DEBUG
  12810. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12811. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12812. #endif
  12813. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12814. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12815. };
  12816. /* One or more of the following flags are set to indicate the validOK
  12817. ** representations of the value stored in the Mem struct.
  12818. **
  12819. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12820. ** No other flags may be set in this case.
  12821. **
  12822. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12823. ** Usually this is encoded in the same unicode encoding as the main
  12824. ** database (see below for exceptions). If the MEM_Term flag is also
  12825. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12826. ** flags may coexist with the MEM_Str flag.
  12827. */
  12828. #define MEM_Null 0x0001 /* Value is NULL */
  12829. #define MEM_Str 0x0002 /* Value is a string */
  12830. #define MEM_Int 0x0004 /* Value is an integer */
  12831. #define MEM_Real 0x0008 /* Value is a real number */
  12832. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12833. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12834. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12835. #define MEM_Invalid 0x0080 /* Value is undefined */
  12836. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12837. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12838. /* Whenever Mem contains a valid string or blob representation, one of
  12839. ** the following flags must be set to determine the memory management
  12840. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12841. ** string is \000 or \u0000 terminated
  12842. */
  12843. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12844. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12845. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12846. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12847. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12848. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12849. #ifdef SQLITE_OMIT_INCRBLOB
  12850. #undef MEM_Zero
  12851. #define MEM_Zero 0x0000
  12852. #endif
  12853. /*
  12854. ** Clear any existing type flags from a Mem and replace them with f
  12855. */
  12856. #define MemSetTypeFlag(p, f) \
  12857. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12858. /*
  12859. ** Return true if a memory cell is not marked as invalid. This macro
  12860. ** is for use inside assert() statements only.
  12861. */
  12862. #ifdef SQLITE_DEBUG
  12863. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12864. #endif
  12865. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  12866. ** additional information about auxiliary information bound to arguments
  12867. ** of the function. This is used to implement the sqlite3_get_auxdata()
  12868. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  12869. ** that can be associated with a constant argument to a function. This
  12870. ** allows functions such as "regexp" to compile their constant regular
  12871. ** expression argument once and reused the compiled code for multiple
  12872. ** invocations.
  12873. */
  12874. struct VdbeFunc {
  12875. FuncDef *pFunc; /* The definition of the function */
  12876. int nAux; /* Number of entries allocated for apAux[] */
  12877. struct AuxData {
  12878. void *pAux; /* Aux data for the i-th argument */
  12879. void (*xDelete)(void *); /* Destructor for the aux data */
  12880. } apAux[1]; /* One slot for each function argument */
  12881. };
  12882. /*
  12883. ** The "context" argument for a installable function. A pointer to an
  12884. ** instance of this structure is the first argument to the routines used
  12885. ** implement the SQL functions.
  12886. **
  12887. ** There is a typedef for this structure in sqlite.h. So all routines,
  12888. ** even the public interface to SQLite, can use a pointer to this structure.
  12889. ** But this file is the only place where the internal details of this
  12890. ** structure are known.
  12891. **
  12892. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12893. ** (Mem) which are only defined there.
  12894. */
  12895. struct sqlite3_context {
  12896. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12897. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  12898. Mem s; /* The return value is stored here */
  12899. Mem *pMem; /* Memory cell used to store aggregate context */
  12900. CollSeq *pColl; /* Collating sequence */
  12901. int isError; /* Error code returned by the function. */
  12902. int skipFlag; /* Skip skip accumulator loading if true */
  12903. };
  12904. /*
  12905. ** An Explain object accumulates indented output which is helpful
  12906. ** in describing recursive data structures.
  12907. */
  12908. struct Explain {
  12909. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12910. StrAccum str; /* The string being accumulated */
  12911. int nIndent; /* Number of elements in aIndent */
  12912. u16 aIndent[100]; /* Levels of indentation */
  12913. char zBase[100]; /* Initial space */
  12914. };
  12915. /* A bitfield type for use inside of structures. Always follow with :N where
  12916. ** N is the number of bits.
  12917. */
  12918. typedef unsigned bft; /* Bit Field Type */
  12919. /*
  12920. ** An instance of the virtual machine. This structure contains the complete
  12921. ** state of the virtual machine.
  12922. **
  12923. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12924. ** is really a pointer to an instance of this structure.
  12925. **
  12926. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12927. ** any virtual table method invocations made by the vdbe program. It is
  12928. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12929. ** variable is used for two purposes: to allow xDestroy methods to execute
  12930. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12931. ** malloc failure when SQLite is invoked recursively by a virtual table
  12932. ** method function.
  12933. */
  12934. struct Vdbe {
  12935. sqlite3 *db; /* The database connection that owns this statement */
  12936. Op *aOp; /* Space to hold the virtual machine's program */
  12937. Mem *aMem; /* The memory locations */
  12938. Mem **apArg; /* Arguments to currently executing user function */
  12939. Mem *aColName; /* Column names to return */
  12940. Mem *pResultSet; /* Pointer to an array of results */
  12941. int nMem; /* Number of memory locations currently allocated */
  12942. int nOp; /* Number of instructions in the program */
  12943. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12944. int nLabel; /* Number of labels used */
  12945. int *aLabel; /* Space to hold the labels */
  12946. u16 nResColumn; /* Number of columns in one row of the result set */
  12947. int nCursor; /* Number of slots in apCsr[] */
  12948. u32 magic; /* Magic number for sanity checking */
  12949. char *zErrMsg; /* Error message written here */
  12950. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12951. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12952. Mem *aVar; /* Values for the OP_Variable opcode. */
  12953. char **azVar; /* Name of variables */
  12954. ynVar nVar; /* Number of entries in aVar[] */
  12955. ynVar nzVar; /* Number of entries in azVar[] */
  12956. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12957. int pc; /* The program counter */
  12958. int rc; /* Value to return */
  12959. u8 errorAction; /* Recovery action to do in case of an error */
  12960. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12961. bft explain:2; /* True if EXPLAIN present on SQL command */
  12962. bft inVtabMethod:2; /* See comments above */
  12963. bft changeCntOn:1; /* True to update the change-counter */
  12964. bft expired:1; /* True if the VM needs to be recompiled */
  12965. bft runOnlyOnce:1; /* Automatically expire on reset */
  12966. bft usesStmtJournal:1; /* True if uses a statement journal */
  12967. bft readOnly:1; /* True for read-only statements */
  12968. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  12969. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  12970. int nChange; /* Number of db changes made since last reset */
  12971. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  12972. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  12973. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  12974. int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
  12975. #ifndef SQLITE_OMIT_TRACE
  12976. i64 startTime; /* Time when query started - used for profiling */
  12977. #endif
  12978. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  12979. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  12980. char *zSql; /* Text of the SQL statement that generated this */
  12981. void *pFree; /* Free this when deleting the vdbe */
  12982. #ifdef SQLITE_DEBUG
  12983. FILE *trace; /* Write an execution trace here, if not NULL */
  12984. #endif
  12985. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  12986. Explain *pExplain; /* The explainer */
  12987. char *zExplain; /* Explanation of data structures */
  12988. #endif
  12989. VdbeFrame *pFrame; /* Parent frame */
  12990. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  12991. int nFrame; /* Number of frames in pFrame list */
  12992. u32 expmask; /* Binding to these vars invalidates VM */
  12993. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  12994. int nOnceFlag; /* Size of array aOnceFlag[] */
  12995. u8 *aOnceFlag; /* Flags for OP_Once */
  12996. };
  12997. /*
  12998. ** The following are allowed values for Vdbe.magic
  12999. */
  13000. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13001. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13002. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13003. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13004. /*
  13005. ** Function prototypes
  13006. */
  13007. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13008. void sqliteVdbePopStack(Vdbe*,int);
  13009. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13010. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13011. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13012. #endif
  13013. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13014. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13015. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  13016. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13017. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  13018. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13019. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  13020. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  13021. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13022. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13023. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13024. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13025. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13026. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13027. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13028. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13029. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13030. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13031. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13032. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13033. #ifdef SQLITE_OMIT_FLOATING_POINT
  13034. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13035. #else
  13036. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13037. #endif
  13038. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13039. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13040. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13041. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13042. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  13043. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13044. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13045. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13046. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13047. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13048. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13049. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  13050. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13051. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  13052. #define VdbeMemRelease(X) \
  13053. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  13054. sqlite3VdbeMemReleaseExternal(X);
  13055. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13056. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13057. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13058. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13059. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13060. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13061. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  13062. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13063. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  13064. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13065. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13066. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13067. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  13068. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  13069. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  13070. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13071. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13072. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13073. #else
  13074. # define sqlite3VdbeEnter(X)
  13075. # define sqlite3VdbeLeave(X)
  13076. #endif
  13077. #ifdef SQLITE_DEBUG
  13078. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13079. #endif
  13080. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13081. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13082. #else
  13083. # define sqlite3VdbeCheckFk(p,i) 0
  13084. #endif
  13085. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13086. #ifdef SQLITE_DEBUG
  13087. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13088. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13089. #endif
  13090. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13091. #ifndef SQLITE_OMIT_INCRBLOB
  13092. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13093. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13094. #else
  13095. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13096. #define ExpandBlob(P) SQLITE_OK
  13097. #endif
  13098. #endif /* !defined(_VDBEINT_H_) */
  13099. /************** End of vdbeInt.h *********************************************/
  13100. /************** Continuing where we left off in status.c *********************/
  13101. /*
  13102. ** Variables in which to record status information.
  13103. */
  13104. typedef struct sqlite3StatType sqlite3StatType;
  13105. static SQLITE_WSD struct sqlite3StatType {
  13106. int nowValue[10]; /* Current value */
  13107. int mxValue[10]; /* Maximum value */
  13108. } sqlite3Stat = { {0,}, {0,} };
  13109. /* The "wsdStat" macro will resolve to the status information
  13110. ** state vector. If writable static data is unsupported on the target,
  13111. ** we have to locate the state vector at run-time. In the more common
  13112. ** case where writable static data is supported, wsdStat can refer directly
  13113. ** to the "sqlite3Stat" state vector declared above.
  13114. */
  13115. #ifdef SQLITE_OMIT_WSD
  13116. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13117. # define wsdStat x[0]
  13118. #else
  13119. # define wsdStatInit
  13120. # define wsdStat sqlite3Stat
  13121. #endif
  13122. /*
  13123. ** Return the current value of a status parameter.
  13124. */
  13125. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13126. wsdStatInit;
  13127. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13128. return wsdStat.nowValue[op];
  13129. }
  13130. /*
  13131. ** Add N to the value of a status record. It is assumed that the
  13132. ** caller holds appropriate locks.
  13133. */
  13134. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13135. wsdStatInit;
  13136. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13137. wsdStat.nowValue[op] += N;
  13138. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13139. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13140. }
  13141. }
  13142. /*
  13143. ** Set the value of a status to X.
  13144. */
  13145. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13146. wsdStatInit;
  13147. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13148. wsdStat.nowValue[op] = X;
  13149. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13150. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13151. }
  13152. }
  13153. /*
  13154. ** Query status information.
  13155. **
  13156. ** This implementation assumes that reading or writing an aligned
  13157. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13158. ** then this routine is not threadsafe.
  13159. */
  13160. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13161. wsdStatInit;
  13162. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13163. return SQLITE_MISUSE_BKPT;
  13164. }
  13165. *pCurrent = wsdStat.nowValue[op];
  13166. *pHighwater = wsdStat.mxValue[op];
  13167. if( resetFlag ){
  13168. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13169. }
  13170. return SQLITE_OK;
  13171. }
  13172. /*
  13173. ** Query status information for a single database connection
  13174. */
  13175. SQLITE_API int sqlite3_db_status(
  13176. sqlite3 *db, /* The database connection whose status is desired */
  13177. int op, /* Status verb */
  13178. int *pCurrent, /* Write current value here */
  13179. int *pHighwater, /* Write high-water mark here */
  13180. int resetFlag /* Reset high-water mark if true */
  13181. ){
  13182. int rc = SQLITE_OK; /* Return code */
  13183. sqlite3_mutex_enter(db->mutex);
  13184. switch( op ){
  13185. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13186. *pCurrent = db->lookaside.nOut;
  13187. *pHighwater = db->lookaside.mxOut;
  13188. if( resetFlag ){
  13189. db->lookaside.mxOut = db->lookaside.nOut;
  13190. }
  13191. break;
  13192. }
  13193. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13194. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13195. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13196. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13197. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13198. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13199. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13200. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13201. *pCurrent = 0;
  13202. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13203. if( resetFlag ){
  13204. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13205. }
  13206. break;
  13207. }
  13208. /*
  13209. ** Return an approximation for the amount of memory currently used
  13210. ** by all pagers associated with the given database connection. The
  13211. ** highwater mark is meaningless and is returned as zero.
  13212. */
  13213. case SQLITE_DBSTATUS_CACHE_USED: {
  13214. int totalUsed = 0;
  13215. int i;
  13216. sqlite3BtreeEnterAll(db);
  13217. for(i=0; i<db->nDb; i++){
  13218. Btree *pBt = db->aDb[i].pBt;
  13219. if( pBt ){
  13220. Pager *pPager = sqlite3BtreePager(pBt);
  13221. totalUsed += sqlite3PagerMemUsed(pPager);
  13222. }
  13223. }
  13224. sqlite3BtreeLeaveAll(db);
  13225. *pCurrent = totalUsed;
  13226. *pHighwater = 0;
  13227. break;
  13228. }
  13229. /*
  13230. ** *pCurrent gets an accurate estimate of the amount of memory used
  13231. ** to store the schema for all databases (main, temp, and any ATTACHed
  13232. ** databases. *pHighwater is set to zero.
  13233. */
  13234. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13235. int i; /* Used to iterate through schemas */
  13236. int nByte = 0; /* Used to accumulate return value */
  13237. sqlite3BtreeEnterAll(db);
  13238. db->pnBytesFreed = &nByte;
  13239. for(i=0; i<db->nDb; i++){
  13240. Schema *pSchema = db->aDb[i].pSchema;
  13241. if( ALWAYS(pSchema!=0) ){
  13242. HashElem *p;
  13243. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13244. pSchema->tblHash.count
  13245. + pSchema->trigHash.count
  13246. + pSchema->idxHash.count
  13247. + pSchema->fkeyHash.count
  13248. );
  13249. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13250. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13251. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13252. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13253. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13254. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13255. }
  13256. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13257. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13258. }
  13259. }
  13260. }
  13261. db->pnBytesFreed = 0;
  13262. sqlite3BtreeLeaveAll(db);
  13263. *pHighwater = 0;
  13264. *pCurrent = nByte;
  13265. break;
  13266. }
  13267. /*
  13268. ** *pCurrent gets an accurate estimate of the amount of memory used
  13269. ** to store all prepared statements.
  13270. ** *pHighwater is set to zero.
  13271. */
  13272. case SQLITE_DBSTATUS_STMT_USED: {
  13273. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13274. int nByte = 0; /* Used to accumulate return value */
  13275. db->pnBytesFreed = &nByte;
  13276. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13277. sqlite3VdbeClearObject(db, pVdbe);
  13278. sqlite3DbFree(db, pVdbe);
  13279. }
  13280. db->pnBytesFreed = 0;
  13281. *pHighwater = 0;
  13282. *pCurrent = nByte;
  13283. break;
  13284. }
  13285. /*
  13286. ** Set *pCurrent to the total cache hits or misses encountered by all
  13287. ** pagers the database handle is connected to. *pHighwater is always set
  13288. ** to zero.
  13289. */
  13290. case SQLITE_DBSTATUS_CACHE_HIT:
  13291. case SQLITE_DBSTATUS_CACHE_MISS:
  13292. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13293. int i;
  13294. int nRet = 0;
  13295. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13296. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13297. for(i=0; i<db->nDb; i++){
  13298. if( db->aDb[i].pBt ){
  13299. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13300. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13301. }
  13302. }
  13303. *pHighwater = 0;
  13304. *pCurrent = nRet;
  13305. break;
  13306. }
  13307. default: {
  13308. rc = SQLITE_ERROR;
  13309. }
  13310. }
  13311. sqlite3_mutex_leave(db->mutex);
  13312. return rc;
  13313. }
  13314. /************** End of status.c **********************************************/
  13315. /************** Begin file date.c ********************************************/
  13316. /*
  13317. ** 2003 October 31
  13318. **
  13319. ** The author disclaims copyright to this source code. In place of
  13320. ** a legal notice, here is a blessing:
  13321. **
  13322. ** May you do good and not evil.
  13323. ** May you find forgiveness for yourself and forgive others.
  13324. ** May you share freely, never taking more than you give.
  13325. **
  13326. *************************************************************************
  13327. ** This file contains the C functions that implement date and time
  13328. ** functions for SQLite.
  13329. **
  13330. ** There is only one exported symbol in this file - the function
  13331. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13332. ** All other code has file scope.
  13333. **
  13334. ** SQLite processes all times and dates as Julian Day numbers. The
  13335. ** dates and times are stored as the number of days since noon
  13336. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13337. ** calendar system.
  13338. **
  13339. ** 1970-01-01 00:00:00 is JD 2440587.5
  13340. ** 2000-01-01 00:00:00 is JD 2451544.5
  13341. **
  13342. ** This implemention requires years to be expressed as a 4-digit number
  13343. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13344. ** be represented, even though julian day numbers allow a much wider
  13345. ** range of dates.
  13346. **
  13347. ** The Gregorian calendar system is used for all dates and times,
  13348. ** even those that predate the Gregorian calendar. Historians usually
  13349. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13350. ** dates afterwards, depending on locale. Beware of this difference.
  13351. **
  13352. ** The conversion algorithms are implemented based on descriptions
  13353. ** in the following text:
  13354. **
  13355. ** Jean Meeus
  13356. ** Astronomical Algorithms, 2nd Edition, 1998
  13357. ** ISBM 0-943396-61-1
  13358. ** Willmann-Bell, Inc
  13359. ** Richmond, Virginia (USA)
  13360. */
  13361. /* #include <stdlib.h> */
  13362. /* #include <assert.h> */
  13363. #include <time.h>
  13364. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13365. /*
  13366. ** A structure for holding a single date and time.
  13367. */
  13368. typedef struct DateTime DateTime;
  13369. struct DateTime {
  13370. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13371. int Y, M, D; /* Year, month, and day */
  13372. int h, m; /* Hour and minutes */
  13373. int tz; /* Timezone offset in minutes */
  13374. double s; /* Seconds */
  13375. char validYMD; /* True (1) if Y,M,D are valid */
  13376. char validHMS; /* True (1) if h,m,s are valid */
  13377. char validJD; /* True (1) if iJD is valid */
  13378. char validTZ; /* True (1) if tz is valid */
  13379. };
  13380. /*
  13381. ** Convert zDate into one or more integers. Additional arguments
  13382. ** come in groups of 5 as follows:
  13383. **
  13384. ** N number of digits in the integer
  13385. ** min minimum allowed value of the integer
  13386. ** max maximum allowed value of the integer
  13387. ** nextC first character after the integer
  13388. ** pVal where to write the integers value.
  13389. **
  13390. ** Conversions continue until one with nextC==0 is encountered.
  13391. ** The function returns the number of successful conversions.
  13392. */
  13393. static int getDigits(const char *zDate, ...){
  13394. va_list ap;
  13395. int val;
  13396. int N;
  13397. int min;
  13398. int max;
  13399. int nextC;
  13400. int *pVal;
  13401. int cnt = 0;
  13402. va_start(ap, zDate);
  13403. do{
  13404. N = va_arg(ap, int);
  13405. min = va_arg(ap, int);
  13406. max = va_arg(ap, int);
  13407. nextC = va_arg(ap, int);
  13408. pVal = va_arg(ap, int*);
  13409. val = 0;
  13410. while( N-- ){
  13411. if( !sqlite3Isdigit(*zDate) ){
  13412. goto end_getDigits;
  13413. }
  13414. val = val*10 + *zDate - '0';
  13415. zDate++;
  13416. }
  13417. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13418. goto end_getDigits;
  13419. }
  13420. *pVal = val;
  13421. zDate++;
  13422. cnt++;
  13423. }while( nextC );
  13424. end_getDigits:
  13425. va_end(ap);
  13426. return cnt;
  13427. }
  13428. /*
  13429. ** Parse a timezone extension on the end of a date-time.
  13430. ** The extension is of the form:
  13431. **
  13432. ** (+/-)HH:MM
  13433. **
  13434. ** Or the "zulu" notation:
  13435. **
  13436. ** Z
  13437. **
  13438. ** If the parse is successful, write the number of minutes
  13439. ** of change in p->tz and return 0. If a parser error occurs,
  13440. ** return non-zero.
  13441. **
  13442. ** A missing specifier is not considered an error.
  13443. */
  13444. static int parseTimezone(const char *zDate, DateTime *p){
  13445. int sgn = 0;
  13446. int nHr, nMn;
  13447. int c;
  13448. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13449. p->tz = 0;
  13450. c = *zDate;
  13451. if( c=='-' ){
  13452. sgn = -1;
  13453. }else if( c=='+' ){
  13454. sgn = +1;
  13455. }else if( c=='Z' || c=='z' ){
  13456. zDate++;
  13457. goto zulu_time;
  13458. }else{
  13459. return c!=0;
  13460. }
  13461. zDate++;
  13462. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13463. return 1;
  13464. }
  13465. zDate += 5;
  13466. p->tz = sgn*(nMn + nHr*60);
  13467. zulu_time:
  13468. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13469. return *zDate!=0;
  13470. }
  13471. /*
  13472. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13473. ** The HH, MM, and SS must each be exactly 2 digits. The
  13474. ** fractional seconds FFFF can be one or more digits.
  13475. **
  13476. ** Return 1 if there is a parsing error and 0 on success.
  13477. */
  13478. static int parseHhMmSs(const char *zDate, DateTime *p){
  13479. int h, m, s;
  13480. double ms = 0.0;
  13481. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13482. return 1;
  13483. }
  13484. zDate += 5;
  13485. if( *zDate==':' ){
  13486. zDate++;
  13487. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13488. return 1;
  13489. }
  13490. zDate += 2;
  13491. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13492. double rScale = 1.0;
  13493. zDate++;
  13494. while( sqlite3Isdigit(*zDate) ){
  13495. ms = ms*10.0 + *zDate - '0';
  13496. rScale *= 10.0;
  13497. zDate++;
  13498. }
  13499. ms /= rScale;
  13500. }
  13501. }else{
  13502. s = 0;
  13503. }
  13504. p->validJD = 0;
  13505. p->validHMS = 1;
  13506. p->h = h;
  13507. p->m = m;
  13508. p->s = s + ms;
  13509. if( parseTimezone(zDate, p) ) return 1;
  13510. p->validTZ = (p->tz!=0)?1:0;
  13511. return 0;
  13512. }
  13513. /*
  13514. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13515. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13516. **
  13517. ** Reference: Meeus page 61
  13518. */
  13519. static void computeJD(DateTime *p){
  13520. int Y, M, D, A, B, X1, X2;
  13521. if( p->validJD ) return;
  13522. if( p->validYMD ){
  13523. Y = p->Y;
  13524. M = p->M;
  13525. D = p->D;
  13526. }else{
  13527. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13528. M = 1;
  13529. D = 1;
  13530. }
  13531. if( M<=2 ){
  13532. Y--;
  13533. M += 12;
  13534. }
  13535. A = Y/100;
  13536. B = 2 - A + (A/4);
  13537. X1 = 36525*(Y+4716)/100;
  13538. X2 = 306001*(M+1)/10000;
  13539. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13540. p->validJD = 1;
  13541. if( p->validHMS ){
  13542. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13543. if( p->validTZ ){
  13544. p->iJD -= p->tz*60000;
  13545. p->validYMD = 0;
  13546. p->validHMS = 0;
  13547. p->validTZ = 0;
  13548. }
  13549. }
  13550. }
  13551. /*
  13552. ** Parse dates of the form
  13553. **
  13554. ** YYYY-MM-DD HH:MM:SS.FFF
  13555. ** YYYY-MM-DD HH:MM:SS
  13556. ** YYYY-MM-DD HH:MM
  13557. ** YYYY-MM-DD
  13558. **
  13559. ** Write the result into the DateTime structure and return 0
  13560. ** on success and 1 if the input string is not a well-formed
  13561. ** date.
  13562. */
  13563. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13564. int Y, M, D, neg;
  13565. if( zDate[0]=='-' ){
  13566. zDate++;
  13567. neg = 1;
  13568. }else{
  13569. neg = 0;
  13570. }
  13571. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13572. return 1;
  13573. }
  13574. zDate += 10;
  13575. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13576. if( parseHhMmSs(zDate, p)==0 ){
  13577. /* We got the time */
  13578. }else if( *zDate==0 ){
  13579. p->validHMS = 0;
  13580. }else{
  13581. return 1;
  13582. }
  13583. p->validJD = 0;
  13584. p->validYMD = 1;
  13585. p->Y = neg ? -Y : Y;
  13586. p->M = M;
  13587. p->D = D;
  13588. if( p->validTZ ){
  13589. computeJD(p);
  13590. }
  13591. return 0;
  13592. }
  13593. /*
  13594. ** Set the time to the current time reported by the VFS.
  13595. **
  13596. ** Return the number of errors.
  13597. */
  13598. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13599. sqlite3 *db = sqlite3_context_db_handle(context);
  13600. if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
  13601. p->validJD = 1;
  13602. return 0;
  13603. }else{
  13604. return 1;
  13605. }
  13606. }
  13607. /*
  13608. ** Attempt to parse the given string into a Julian Day Number. Return
  13609. ** the number of errors.
  13610. **
  13611. ** The following are acceptable forms for the input string:
  13612. **
  13613. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13614. ** DDDD.DD
  13615. ** now
  13616. **
  13617. ** In the first form, the +/-HH:MM is always optional. The fractional
  13618. ** seconds extension (the ".FFF") is optional. The seconds portion
  13619. ** (":SS.FFF") is option. The year and date can be omitted as long
  13620. ** as there is a time string. The time string can be omitted as long
  13621. ** as there is a year and date.
  13622. */
  13623. static int parseDateOrTime(
  13624. sqlite3_context *context,
  13625. const char *zDate,
  13626. DateTime *p
  13627. ){
  13628. double r;
  13629. if( parseYyyyMmDd(zDate,p)==0 ){
  13630. return 0;
  13631. }else if( parseHhMmSs(zDate, p)==0 ){
  13632. return 0;
  13633. }else if( sqlite3StrICmp(zDate,"now")==0){
  13634. return setDateTimeToCurrent(context, p);
  13635. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13636. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13637. p->validJD = 1;
  13638. return 0;
  13639. }
  13640. return 1;
  13641. }
  13642. /*
  13643. ** Compute the Year, Month, and Day from the julian day number.
  13644. */
  13645. static void computeYMD(DateTime *p){
  13646. int Z, A, B, C, D, E, X1;
  13647. if( p->validYMD ) return;
  13648. if( !p->validJD ){
  13649. p->Y = 2000;
  13650. p->M = 1;
  13651. p->D = 1;
  13652. }else{
  13653. Z = (int)((p->iJD + 43200000)/86400000);
  13654. A = (int)((Z - 1867216.25)/36524.25);
  13655. A = Z + 1 + A - (A/4);
  13656. B = A + 1524;
  13657. C = (int)((B - 122.1)/365.25);
  13658. D = (36525*C)/100;
  13659. E = (int)((B-D)/30.6001);
  13660. X1 = (int)(30.6001*E);
  13661. p->D = B - D - X1;
  13662. p->M = E<14 ? E-1 : E-13;
  13663. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13664. }
  13665. p->validYMD = 1;
  13666. }
  13667. /*
  13668. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13669. */
  13670. static void computeHMS(DateTime *p){
  13671. int s;
  13672. if( p->validHMS ) return;
  13673. computeJD(p);
  13674. s = (int)((p->iJD + 43200000) % 86400000);
  13675. p->s = s/1000.0;
  13676. s = (int)p->s;
  13677. p->s -= s;
  13678. p->h = s/3600;
  13679. s -= p->h*3600;
  13680. p->m = s/60;
  13681. p->s += s - p->m*60;
  13682. p->validHMS = 1;
  13683. }
  13684. /*
  13685. ** Compute both YMD and HMS
  13686. */
  13687. static void computeYMD_HMS(DateTime *p){
  13688. computeYMD(p);
  13689. computeHMS(p);
  13690. }
  13691. /*
  13692. ** Clear the YMD and HMS and the TZ
  13693. */
  13694. static void clearYMD_HMS_TZ(DateTime *p){
  13695. p->validYMD = 0;
  13696. p->validHMS = 0;
  13697. p->validTZ = 0;
  13698. }
  13699. /*
  13700. ** On recent Windows platforms, the localtime_s() function is available
  13701. ** as part of the "Secure CRT". It is essentially equivalent to
  13702. ** localtime_r() available under most POSIX platforms, except that the
  13703. ** order of the parameters is reversed.
  13704. **
  13705. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13706. **
  13707. ** If the user has not indicated to use localtime_r() or localtime_s()
  13708. ** already, check for an MSVC build environment that provides
  13709. ** localtime_s().
  13710. */
  13711. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13712. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13713. #define HAVE_LOCALTIME_S 1
  13714. #endif
  13715. #ifndef SQLITE_OMIT_LOCALTIME
  13716. /*
  13717. ** The following routine implements the rough equivalent of localtime_r()
  13718. ** using whatever operating-system specific localtime facility that
  13719. ** is available. This routine returns 0 on success and
  13720. ** non-zero on any kind of error.
  13721. **
  13722. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13723. ** routine will always fail.
  13724. */
  13725. static int osLocaltime(time_t *t, struct tm *pTm){
  13726. int rc;
  13727. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13728. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13729. struct tm *pX;
  13730. #if SQLITE_THREADSAFE>0
  13731. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13732. #endif
  13733. sqlite3_mutex_enter(mutex);
  13734. pX = localtime(t);
  13735. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13736. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13737. #endif
  13738. if( pX ) *pTm = *pX;
  13739. sqlite3_mutex_leave(mutex);
  13740. rc = pX==0;
  13741. #else
  13742. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13743. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13744. #endif
  13745. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13746. rc = localtime_r(t, pTm)==0;
  13747. #else
  13748. rc = localtime_s(pTm, t);
  13749. #endif /* HAVE_LOCALTIME_R */
  13750. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13751. return rc;
  13752. }
  13753. #endif /* SQLITE_OMIT_LOCALTIME */
  13754. #ifndef SQLITE_OMIT_LOCALTIME
  13755. /*
  13756. ** Compute the difference (in milliseconds) between localtime and UTC
  13757. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13758. ** return this value and set *pRc to SQLITE_OK.
  13759. **
  13760. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13761. ** is undefined in this case.
  13762. */
  13763. static sqlite3_int64 localtimeOffset(
  13764. DateTime *p, /* Date at which to calculate offset */
  13765. sqlite3_context *pCtx, /* Write error here if one occurs */
  13766. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13767. ){
  13768. DateTime x, y;
  13769. time_t t;
  13770. struct tm sLocal;
  13771. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13772. memset(&sLocal, 0, sizeof(sLocal));
  13773. x = *p;
  13774. computeYMD_HMS(&x);
  13775. if( x.Y<1971 || x.Y>=2038 ){
  13776. x.Y = 2000;
  13777. x.M = 1;
  13778. x.D = 1;
  13779. x.h = 0;
  13780. x.m = 0;
  13781. x.s = 0.0;
  13782. } else {
  13783. int s = (int)(x.s + 0.5);
  13784. x.s = s;
  13785. }
  13786. x.tz = 0;
  13787. x.validJD = 0;
  13788. computeJD(&x);
  13789. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13790. if( osLocaltime(&t, &sLocal) ){
  13791. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13792. *pRc = SQLITE_ERROR;
  13793. return 0;
  13794. }
  13795. y.Y = sLocal.tm_year + 1900;
  13796. y.M = sLocal.tm_mon + 1;
  13797. y.D = sLocal.tm_mday;
  13798. y.h = sLocal.tm_hour;
  13799. y.m = sLocal.tm_min;
  13800. y.s = sLocal.tm_sec;
  13801. y.validYMD = 1;
  13802. y.validHMS = 1;
  13803. y.validJD = 0;
  13804. y.validTZ = 0;
  13805. computeJD(&y);
  13806. *pRc = SQLITE_OK;
  13807. return y.iJD - x.iJD;
  13808. }
  13809. #endif /* SQLITE_OMIT_LOCALTIME */
  13810. /*
  13811. ** Process a modifier to a date-time stamp. The modifiers are
  13812. ** as follows:
  13813. **
  13814. ** NNN days
  13815. ** NNN hours
  13816. ** NNN minutes
  13817. ** NNN.NNNN seconds
  13818. ** NNN months
  13819. ** NNN years
  13820. ** start of month
  13821. ** start of year
  13822. ** start of week
  13823. ** start of day
  13824. ** weekday N
  13825. ** unixepoch
  13826. ** localtime
  13827. ** utc
  13828. **
  13829. ** Return 0 on success and 1 if there is any kind of error. If the error
  13830. ** is in a system call (i.e. localtime()), then an error message is written
  13831. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13832. ** written to pCtx.
  13833. */
  13834. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13835. int rc = 1;
  13836. int n;
  13837. double r;
  13838. char *z, zBuf[30];
  13839. z = zBuf;
  13840. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13841. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13842. }
  13843. z[n] = 0;
  13844. switch( z[0] ){
  13845. #ifndef SQLITE_OMIT_LOCALTIME
  13846. case 'l': {
  13847. /* localtime
  13848. **
  13849. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13850. ** show local time.
  13851. */
  13852. if( strcmp(z, "localtime")==0 ){
  13853. computeJD(p);
  13854. p->iJD += localtimeOffset(p, pCtx, &rc);
  13855. clearYMD_HMS_TZ(p);
  13856. }
  13857. break;
  13858. }
  13859. #endif
  13860. case 'u': {
  13861. /*
  13862. ** unixepoch
  13863. **
  13864. ** Treat the current value of p->iJD as the number of
  13865. ** seconds since 1970. Convert to a real julian day number.
  13866. */
  13867. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13868. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13869. clearYMD_HMS_TZ(p);
  13870. rc = 0;
  13871. }
  13872. #ifndef SQLITE_OMIT_LOCALTIME
  13873. else if( strcmp(z, "utc")==0 ){
  13874. sqlite3_int64 c1;
  13875. computeJD(p);
  13876. c1 = localtimeOffset(p, pCtx, &rc);
  13877. if( rc==SQLITE_OK ){
  13878. p->iJD -= c1;
  13879. clearYMD_HMS_TZ(p);
  13880. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13881. }
  13882. }
  13883. #endif
  13884. break;
  13885. }
  13886. case 'w': {
  13887. /*
  13888. ** weekday N
  13889. **
  13890. ** Move the date to the same time on the next occurrence of
  13891. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13892. ** date is already on the appropriate weekday, this is a no-op.
  13893. */
  13894. if( strncmp(z, "weekday ", 8)==0
  13895. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13896. && (n=(int)r)==r && n>=0 && r<7 ){
  13897. sqlite3_int64 Z;
  13898. computeYMD_HMS(p);
  13899. p->validTZ = 0;
  13900. p->validJD = 0;
  13901. computeJD(p);
  13902. Z = ((p->iJD + 129600000)/86400000) % 7;
  13903. if( Z>n ) Z -= 7;
  13904. p->iJD += (n - Z)*86400000;
  13905. clearYMD_HMS_TZ(p);
  13906. rc = 0;
  13907. }
  13908. break;
  13909. }
  13910. case 's': {
  13911. /*
  13912. ** start of TTTTT
  13913. **
  13914. ** Move the date backwards to the beginning of the current day,
  13915. ** or month or year.
  13916. */
  13917. if( strncmp(z, "start of ", 9)!=0 ) break;
  13918. z += 9;
  13919. computeYMD(p);
  13920. p->validHMS = 1;
  13921. p->h = p->m = 0;
  13922. p->s = 0.0;
  13923. p->validTZ = 0;
  13924. p->validJD = 0;
  13925. if( strcmp(z,"month")==0 ){
  13926. p->D = 1;
  13927. rc = 0;
  13928. }else if( strcmp(z,"year")==0 ){
  13929. computeYMD(p);
  13930. p->M = 1;
  13931. p->D = 1;
  13932. rc = 0;
  13933. }else if( strcmp(z,"day")==0 ){
  13934. rc = 0;
  13935. }
  13936. break;
  13937. }
  13938. case '+':
  13939. case '-':
  13940. case '0':
  13941. case '1':
  13942. case '2':
  13943. case '3':
  13944. case '4':
  13945. case '5':
  13946. case '6':
  13947. case '7':
  13948. case '8':
  13949. case '9': {
  13950. double rRounder;
  13951. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  13952. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  13953. rc = 1;
  13954. break;
  13955. }
  13956. if( z[n]==':' ){
  13957. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  13958. ** specified number of hours, minutes, seconds, and fractional seconds
  13959. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  13960. ** omitted.
  13961. */
  13962. const char *z2 = z;
  13963. DateTime tx;
  13964. sqlite3_int64 day;
  13965. if( !sqlite3Isdigit(*z2) ) z2++;
  13966. memset(&tx, 0, sizeof(tx));
  13967. if( parseHhMmSs(z2, &tx) ) break;
  13968. computeJD(&tx);
  13969. tx.iJD -= 43200000;
  13970. day = tx.iJD/86400000;
  13971. tx.iJD -= day*86400000;
  13972. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  13973. computeJD(p);
  13974. clearYMD_HMS_TZ(p);
  13975. p->iJD += tx.iJD;
  13976. rc = 0;
  13977. break;
  13978. }
  13979. z += n;
  13980. while( sqlite3Isspace(*z) ) z++;
  13981. n = sqlite3Strlen30(z);
  13982. if( n>10 || n<3 ) break;
  13983. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  13984. computeJD(p);
  13985. rc = 0;
  13986. rRounder = r<0 ? -0.5 : +0.5;
  13987. if( n==3 && strcmp(z,"day")==0 ){
  13988. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  13989. }else if( n==4 && strcmp(z,"hour")==0 ){
  13990. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  13991. }else if( n==6 && strcmp(z,"minute")==0 ){
  13992. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  13993. }else if( n==6 && strcmp(z,"second")==0 ){
  13994. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  13995. }else if( n==5 && strcmp(z,"month")==0 ){
  13996. int x, y;
  13997. computeYMD_HMS(p);
  13998. p->M += (int)r;
  13999. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14000. p->Y += x;
  14001. p->M -= x*12;
  14002. p->validJD = 0;
  14003. computeJD(p);
  14004. y = (int)r;
  14005. if( y!=r ){
  14006. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14007. }
  14008. }else if( n==4 && strcmp(z,"year")==0 ){
  14009. int y = (int)r;
  14010. computeYMD_HMS(p);
  14011. p->Y += y;
  14012. p->validJD = 0;
  14013. computeJD(p);
  14014. if( y!=r ){
  14015. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14016. }
  14017. }else{
  14018. rc = 1;
  14019. }
  14020. clearYMD_HMS_TZ(p);
  14021. break;
  14022. }
  14023. default: {
  14024. break;
  14025. }
  14026. }
  14027. return rc;
  14028. }
  14029. /*
  14030. ** Process time function arguments. argv[0] is a date-time stamp.
  14031. ** argv[1] and following are modifiers. Parse them all and write
  14032. ** the resulting time into the DateTime structure p. Return 0
  14033. ** on success and 1 if there are any errors.
  14034. **
  14035. ** If there are zero parameters (if even argv[0] is undefined)
  14036. ** then assume a default value of "now" for argv[0].
  14037. */
  14038. static int isDate(
  14039. sqlite3_context *context,
  14040. int argc,
  14041. sqlite3_value **argv,
  14042. DateTime *p
  14043. ){
  14044. int i;
  14045. const unsigned char *z;
  14046. int eType;
  14047. memset(p, 0, sizeof(*p));
  14048. if( argc==0 ){
  14049. return setDateTimeToCurrent(context, p);
  14050. }
  14051. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14052. || eType==SQLITE_INTEGER ){
  14053. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14054. p->validJD = 1;
  14055. }else{
  14056. z = sqlite3_value_text(argv[0]);
  14057. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14058. return 1;
  14059. }
  14060. }
  14061. for(i=1; i<argc; i++){
  14062. z = sqlite3_value_text(argv[i]);
  14063. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14064. }
  14065. return 0;
  14066. }
  14067. /*
  14068. ** The following routines implement the various date and time functions
  14069. ** of SQLite.
  14070. */
  14071. /*
  14072. ** julianday( TIMESTRING, MOD, MOD, ...)
  14073. **
  14074. ** Return the julian day number of the date specified in the arguments
  14075. */
  14076. static void juliandayFunc(
  14077. sqlite3_context *context,
  14078. int argc,
  14079. sqlite3_value **argv
  14080. ){
  14081. DateTime x;
  14082. if( isDate(context, argc, argv, &x)==0 ){
  14083. computeJD(&x);
  14084. sqlite3_result_double(context, x.iJD/86400000.0);
  14085. }
  14086. }
  14087. /*
  14088. ** datetime( TIMESTRING, MOD, MOD, ...)
  14089. **
  14090. ** Return YYYY-MM-DD HH:MM:SS
  14091. */
  14092. static void datetimeFunc(
  14093. sqlite3_context *context,
  14094. int argc,
  14095. sqlite3_value **argv
  14096. ){
  14097. DateTime x;
  14098. if( isDate(context, argc, argv, &x)==0 ){
  14099. char zBuf[100];
  14100. computeYMD_HMS(&x);
  14101. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14102. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14103. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14104. }
  14105. }
  14106. /*
  14107. ** time( TIMESTRING, MOD, MOD, ...)
  14108. **
  14109. ** Return HH:MM:SS
  14110. */
  14111. static void timeFunc(
  14112. sqlite3_context *context,
  14113. int argc,
  14114. sqlite3_value **argv
  14115. ){
  14116. DateTime x;
  14117. if( isDate(context, argc, argv, &x)==0 ){
  14118. char zBuf[100];
  14119. computeHMS(&x);
  14120. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14121. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14122. }
  14123. }
  14124. /*
  14125. ** date( TIMESTRING, MOD, MOD, ...)
  14126. **
  14127. ** Return YYYY-MM-DD
  14128. */
  14129. static void dateFunc(
  14130. sqlite3_context *context,
  14131. int argc,
  14132. sqlite3_value **argv
  14133. ){
  14134. DateTime x;
  14135. if( isDate(context, argc, argv, &x)==0 ){
  14136. char zBuf[100];
  14137. computeYMD(&x);
  14138. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14139. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14140. }
  14141. }
  14142. /*
  14143. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14144. **
  14145. ** Return a string described by FORMAT. Conversions as follows:
  14146. **
  14147. ** %d day of month
  14148. ** %f ** fractional seconds SS.SSS
  14149. ** %H hour 00-24
  14150. ** %j day of year 000-366
  14151. ** %J ** Julian day number
  14152. ** %m month 01-12
  14153. ** %M minute 00-59
  14154. ** %s seconds since 1970-01-01
  14155. ** %S seconds 00-59
  14156. ** %w day of week 0-6 sunday==0
  14157. ** %W week of year 00-53
  14158. ** %Y year 0000-9999
  14159. ** %% %
  14160. */
  14161. static void strftimeFunc(
  14162. sqlite3_context *context,
  14163. int argc,
  14164. sqlite3_value **argv
  14165. ){
  14166. DateTime x;
  14167. u64 n;
  14168. size_t i,j;
  14169. char *z;
  14170. sqlite3 *db;
  14171. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14172. char zBuf[100];
  14173. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14174. db = sqlite3_context_db_handle(context);
  14175. for(i=0, n=1; zFmt[i]; i++, n++){
  14176. if( zFmt[i]=='%' ){
  14177. switch( zFmt[i+1] ){
  14178. case 'd':
  14179. case 'H':
  14180. case 'm':
  14181. case 'M':
  14182. case 'S':
  14183. case 'W':
  14184. n++;
  14185. /* fall thru */
  14186. case 'w':
  14187. case '%':
  14188. break;
  14189. case 'f':
  14190. n += 8;
  14191. break;
  14192. case 'j':
  14193. n += 3;
  14194. break;
  14195. case 'Y':
  14196. n += 8;
  14197. break;
  14198. case 's':
  14199. case 'J':
  14200. n += 50;
  14201. break;
  14202. default:
  14203. return; /* ERROR. return a NULL */
  14204. }
  14205. i++;
  14206. }
  14207. }
  14208. testcase( n==sizeof(zBuf)-1 );
  14209. testcase( n==sizeof(zBuf) );
  14210. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14211. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14212. if( n<sizeof(zBuf) ){
  14213. z = zBuf;
  14214. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14215. sqlite3_result_error_toobig(context);
  14216. return;
  14217. }else{
  14218. z = sqlite3DbMallocRaw(db, (int)n);
  14219. if( z==0 ){
  14220. sqlite3_result_error_nomem(context);
  14221. return;
  14222. }
  14223. }
  14224. computeJD(&x);
  14225. computeYMD_HMS(&x);
  14226. for(i=j=0; zFmt[i]; i++){
  14227. if( zFmt[i]!='%' ){
  14228. z[j++] = zFmt[i];
  14229. }else{
  14230. i++;
  14231. switch( zFmt[i] ){
  14232. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14233. case 'f': {
  14234. double s = x.s;
  14235. if( s>59.999 ) s = 59.999;
  14236. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14237. j += sqlite3Strlen30(&z[j]);
  14238. break;
  14239. }
  14240. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14241. case 'W': /* Fall thru */
  14242. case 'j': {
  14243. int nDay; /* Number of days since 1st day of year */
  14244. DateTime y = x;
  14245. y.validJD = 0;
  14246. y.M = 1;
  14247. y.D = 1;
  14248. computeJD(&y);
  14249. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14250. if( zFmt[i]=='W' ){
  14251. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14252. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14253. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14254. j += 2;
  14255. }else{
  14256. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14257. j += 3;
  14258. }
  14259. break;
  14260. }
  14261. case 'J': {
  14262. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14263. j+=sqlite3Strlen30(&z[j]);
  14264. break;
  14265. }
  14266. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14267. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14268. case 's': {
  14269. sqlite3_snprintf(30,&z[j],"%lld",
  14270. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14271. j += sqlite3Strlen30(&z[j]);
  14272. break;
  14273. }
  14274. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14275. case 'w': {
  14276. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14277. break;
  14278. }
  14279. case 'Y': {
  14280. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14281. break;
  14282. }
  14283. default: z[j++] = '%'; break;
  14284. }
  14285. }
  14286. }
  14287. z[j] = 0;
  14288. sqlite3_result_text(context, z, -1,
  14289. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14290. }
  14291. /*
  14292. ** current_time()
  14293. **
  14294. ** This function returns the same value as time('now').
  14295. */
  14296. static void ctimeFunc(
  14297. sqlite3_context *context,
  14298. int NotUsed,
  14299. sqlite3_value **NotUsed2
  14300. ){
  14301. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14302. timeFunc(context, 0, 0);
  14303. }
  14304. /*
  14305. ** current_date()
  14306. **
  14307. ** This function returns the same value as date('now').
  14308. */
  14309. static void cdateFunc(
  14310. sqlite3_context *context,
  14311. int NotUsed,
  14312. sqlite3_value **NotUsed2
  14313. ){
  14314. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14315. dateFunc(context, 0, 0);
  14316. }
  14317. /*
  14318. ** current_timestamp()
  14319. **
  14320. ** This function returns the same value as datetime('now').
  14321. */
  14322. static void ctimestampFunc(
  14323. sqlite3_context *context,
  14324. int NotUsed,
  14325. sqlite3_value **NotUsed2
  14326. ){
  14327. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14328. datetimeFunc(context, 0, 0);
  14329. }
  14330. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14331. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14332. /*
  14333. ** If the library is compiled to omit the full-scale date and time
  14334. ** handling (to get a smaller binary), the following minimal version
  14335. ** of the functions current_time(), current_date() and current_timestamp()
  14336. ** are included instead. This is to support column declarations that
  14337. ** include "DEFAULT CURRENT_TIME" etc.
  14338. **
  14339. ** This function uses the C-library functions time(), gmtime()
  14340. ** and strftime(). The format string to pass to strftime() is supplied
  14341. ** as the user-data for the function.
  14342. */
  14343. static void currentTimeFunc(
  14344. sqlite3_context *context,
  14345. int argc,
  14346. sqlite3_value **argv
  14347. ){
  14348. time_t t;
  14349. char *zFormat = (char *)sqlite3_user_data(context);
  14350. sqlite3 *db;
  14351. sqlite3_int64 iT;
  14352. struct tm *pTm;
  14353. struct tm sNow;
  14354. char zBuf[20];
  14355. UNUSED_PARAMETER(argc);
  14356. UNUSED_PARAMETER(argv);
  14357. db = sqlite3_context_db_handle(context);
  14358. if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
  14359. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14360. #ifdef HAVE_GMTIME_R
  14361. pTm = gmtime_r(&t, &sNow);
  14362. #else
  14363. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14364. pTm = gmtime(&t);
  14365. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14366. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14367. #endif
  14368. if( pTm ){
  14369. strftime(zBuf, 20, zFormat, &sNow);
  14370. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14371. }
  14372. }
  14373. #endif
  14374. /*
  14375. ** This function registered all of the above C functions as SQL
  14376. ** functions. This should be the only routine in this file with
  14377. ** external linkage.
  14378. */
  14379. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14380. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14381. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14382. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14383. FUNCTION(date, -1, 0, 0, dateFunc ),
  14384. FUNCTION(time, -1, 0, 0, timeFunc ),
  14385. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14386. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14387. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14388. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14389. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14390. #else
  14391. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14392. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14393. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14394. #endif
  14395. };
  14396. int i;
  14397. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14398. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14399. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14400. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14401. }
  14402. }
  14403. /************** End of date.c ************************************************/
  14404. /************** Begin file os.c **********************************************/
  14405. /*
  14406. ** 2005 November 29
  14407. **
  14408. ** The author disclaims copyright to this source code. In place of
  14409. ** a legal notice, here is a blessing:
  14410. **
  14411. ** May you do good and not evil.
  14412. ** May you find forgiveness for yourself and forgive others.
  14413. ** May you share freely, never taking more than you give.
  14414. **
  14415. ******************************************************************************
  14416. **
  14417. ** This file contains OS interface code that is common to all
  14418. ** architectures.
  14419. */
  14420. #define _SQLITE_OS_C_ 1
  14421. #undef _SQLITE_OS_C_
  14422. /*
  14423. ** The default SQLite sqlite3_vfs implementations do not allocate
  14424. ** memory (actually, os_unix.c allocates a small amount of memory
  14425. ** from within OsOpen()), but some third-party implementations may.
  14426. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14427. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14428. **
  14429. ** The following functions are instrumented for malloc() failure
  14430. ** testing:
  14431. **
  14432. ** sqlite3OsRead()
  14433. ** sqlite3OsWrite()
  14434. ** sqlite3OsSync()
  14435. ** sqlite3OsFileSize()
  14436. ** sqlite3OsLock()
  14437. ** sqlite3OsCheckReservedLock()
  14438. ** sqlite3OsFileControl()
  14439. ** sqlite3OsShmMap()
  14440. ** sqlite3OsOpen()
  14441. ** sqlite3OsDelete()
  14442. ** sqlite3OsAccess()
  14443. ** sqlite3OsFullPathname()
  14444. **
  14445. */
  14446. #if defined(SQLITE_TEST)
  14447. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14448. #define DO_OS_MALLOC_TEST(x) \
  14449. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14450. void *pTstAlloc = sqlite3Malloc(10); \
  14451. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14452. sqlite3_free(pTstAlloc); \
  14453. }
  14454. #else
  14455. #define DO_OS_MALLOC_TEST(x)
  14456. #endif
  14457. /*
  14458. ** The following routines are convenience wrappers around methods
  14459. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14460. ** of this would be completely automatic if SQLite were coded using
  14461. ** C++ instead of plain old C.
  14462. */
  14463. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14464. int rc = SQLITE_OK;
  14465. if( pId->pMethods ){
  14466. rc = pId->pMethods->xClose(pId);
  14467. pId->pMethods = 0;
  14468. }
  14469. return rc;
  14470. }
  14471. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14472. DO_OS_MALLOC_TEST(id);
  14473. return id->pMethods->xRead(id, pBuf, amt, offset);
  14474. }
  14475. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14476. DO_OS_MALLOC_TEST(id);
  14477. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14478. }
  14479. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14480. return id->pMethods->xTruncate(id, size);
  14481. }
  14482. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14483. DO_OS_MALLOC_TEST(id);
  14484. return id->pMethods->xSync(id, flags);
  14485. }
  14486. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14487. DO_OS_MALLOC_TEST(id);
  14488. return id->pMethods->xFileSize(id, pSize);
  14489. }
  14490. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14491. DO_OS_MALLOC_TEST(id);
  14492. return id->pMethods->xLock(id, lockType);
  14493. }
  14494. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14495. return id->pMethods->xUnlock(id, lockType);
  14496. }
  14497. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14498. DO_OS_MALLOC_TEST(id);
  14499. return id->pMethods->xCheckReservedLock(id, pResOut);
  14500. }
  14501. /*
  14502. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14503. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14504. ** when simply tossing information over the wall to the VFS and we do not
  14505. ** really care if the VFS receives and understands the information since it
  14506. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14507. ** routine has no return value since the return value would be meaningless.
  14508. */
  14509. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14510. DO_OS_MALLOC_TEST(id);
  14511. return id->pMethods->xFileControl(id, op, pArg);
  14512. }
  14513. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14514. (void)id->pMethods->xFileControl(id, op, pArg);
  14515. }
  14516. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14517. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14518. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14519. }
  14520. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14521. return id->pMethods->xDeviceCharacteristics(id);
  14522. }
  14523. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14524. return id->pMethods->xShmLock(id, offset, n, flags);
  14525. }
  14526. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14527. id->pMethods->xShmBarrier(id);
  14528. }
  14529. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14530. return id->pMethods->xShmUnmap(id, deleteFlag);
  14531. }
  14532. SQLITE_PRIVATE int sqlite3OsShmMap(
  14533. sqlite3_file *id, /* Database file handle */
  14534. int iPage,
  14535. int pgsz,
  14536. int bExtend, /* True to extend file if necessary */
  14537. void volatile **pp /* OUT: Pointer to mapping */
  14538. ){
  14539. DO_OS_MALLOC_TEST(id);
  14540. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14541. }
  14542. #if SQLITE_MAX_MMAP_SIZE>0
  14543. /* The real implementation of xFetch and xUnfetch */
  14544. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14545. DO_OS_MALLOC_TEST(id);
  14546. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  14547. }
  14548. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14549. return id->pMethods->xUnfetch(id, iOff, p);
  14550. }
  14551. #else
  14552. /* No-op stubs to use when memory-mapped I/O is disabled */
  14553. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14554. *pp = 0;
  14555. return SQLITE_OK;
  14556. }
  14557. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14558. return SQLITE_OK;
  14559. }
  14560. #endif
  14561. /*
  14562. ** The next group of routines are convenience wrappers around the
  14563. ** VFS methods.
  14564. */
  14565. SQLITE_PRIVATE int sqlite3OsOpen(
  14566. sqlite3_vfs *pVfs,
  14567. const char *zPath,
  14568. sqlite3_file *pFile,
  14569. int flags,
  14570. int *pFlagsOut
  14571. ){
  14572. int rc;
  14573. DO_OS_MALLOC_TEST(0);
  14574. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14575. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14576. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14577. ** reaching the VFS. */
  14578. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14579. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14580. return rc;
  14581. }
  14582. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14583. DO_OS_MALLOC_TEST(0);
  14584. assert( dirSync==0 || dirSync==1 );
  14585. return pVfs->xDelete(pVfs, zPath, dirSync);
  14586. }
  14587. SQLITE_PRIVATE int sqlite3OsAccess(
  14588. sqlite3_vfs *pVfs,
  14589. const char *zPath,
  14590. int flags,
  14591. int *pResOut
  14592. ){
  14593. DO_OS_MALLOC_TEST(0);
  14594. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14595. }
  14596. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14597. sqlite3_vfs *pVfs,
  14598. const char *zPath,
  14599. int nPathOut,
  14600. char *zPathOut
  14601. ){
  14602. DO_OS_MALLOC_TEST(0);
  14603. zPathOut[0] = 0;
  14604. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14605. }
  14606. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14607. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14608. return pVfs->xDlOpen(pVfs, zPath);
  14609. }
  14610. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14611. pVfs->xDlError(pVfs, nByte, zBufOut);
  14612. }
  14613. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14614. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14615. }
  14616. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14617. pVfs->xDlClose(pVfs, pHandle);
  14618. }
  14619. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14620. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14621. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14622. }
  14623. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14624. return pVfs->xSleep(pVfs, nMicro);
  14625. }
  14626. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14627. int rc;
  14628. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14629. ** method to get the current date and time if that method is available
  14630. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14631. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14632. ** unavailable.
  14633. */
  14634. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14635. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14636. }else{
  14637. double r;
  14638. rc = pVfs->xCurrentTime(pVfs, &r);
  14639. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14640. }
  14641. return rc;
  14642. }
  14643. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14644. sqlite3_vfs *pVfs,
  14645. const char *zFile,
  14646. sqlite3_file **ppFile,
  14647. int flags,
  14648. int *pOutFlags
  14649. ){
  14650. int rc = SQLITE_NOMEM;
  14651. sqlite3_file *pFile;
  14652. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14653. if( pFile ){
  14654. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14655. if( rc!=SQLITE_OK ){
  14656. sqlite3_free(pFile);
  14657. }else{
  14658. *ppFile = pFile;
  14659. }
  14660. }
  14661. return rc;
  14662. }
  14663. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14664. int rc = SQLITE_OK;
  14665. assert( pFile );
  14666. rc = sqlite3OsClose(pFile);
  14667. sqlite3_free(pFile);
  14668. return rc;
  14669. }
  14670. /*
  14671. ** This function is a wrapper around the OS specific implementation of
  14672. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14673. ** ability to simulate a malloc failure, so that the handling of an
  14674. ** error in sqlite3_os_init() by the upper layers can be tested.
  14675. */
  14676. SQLITE_PRIVATE int sqlite3OsInit(void){
  14677. void *p = sqlite3_malloc(10);
  14678. if( p==0 ) return SQLITE_NOMEM;
  14679. sqlite3_free(p);
  14680. return sqlite3_os_init();
  14681. }
  14682. /*
  14683. ** The list of all registered VFS implementations.
  14684. */
  14685. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14686. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14687. /*
  14688. ** Locate a VFS by name. If no name is given, simply return the
  14689. ** first VFS on the list.
  14690. */
  14691. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14692. sqlite3_vfs *pVfs = 0;
  14693. #if SQLITE_THREADSAFE
  14694. sqlite3_mutex *mutex;
  14695. #endif
  14696. #ifndef SQLITE_OMIT_AUTOINIT
  14697. int rc = sqlite3_initialize();
  14698. if( rc ) return 0;
  14699. #endif
  14700. #if SQLITE_THREADSAFE
  14701. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14702. #endif
  14703. sqlite3_mutex_enter(mutex);
  14704. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14705. if( zVfs==0 ) break;
  14706. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14707. }
  14708. sqlite3_mutex_leave(mutex);
  14709. return pVfs;
  14710. }
  14711. /*
  14712. ** Unlink a VFS from the linked list
  14713. */
  14714. static void vfsUnlink(sqlite3_vfs *pVfs){
  14715. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14716. if( pVfs==0 ){
  14717. /* No-op */
  14718. }else if( vfsList==pVfs ){
  14719. vfsList = pVfs->pNext;
  14720. }else if( vfsList ){
  14721. sqlite3_vfs *p = vfsList;
  14722. while( p->pNext && p->pNext!=pVfs ){
  14723. p = p->pNext;
  14724. }
  14725. if( p->pNext==pVfs ){
  14726. p->pNext = pVfs->pNext;
  14727. }
  14728. }
  14729. }
  14730. /*
  14731. ** Register a VFS with the system. It is harmless to register the same
  14732. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14733. ** true.
  14734. */
  14735. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14736. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14737. #ifndef SQLITE_OMIT_AUTOINIT
  14738. int rc = sqlite3_initialize();
  14739. if( rc ) return rc;
  14740. #endif
  14741. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14742. sqlite3_mutex_enter(mutex);
  14743. vfsUnlink(pVfs);
  14744. if( makeDflt || vfsList==0 ){
  14745. pVfs->pNext = vfsList;
  14746. vfsList = pVfs;
  14747. }else{
  14748. pVfs->pNext = vfsList->pNext;
  14749. vfsList->pNext = pVfs;
  14750. }
  14751. assert(vfsList);
  14752. sqlite3_mutex_leave(mutex);
  14753. return SQLITE_OK;
  14754. }
  14755. /*
  14756. ** Unregister a VFS so that it is no longer accessible.
  14757. */
  14758. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14759. #if SQLITE_THREADSAFE
  14760. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14761. #endif
  14762. sqlite3_mutex_enter(mutex);
  14763. vfsUnlink(pVfs);
  14764. sqlite3_mutex_leave(mutex);
  14765. return SQLITE_OK;
  14766. }
  14767. /************** End of os.c **************************************************/
  14768. /************** Begin file fault.c *******************************************/
  14769. /*
  14770. ** 2008 Jan 22
  14771. **
  14772. ** The author disclaims copyright to this source code. In place of
  14773. ** a legal notice, here is a blessing:
  14774. **
  14775. ** May you do good and not evil.
  14776. ** May you find forgiveness for yourself and forgive others.
  14777. ** May you share freely, never taking more than you give.
  14778. **
  14779. *************************************************************************
  14780. **
  14781. ** This file contains code to support the concept of "benign"
  14782. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14783. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14784. ** and returns 0).
  14785. **
  14786. ** Most malloc failures are non-benign. After they occur, SQLite
  14787. ** abandons the current operation and returns an error code (usually
  14788. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14789. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14790. ** is completely recoverable simply by not carrying out the resize. The
  14791. ** hash table will continue to function normally. So a malloc failure
  14792. ** during a hash table resize is a benign fault.
  14793. */
  14794. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14795. /*
  14796. ** Global variables.
  14797. */
  14798. typedef struct BenignMallocHooks BenignMallocHooks;
  14799. static SQLITE_WSD struct BenignMallocHooks {
  14800. void (*xBenignBegin)(void);
  14801. void (*xBenignEnd)(void);
  14802. } sqlite3Hooks = { 0, 0 };
  14803. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14804. ** structure. If writable static data is unsupported on the target,
  14805. ** we have to locate the state vector at run-time. In the more common
  14806. ** case where writable static data is supported, wsdHooks can refer directly
  14807. ** to the "sqlite3Hooks" state vector declared above.
  14808. */
  14809. #ifdef SQLITE_OMIT_WSD
  14810. # define wsdHooksInit \
  14811. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14812. # define wsdHooks x[0]
  14813. #else
  14814. # define wsdHooksInit
  14815. # define wsdHooks sqlite3Hooks
  14816. #endif
  14817. /*
  14818. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14819. ** sqlite3EndBenignMalloc() are called, respectively.
  14820. */
  14821. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14822. void (*xBenignBegin)(void),
  14823. void (*xBenignEnd)(void)
  14824. ){
  14825. wsdHooksInit;
  14826. wsdHooks.xBenignBegin = xBenignBegin;
  14827. wsdHooks.xBenignEnd = xBenignEnd;
  14828. }
  14829. /*
  14830. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14831. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14832. ** indicates that subsequent malloc failures are non-benign.
  14833. */
  14834. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14835. wsdHooksInit;
  14836. if( wsdHooks.xBenignBegin ){
  14837. wsdHooks.xBenignBegin();
  14838. }
  14839. }
  14840. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14841. wsdHooksInit;
  14842. if( wsdHooks.xBenignEnd ){
  14843. wsdHooks.xBenignEnd();
  14844. }
  14845. }
  14846. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14847. /************** End of fault.c ***********************************************/
  14848. /************** Begin file mem0.c ********************************************/
  14849. /*
  14850. ** 2008 October 28
  14851. **
  14852. ** The author disclaims copyright to this source code. In place of
  14853. ** a legal notice, here is a blessing:
  14854. **
  14855. ** May you do good and not evil.
  14856. ** May you find forgiveness for yourself and forgive others.
  14857. ** May you share freely, never taking more than you give.
  14858. **
  14859. *************************************************************************
  14860. **
  14861. ** This file contains a no-op memory allocation drivers for use when
  14862. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14863. ** here always fail. SQLite will not operate with these drivers. These
  14864. ** are merely placeholders. Real drivers must be substituted using
  14865. ** sqlite3_config() before SQLite will operate.
  14866. */
  14867. /*
  14868. ** This version of the memory allocator is the default. It is
  14869. ** used when no other memory allocator is specified using compile-time
  14870. ** macros.
  14871. */
  14872. #ifdef SQLITE_ZERO_MALLOC
  14873. /*
  14874. ** No-op versions of all memory allocation routines
  14875. */
  14876. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14877. static void sqlite3MemFree(void *pPrior){ return; }
  14878. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14879. static int sqlite3MemSize(void *pPrior){ return 0; }
  14880. static int sqlite3MemRoundup(int n){ return n; }
  14881. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14882. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14883. /*
  14884. ** This routine is the only routine in this file with external linkage.
  14885. **
  14886. ** Populate the low-level memory allocation function pointers in
  14887. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14888. */
  14889. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14890. static const sqlite3_mem_methods defaultMethods = {
  14891. sqlite3MemMalloc,
  14892. sqlite3MemFree,
  14893. sqlite3MemRealloc,
  14894. sqlite3MemSize,
  14895. sqlite3MemRoundup,
  14896. sqlite3MemInit,
  14897. sqlite3MemShutdown,
  14898. 0
  14899. };
  14900. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14901. }
  14902. #endif /* SQLITE_ZERO_MALLOC */
  14903. /************** End of mem0.c ************************************************/
  14904. /************** Begin file mem1.c ********************************************/
  14905. /*
  14906. ** 2007 August 14
  14907. **
  14908. ** The author disclaims copyright to this source code. In place of
  14909. ** a legal notice, here is a blessing:
  14910. **
  14911. ** May you do good and not evil.
  14912. ** May you find forgiveness for yourself and forgive others.
  14913. ** May you share freely, never taking more than you give.
  14914. **
  14915. *************************************************************************
  14916. **
  14917. ** This file contains low-level memory allocation drivers for when
  14918. ** SQLite will use the standard C-library malloc/realloc/free interface
  14919. ** to obtain the memory it needs.
  14920. **
  14921. ** This file contains implementations of the low-level memory allocation
  14922. ** routines specified in the sqlite3_mem_methods object. The content of
  14923. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  14924. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  14925. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  14926. ** default configuration is to use memory allocation routines in this
  14927. ** file.
  14928. **
  14929. ** C-preprocessor macro summary:
  14930. **
  14931. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  14932. ** the malloc_usable_size() interface exists
  14933. ** on the target platform. Or, this symbol
  14934. ** can be set manually, if desired.
  14935. ** If an equivalent interface exists by
  14936. ** a different name, using a separate -D
  14937. ** option to rename it.
  14938. **
  14939. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  14940. ** memory allocator. Set this symbol to enable
  14941. ** building on older macs.
  14942. **
  14943. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  14944. ** _msize() on windows systems. This might
  14945. ** be necessary when compiling for Delphi,
  14946. ** for example.
  14947. */
  14948. /*
  14949. ** This version of the memory allocator is the default. It is
  14950. ** used when no other memory allocator is specified using compile-time
  14951. ** macros.
  14952. */
  14953. #ifdef SQLITE_SYSTEM_MALLOC
  14954. /*
  14955. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  14956. ** The use of _msize() is automatic, but can be disabled by compiling
  14957. ** with -DSQLITE_WITHOUT_MSIZE
  14958. */
  14959. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  14960. # define SQLITE_MALLOCSIZE _msize
  14961. #endif
  14962. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  14963. /*
  14964. ** Use the zone allocator available on apple products unless the
  14965. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  14966. */
  14967. #include <sys/sysctl.h>
  14968. #include <malloc/malloc.h>
  14969. #include <libkern/OSAtomic.h>
  14970. static malloc_zone_t* _sqliteZone_;
  14971. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  14972. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  14973. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  14974. #define SQLITE_MALLOCSIZE(x) \
  14975. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  14976. #else /* if not __APPLE__ */
  14977. /*
  14978. ** Use standard C library malloc and free on non-Apple systems.
  14979. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  14980. */
  14981. #define SQLITE_MALLOC(x) malloc(x)
  14982. #define SQLITE_FREE(x) free(x)
  14983. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  14984. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  14985. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  14986. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  14987. #endif
  14988. #ifdef HAVE_MALLOC_USABLE_SIZE
  14989. # ifndef SQLITE_MALLOCSIZE
  14990. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  14991. # endif
  14992. #else
  14993. # undef SQLITE_MALLOCSIZE
  14994. #endif
  14995. #endif /* __APPLE__ or not __APPLE__ */
  14996. /*
  14997. ** Like malloc(), but remember the size of the allocation
  14998. ** so that we can find it later using sqlite3MemSize().
  14999. **
  15000. ** For this low-level routine, we are guaranteed that nByte>0 because
  15001. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15002. ** routines.
  15003. */
  15004. static void *sqlite3MemMalloc(int nByte){
  15005. #ifdef SQLITE_MALLOCSIZE
  15006. void *p = SQLITE_MALLOC( nByte );
  15007. if( p==0 ){
  15008. testcase( sqlite3GlobalConfig.xLog!=0 );
  15009. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15010. }
  15011. return p;
  15012. #else
  15013. sqlite3_int64 *p;
  15014. assert( nByte>0 );
  15015. nByte = ROUND8(nByte);
  15016. p = SQLITE_MALLOC( nByte+8 );
  15017. if( p ){
  15018. p[0] = nByte;
  15019. p++;
  15020. }else{
  15021. testcase( sqlite3GlobalConfig.xLog!=0 );
  15022. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15023. }
  15024. return (void *)p;
  15025. #endif
  15026. }
  15027. /*
  15028. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15029. ** or sqlite3MemRealloc().
  15030. **
  15031. ** For this low-level routine, we already know that pPrior!=0 since
  15032. ** cases where pPrior==0 will have been intecepted and dealt with
  15033. ** by higher-level routines.
  15034. */
  15035. static void sqlite3MemFree(void *pPrior){
  15036. #ifdef SQLITE_MALLOCSIZE
  15037. SQLITE_FREE(pPrior);
  15038. #else
  15039. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15040. assert( pPrior!=0 );
  15041. p--;
  15042. SQLITE_FREE(p);
  15043. #endif
  15044. }
  15045. /*
  15046. ** Report the allocated size of a prior return from xMalloc()
  15047. ** or xRealloc().
  15048. */
  15049. static int sqlite3MemSize(void *pPrior){
  15050. #ifdef SQLITE_MALLOCSIZE
  15051. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15052. #else
  15053. sqlite3_int64 *p;
  15054. if( pPrior==0 ) return 0;
  15055. p = (sqlite3_int64*)pPrior;
  15056. p--;
  15057. return (int)p[0];
  15058. #endif
  15059. }
  15060. /*
  15061. ** Like realloc(). Resize an allocation previously obtained from
  15062. ** sqlite3MemMalloc().
  15063. **
  15064. ** For this low-level interface, we know that pPrior!=0. Cases where
  15065. ** pPrior==0 while have been intercepted by higher-level routine and
  15066. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  15067. ** cases where nByte<=0 will have been intercepted by higher-level
  15068. ** routines and redirected to xFree.
  15069. */
  15070. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15071. #ifdef SQLITE_MALLOCSIZE
  15072. void *p = SQLITE_REALLOC(pPrior, nByte);
  15073. if( p==0 ){
  15074. testcase( sqlite3GlobalConfig.xLog!=0 );
  15075. sqlite3_log(SQLITE_NOMEM,
  15076. "failed memory resize %u to %u bytes",
  15077. SQLITE_MALLOCSIZE(pPrior), nByte);
  15078. }
  15079. return p;
  15080. #else
  15081. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15082. assert( pPrior!=0 && nByte>0 );
  15083. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15084. p--;
  15085. p = SQLITE_REALLOC(p, nByte+8 );
  15086. if( p ){
  15087. p[0] = nByte;
  15088. p++;
  15089. }else{
  15090. testcase( sqlite3GlobalConfig.xLog!=0 );
  15091. sqlite3_log(SQLITE_NOMEM,
  15092. "failed memory resize %u to %u bytes",
  15093. sqlite3MemSize(pPrior), nByte);
  15094. }
  15095. return (void*)p;
  15096. #endif
  15097. }
  15098. /*
  15099. ** Round up a request size to the next valid allocation size.
  15100. */
  15101. static int sqlite3MemRoundup(int n){
  15102. return ROUND8(n);
  15103. }
  15104. /*
  15105. ** Initialize this module.
  15106. */
  15107. static int sqlite3MemInit(void *NotUsed){
  15108. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15109. int cpuCount;
  15110. size_t len;
  15111. if( _sqliteZone_ ){
  15112. return SQLITE_OK;
  15113. }
  15114. len = sizeof(cpuCount);
  15115. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15116. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15117. if( cpuCount>1 ){
  15118. /* defer MT decisions to system malloc */
  15119. _sqliteZone_ = malloc_default_zone();
  15120. }else{
  15121. /* only 1 core, use our own zone to contention over global locks,
  15122. ** e.g. we have our own dedicated locks */
  15123. bool success;
  15124. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15125. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15126. do{
  15127. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15128. (void * volatile *)&_sqliteZone_);
  15129. }while(!_sqliteZone_);
  15130. if( !success ){
  15131. /* somebody registered a zone first */
  15132. malloc_destroy_zone(newzone);
  15133. }
  15134. }
  15135. #endif
  15136. UNUSED_PARAMETER(NotUsed);
  15137. return SQLITE_OK;
  15138. }
  15139. /*
  15140. ** Deinitialize this module.
  15141. */
  15142. static void sqlite3MemShutdown(void *NotUsed){
  15143. UNUSED_PARAMETER(NotUsed);
  15144. return;
  15145. }
  15146. /*
  15147. ** This routine is the only routine in this file with external linkage.
  15148. **
  15149. ** Populate the low-level memory allocation function pointers in
  15150. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15151. */
  15152. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15153. static const sqlite3_mem_methods defaultMethods = {
  15154. sqlite3MemMalloc,
  15155. sqlite3MemFree,
  15156. sqlite3MemRealloc,
  15157. sqlite3MemSize,
  15158. sqlite3MemRoundup,
  15159. sqlite3MemInit,
  15160. sqlite3MemShutdown,
  15161. 0
  15162. };
  15163. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15164. }
  15165. #endif /* SQLITE_SYSTEM_MALLOC */
  15166. /************** End of mem1.c ************************************************/
  15167. /************** Begin file mem2.c ********************************************/
  15168. /*
  15169. ** 2007 August 15
  15170. **
  15171. ** The author disclaims copyright to this source code. In place of
  15172. ** a legal notice, here is a blessing:
  15173. **
  15174. ** May you do good and not evil.
  15175. ** May you find forgiveness for yourself and forgive others.
  15176. ** May you share freely, never taking more than you give.
  15177. **
  15178. *************************************************************************
  15179. **
  15180. ** This file contains low-level memory allocation drivers for when
  15181. ** SQLite will use the standard C-library malloc/realloc/free interface
  15182. ** to obtain the memory it needs while adding lots of additional debugging
  15183. ** information to each allocation in order to help detect and fix memory
  15184. ** leaks and memory usage errors.
  15185. **
  15186. ** This file contains implementations of the low-level memory allocation
  15187. ** routines specified in the sqlite3_mem_methods object.
  15188. */
  15189. /*
  15190. ** This version of the memory allocator is used only if the
  15191. ** SQLITE_MEMDEBUG macro is defined
  15192. */
  15193. #ifdef SQLITE_MEMDEBUG
  15194. /*
  15195. ** The backtrace functionality is only available with GLIBC
  15196. */
  15197. #ifdef __GLIBC__
  15198. extern int backtrace(void**,int);
  15199. extern void backtrace_symbols_fd(void*const*,int,int);
  15200. #else
  15201. # define backtrace(A,B) 1
  15202. # define backtrace_symbols_fd(A,B,C)
  15203. #endif
  15204. /* #include <stdio.h> */
  15205. /*
  15206. ** Each memory allocation looks like this:
  15207. **
  15208. ** ------------------------------------------------------------------------
  15209. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15210. ** ------------------------------------------------------------------------
  15211. **
  15212. ** The application code sees only a pointer to the allocation. We have
  15213. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15214. ** MemBlockHdr tells us the size of the allocation and the number of
  15215. ** backtrace pointers. There is also a guard word at the end of the
  15216. ** MemBlockHdr.
  15217. */
  15218. struct MemBlockHdr {
  15219. i64 iSize; /* Size of this allocation */
  15220. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15221. char nBacktrace; /* Number of backtraces on this alloc */
  15222. char nBacktraceSlots; /* Available backtrace slots */
  15223. u8 nTitle; /* Bytes of title; includes '\0' */
  15224. u8 eType; /* Allocation type code */
  15225. int iForeGuard; /* Guard word for sanity */
  15226. };
  15227. /*
  15228. ** Guard words
  15229. */
  15230. #define FOREGUARD 0x80F5E153
  15231. #define REARGUARD 0xE4676B53
  15232. /*
  15233. ** Number of malloc size increments to track.
  15234. */
  15235. #define NCSIZE 1000
  15236. /*
  15237. ** All of the static variables used by this module are collected
  15238. ** into a single structure named "mem". This is to keep the
  15239. ** static variables organized and to reduce namespace pollution
  15240. ** when this module is combined with other in the amalgamation.
  15241. */
  15242. static struct {
  15243. /*
  15244. ** Mutex to control access to the memory allocation subsystem.
  15245. */
  15246. sqlite3_mutex *mutex;
  15247. /*
  15248. ** Head and tail of a linked list of all outstanding allocations
  15249. */
  15250. struct MemBlockHdr *pFirst;
  15251. struct MemBlockHdr *pLast;
  15252. /*
  15253. ** The number of levels of backtrace to save in new allocations.
  15254. */
  15255. int nBacktrace;
  15256. void (*xBacktrace)(int, int, void **);
  15257. /*
  15258. ** Title text to insert in front of each block
  15259. */
  15260. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15261. char zTitle[100]; /* The title text */
  15262. /*
  15263. ** sqlite3MallocDisallow() increments the following counter.
  15264. ** sqlite3MallocAllow() decrements it.
  15265. */
  15266. int disallow; /* Do not allow memory allocation */
  15267. /*
  15268. ** Gather statistics on the sizes of memory allocations.
  15269. ** nAlloc[i] is the number of allocation attempts of i*8
  15270. ** bytes. i==NCSIZE is the number of allocation attempts for
  15271. ** sizes more than NCSIZE*8 bytes.
  15272. */
  15273. int nAlloc[NCSIZE]; /* Total number of allocations */
  15274. int nCurrent[NCSIZE]; /* Current number of allocations */
  15275. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15276. } mem;
  15277. /*
  15278. ** Adjust memory usage statistics
  15279. */
  15280. static void adjustStats(int iSize, int increment){
  15281. int i = ROUND8(iSize)/8;
  15282. if( i>NCSIZE-1 ){
  15283. i = NCSIZE - 1;
  15284. }
  15285. if( increment>0 ){
  15286. mem.nAlloc[i]++;
  15287. mem.nCurrent[i]++;
  15288. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15289. mem.mxCurrent[i] = mem.nCurrent[i];
  15290. }
  15291. }else{
  15292. mem.nCurrent[i]--;
  15293. assert( mem.nCurrent[i]>=0 );
  15294. }
  15295. }
  15296. /*
  15297. ** Given an allocation, find the MemBlockHdr for that allocation.
  15298. **
  15299. ** This routine checks the guards at either end of the allocation and
  15300. ** if they are incorrect it asserts.
  15301. */
  15302. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15303. struct MemBlockHdr *p;
  15304. int *pInt;
  15305. u8 *pU8;
  15306. int nReserve;
  15307. p = (struct MemBlockHdr*)pAllocation;
  15308. p--;
  15309. assert( p->iForeGuard==(int)FOREGUARD );
  15310. nReserve = ROUND8(p->iSize);
  15311. pInt = (int*)pAllocation;
  15312. pU8 = (u8*)pAllocation;
  15313. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15314. /* This checks any of the "extra" bytes allocated due
  15315. ** to rounding up to an 8 byte boundary to ensure
  15316. ** they haven't been overwritten.
  15317. */
  15318. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15319. return p;
  15320. }
  15321. /*
  15322. ** Return the number of bytes currently allocated at address p.
  15323. */
  15324. static int sqlite3MemSize(void *p){
  15325. struct MemBlockHdr *pHdr;
  15326. if( !p ){
  15327. return 0;
  15328. }
  15329. pHdr = sqlite3MemsysGetHeader(p);
  15330. return pHdr->iSize;
  15331. }
  15332. /*
  15333. ** Initialize the memory allocation subsystem.
  15334. */
  15335. static int sqlite3MemInit(void *NotUsed){
  15336. UNUSED_PARAMETER(NotUsed);
  15337. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15338. if( !sqlite3GlobalConfig.bMemstat ){
  15339. /* If memory status is enabled, then the malloc.c wrapper will already
  15340. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15341. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15342. }
  15343. return SQLITE_OK;
  15344. }
  15345. /*
  15346. ** Deinitialize the memory allocation subsystem.
  15347. */
  15348. static void sqlite3MemShutdown(void *NotUsed){
  15349. UNUSED_PARAMETER(NotUsed);
  15350. mem.mutex = 0;
  15351. }
  15352. /*
  15353. ** Round up a request size to the next valid allocation size.
  15354. */
  15355. static int sqlite3MemRoundup(int n){
  15356. return ROUND8(n);
  15357. }
  15358. /*
  15359. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15360. ** the content of a new memory allocation to unpredictable values and
  15361. ** to clear the content of a freed allocation to unpredictable values.
  15362. */
  15363. static void randomFill(char *pBuf, int nByte){
  15364. unsigned int x, y, r;
  15365. x = SQLITE_PTR_TO_INT(pBuf);
  15366. y = nByte | 1;
  15367. while( nByte >= 4 ){
  15368. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  15369. y = y*1103515245 + 12345;
  15370. r = x ^ y;
  15371. *(int*)pBuf = r;
  15372. pBuf += 4;
  15373. nByte -= 4;
  15374. }
  15375. while( nByte-- > 0 ){
  15376. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  15377. y = y*1103515245 + 12345;
  15378. r = x ^ y;
  15379. *(pBuf++) = r & 0xff;
  15380. }
  15381. }
  15382. /*
  15383. ** Allocate nByte bytes of memory.
  15384. */
  15385. static void *sqlite3MemMalloc(int nByte){
  15386. struct MemBlockHdr *pHdr;
  15387. void **pBt;
  15388. char *z;
  15389. int *pInt;
  15390. void *p = 0;
  15391. int totalSize;
  15392. int nReserve;
  15393. sqlite3_mutex_enter(mem.mutex);
  15394. assert( mem.disallow==0 );
  15395. nReserve = ROUND8(nByte);
  15396. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15397. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15398. p = malloc(totalSize);
  15399. if( p ){
  15400. z = p;
  15401. pBt = (void**)&z[mem.nTitle];
  15402. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15403. pHdr->pNext = 0;
  15404. pHdr->pPrev = mem.pLast;
  15405. if( mem.pLast ){
  15406. mem.pLast->pNext = pHdr;
  15407. }else{
  15408. mem.pFirst = pHdr;
  15409. }
  15410. mem.pLast = pHdr;
  15411. pHdr->iForeGuard = FOREGUARD;
  15412. pHdr->eType = MEMTYPE_HEAP;
  15413. pHdr->nBacktraceSlots = mem.nBacktrace;
  15414. pHdr->nTitle = mem.nTitle;
  15415. if( mem.nBacktrace ){
  15416. void *aAddr[40];
  15417. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15418. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15419. assert(pBt[0]);
  15420. if( mem.xBacktrace ){
  15421. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15422. }
  15423. }else{
  15424. pHdr->nBacktrace = 0;
  15425. }
  15426. if( mem.nTitle ){
  15427. memcpy(z, mem.zTitle, mem.nTitle);
  15428. }
  15429. pHdr->iSize = nByte;
  15430. adjustStats(nByte, +1);
  15431. pInt = (int*)&pHdr[1];
  15432. pInt[nReserve/sizeof(int)] = REARGUARD;
  15433. randomFill((char*)pInt, nByte);
  15434. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15435. p = (void*)pInt;
  15436. }
  15437. sqlite3_mutex_leave(mem.mutex);
  15438. return p;
  15439. }
  15440. /*
  15441. ** Free memory.
  15442. */
  15443. static void sqlite3MemFree(void *pPrior){
  15444. struct MemBlockHdr *pHdr;
  15445. void **pBt;
  15446. char *z;
  15447. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15448. || mem.mutex!=0 );
  15449. pHdr = sqlite3MemsysGetHeader(pPrior);
  15450. pBt = (void**)pHdr;
  15451. pBt -= pHdr->nBacktraceSlots;
  15452. sqlite3_mutex_enter(mem.mutex);
  15453. if( pHdr->pPrev ){
  15454. assert( pHdr->pPrev->pNext==pHdr );
  15455. pHdr->pPrev->pNext = pHdr->pNext;
  15456. }else{
  15457. assert( mem.pFirst==pHdr );
  15458. mem.pFirst = pHdr->pNext;
  15459. }
  15460. if( pHdr->pNext ){
  15461. assert( pHdr->pNext->pPrev==pHdr );
  15462. pHdr->pNext->pPrev = pHdr->pPrev;
  15463. }else{
  15464. assert( mem.pLast==pHdr );
  15465. mem.pLast = pHdr->pPrev;
  15466. }
  15467. z = (char*)pBt;
  15468. z -= pHdr->nTitle;
  15469. adjustStats(pHdr->iSize, -1);
  15470. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15471. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15472. free(z);
  15473. sqlite3_mutex_leave(mem.mutex);
  15474. }
  15475. /*
  15476. ** Change the size of an existing memory allocation.
  15477. **
  15478. ** For this debugging implementation, we *always* make a copy of the
  15479. ** allocation into a new place in memory. In this way, if the
  15480. ** higher level code is using pointer to the old allocation, it is
  15481. ** much more likely to break and we are much more liking to find
  15482. ** the error.
  15483. */
  15484. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15485. struct MemBlockHdr *pOldHdr;
  15486. void *pNew;
  15487. assert( mem.disallow==0 );
  15488. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15489. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15490. pNew = sqlite3MemMalloc(nByte);
  15491. if( pNew ){
  15492. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  15493. if( nByte>pOldHdr->iSize ){
  15494. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
  15495. }
  15496. sqlite3MemFree(pPrior);
  15497. }
  15498. return pNew;
  15499. }
  15500. /*
  15501. ** Populate the low-level memory allocation function pointers in
  15502. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15503. */
  15504. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15505. static const sqlite3_mem_methods defaultMethods = {
  15506. sqlite3MemMalloc,
  15507. sqlite3MemFree,
  15508. sqlite3MemRealloc,
  15509. sqlite3MemSize,
  15510. sqlite3MemRoundup,
  15511. sqlite3MemInit,
  15512. sqlite3MemShutdown,
  15513. 0
  15514. };
  15515. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15516. }
  15517. /*
  15518. ** Set the "type" of an allocation.
  15519. */
  15520. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15521. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15522. struct MemBlockHdr *pHdr;
  15523. pHdr = sqlite3MemsysGetHeader(p);
  15524. assert( pHdr->iForeGuard==FOREGUARD );
  15525. pHdr->eType = eType;
  15526. }
  15527. }
  15528. /*
  15529. ** Return TRUE if the mask of type in eType matches the type of the
  15530. ** allocation p. Also return true if p==NULL.
  15531. **
  15532. ** This routine is designed for use within an assert() statement, to
  15533. ** verify the type of an allocation. For example:
  15534. **
  15535. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15536. */
  15537. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15538. int rc = 1;
  15539. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15540. struct MemBlockHdr *pHdr;
  15541. pHdr = sqlite3MemsysGetHeader(p);
  15542. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15543. if( (pHdr->eType&eType)==0 ){
  15544. rc = 0;
  15545. }
  15546. }
  15547. return rc;
  15548. }
  15549. /*
  15550. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15551. ** allocation p. Also return true if p==NULL.
  15552. **
  15553. ** This routine is designed for use within an assert() statement, to
  15554. ** verify the type of an allocation. For example:
  15555. **
  15556. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15557. */
  15558. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15559. int rc = 1;
  15560. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15561. struct MemBlockHdr *pHdr;
  15562. pHdr = sqlite3MemsysGetHeader(p);
  15563. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15564. if( (pHdr->eType&eType)!=0 ){
  15565. rc = 0;
  15566. }
  15567. }
  15568. return rc;
  15569. }
  15570. /*
  15571. ** Set the number of backtrace levels kept for each allocation.
  15572. ** A value of zero turns off backtracing. The number is always rounded
  15573. ** up to a multiple of 2.
  15574. */
  15575. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15576. if( depth<0 ){ depth = 0; }
  15577. if( depth>20 ){ depth = 20; }
  15578. depth = (depth+1)&0xfe;
  15579. mem.nBacktrace = depth;
  15580. }
  15581. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15582. mem.xBacktrace = xBacktrace;
  15583. }
  15584. /*
  15585. ** Set the title string for subsequent allocations.
  15586. */
  15587. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15588. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15589. sqlite3_mutex_enter(mem.mutex);
  15590. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15591. memcpy(mem.zTitle, zTitle, n);
  15592. mem.zTitle[n] = 0;
  15593. mem.nTitle = ROUND8(n);
  15594. sqlite3_mutex_leave(mem.mutex);
  15595. }
  15596. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15597. struct MemBlockHdr *pHdr;
  15598. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15599. void **pBt = (void**)pHdr;
  15600. pBt -= pHdr->nBacktraceSlots;
  15601. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15602. }
  15603. }
  15604. /*
  15605. ** Open the file indicated and write a log of all unfreed memory
  15606. ** allocations into that log.
  15607. */
  15608. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15609. FILE *out;
  15610. struct MemBlockHdr *pHdr;
  15611. void **pBt;
  15612. int i;
  15613. out = fopen(zFilename, "w");
  15614. if( out==0 ){
  15615. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15616. zFilename);
  15617. return;
  15618. }
  15619. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15620. char *z = (char*)pHdr;
  15621. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15622. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15623. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15624. if( pHdr->nBacktrace ){
  15625. fflush(out);
  15626. pBt = (void**)pHdr;
  15627. pBt -= pHdr->nBacktraceSlots;
  15628. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15629. fprintf(out, "\n");
  15630. }
  15631. }
  15632. fprintf(out, "COUNTS:\n");
  15633. for(i=0; i<NCSIZE-1; i++){
  15634. if( mem.nAlloc[i] ){
  15635. fprintf(out, " %5d: %10d %10d %10d\n",
  15636. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15637. }
  15638. }
  15639. if( mem.nAlloc[NCSIZE-1] ){
  15640. fprintf(out, " %5d: %10d %10d %10d\n",
  15641. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15642. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15643. }
  15644. fclose(out);
  15645. }
  15646. /*
  15647. ** Return the number of times sqlite3MemMalloc() has been called.
  15648. */
  15649. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15650. int i;
  15651. int nTotal = 0;
  15652. for(i=0; i<NCSIZE; i++){
  15653. nTotal += mem.nAlloc[i];
  15654. }
  15655. return nTotal;
  15656. }
  15657. #endif /* SQLITE_MEMDEBUG */
  15658. /************** End of mem2.c ************************************************/
  15659. /************** Begin file mem3.c ********************************************/
  15660. /*
  15661. ** 2007 October 14
  15662. **
  15663. ** The author disclaims copyright to this source code. In place of
  15664. ** a legal notice, here is a blessing:
  15665. **
  15666. ** May you do good and not evil.
  15667. ** May you find forgiveness for yourself and forgive others.
  15668. ** May you share freely, never taking more than you give.
  15669. **
  15670. *************************************************************************
  15671. ** This file contains the C functions that implement a memory
  15672. ** allocation subsystem for use by SQLite.
  15673. **
  15674. ** This version of the memory allocation subsystem omits all
  15675. ** use of malloc(). The SQLite user supplies a block of memory
  15676. ** before calling sqlite3_initialize() from which allocations
  15677. ** are made and returned by the xMalloc() and xRealloc()
  15678. ** implementations. Once sqlite3_initialize() has been called,
  15679. ** the amount of memory available to SQLite is fixed and cannot
  15680. ** be changed.
  15681. **
  15682. ** This version of the memory allocation subsystem is included
  15683. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15684. */
  15685. /*
  15686. ** This version of the memory allocator is only built into the library
  15687. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15688. ** mean that the library will use a memory-pool by default, just that
  15689. ** it is available. The mempool allocator is activated by calling
  15690. ** sqlite3_config().
  15691. */
  15692. #ifdef SQLITE_ENABLE_MEMSYS3
  15693. /*
  15694. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15695. */
  15696. #define MX_SMALL 10
  15697. /*
  15698. ** Number of freelist hash slots
  15699. */
  15700. #define N_HASH 61
  15701. /*
  15702. ** A memory allocation (also called a "chunk") consists of two or
  15703. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15704. ** a header that is not returned to the user.
  15705. **
  15706. ** A chunk is two or more blocks that is either checked out or
  15707. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15708. ** size of the allocation in blocks if the allocation is free.
  15709. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15710. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15711. ** is true if the previous chunk is checked out and false if the
  15712. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15713. ** the previous chunk in blocks if the previous chunk is on the
  15714. ** freelist. If the previous chunk is checked out, then
  15715. ** u.hdr.prevSize can be part of the data for that chunk and should
  15716. ** not be read or written.
  15717. **
  15718. ** We often identify a chunk by its index in mem3.aPool[]. When
  15719. ** this is done, the chunk index refers to the second block of
  15720. ** the chunk. In this way, the first chunk has an index of 1.
  15721. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15722. ** of a NULL pointer.
  15723. **
  15724. ** The second block of free chunks is of the form u.list. The
  15725. ** two fields form a double-linked list of chunks of related sizes.
  15726. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15727. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15728. **
  15729. ** The second block of a chunk is user data if the chunk is checked
  15730. ** out. If a chunk is checked out, the user data may extend into
  15731. ** the u.hdr.prevSize value of the following chunk.
  15732. */
  15733. typedef struct Mem3Block Mem3Block;
  15734. struct Mem3Block {
  15735. union {
  15736. struct {
  15737. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15738. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15739. } hdr;
  15740. struct {
  15741. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15742. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15743. } list;
  15744. } u;
  15745. };
  15746. /*
  15747. ** All of the static variables used by this module are collected
  15748. ** into a single structure named "mem3". This is to keep the
  15749. ** static variables organized and to reduce namespace pollution
  15750. ** when this module is combined with other in the amalgamation.
  15751. */
  15752. static SQLITE_WSD struct Mem3Global {
  15753. /*
  15754. ** Memory available for allocation. nPool is the size of the array
  15755. ** (in Mem3Blocks) pointed to by aPool less 2.
  15756. */
  15757. u32 nPool;
  15758. Mem3Block *aPool;
  15759. /*
  15760. ** True if we are evaluating an out-of-memory callback.
  15761. */
  15762. int alarmBusy;
  15763. /*
  15764. ** Mutex to control access to the memory allocation subsystem.
  15765. */
  15766. sqlite3_mutex *mutex;
  15767. /*
  15768. ** The minimum amount of free space that we have seen.
  15769. */
  15770. u32 mnMaster;
  15771. /*
  15772. ** iMaster is the index of the master chunk. Most new allocations
  15773. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15774. ** of the current master. iMaster is 0 if there is not master chunk.
  15775. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15776. */
  15777. u32 iMaster;
  15778. u32 szMaster;
  15779. /*
  15780. ** Array of lists of free blocks according to the block size
  15781. ** for smaller chunks, or a hash on the block size for larger
  15782. ** chunks.
  15783. */
  15784. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15785. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15786. } mem3 = { 97535575 };
  15787. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15788. /*
  15789. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15790. ** on. *pRoot is the list that i is a member of.
  15791. */
  15792. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15793. u32 next = mem3.aPool[i].u.list.next;
  15794. u32 prev = mem3.aPool[i].u.list.prev;
  15795. assert( sqlite3_mutex_held(mem3.mutex) );
  15796. if( prev==0 ){
  15797. *pRoot = next;
  15798. }else{
  15799. mem3.aPool[prev].u.list.next = next;
  15800. }
  15801. if( next ){
  15802. mem3.aPool[next].u.list.prev = prev;
  15803. }
  15804. mem3.aPool[i].u.list.next = 0;
  15805. mem3.aPool[i].u.list.prev = 0;
  15806. }
  15807. /*
  15808. ** Unlink the chunk at index i from
  15809. ** whatever list is currently a member of.
  15810. */
  15811. static void memsys3Unlink(u32 i){
  15812. u32 size, hash;
  15813. assert( sqlite3_mutex_held(mem3.mutex) );
  15814. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15815. assert( i>=1 );
  15816. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15817. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15818. assert( size>=2 );
  15819. if( size <= MX_SMALL ){
  15820. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15821. }else{
  15822. hash = size % N_HASH;
  15823. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15824. }
  15825. }
  15826. /*
  15827. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15828. ** at *pRoot.
  15829. */
  15830. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15831. assert( sqlite3_mutex_held(mem3.mutex) );
  15832. mem3.aPool[i].u.list.next = *pRoot;
  15833. mem3.aPool[i].u.list.prev = 0;
  15834. if( *pRoot ){
  15835. mem3.aPool[*pRoot].u.list.prev = i;
  15836. }
  15837. *pRoot = i;
  15838. }
  15839. /*
  15840. ** Link the chunk at index i into either the appropriate
  15841. ** small chunk list, or into the large chunk hash table.
  15842. */
  15843. static void memsys3Link(u32 i){
  15844. u32 size, hash;
  15845. assert( sqlite3_mutex_held(mem3.mutex) );
  15846. assert( i>=1 );
  15847. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15848. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15849. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15850. assert( size>=2 );
  15851. if( size <= MX_SMALL ){
  15852. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15853. }else{
  15854. hash = size % N_HASH;
  15855. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15856. }
  15857. }
  15858. /*
  15859. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15860. ** will already be held (obtained by code in malloc.c) if
  15861. ** sqlite3GlobalConfig.bMemStat is true.
  15862. */
  15863. static void memsys3Enter(void){
  15864. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15865. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15866. }
  15867. sqlite3_mutex_enter(mem3.mutex);
  15868. }
  15869. static void memsys3Leave(void){
  15870. sqlite3_mutex_leave(mem3.mutex);
  15871. }
  15872. /*
  15873. ** Called when we are unable to satisfy an allocation of nBytes.
  15874. */
  15875. static void memsys3OutOfMemory(int nByte){
  15876. if( !mem3.alarmBusy ){
  15877. mem3.alarmBusy = 1;
  15878. assert( sqlite3_mutex_held(mem3.mutex) );
  15879. sqlite3_mutex_leave(mem3.mutex);
  15880. sqlite3_release_memory(nByte);
  15881. sqlite3_mutex_enter(mem3.mutex);
  15882. mem3.alarmBusy = 0;
  15883. }
  15884. }
  15885. /*
  15886. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15887. ** size parameters for check-out and return a pointer to the
  15888. ** user portion of the chunk.
  15889. */
  15890. static void *memsys3Checkout(u32 i, u32 nBlock){
  15891. u32 x;
  15892. assert( sqlite3_mutex_held(mem3.mutex) );
  15893. assert( i>=1 );
  15894. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15895. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15896. x = mem3.aPool[i-1].u.hdr.size4x;
  15897. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15898. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15899. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15900. return &mem3.aPool[i];
  15901. }
  15902. /*
  15903. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15904. ** Return a pointer to the new allocation. Or, if the master chunk
  15905. ** is not large enough, return 0.
  15906. */
  15907. static void *memsys3FromMaster(u32 nBlock){
  15908. assert( sqlite3_mutex_held(mem3.mutex) );
  15909. assert( mem3.szMaster>=nBlock );
  15910. if( nBlock>=mem3.szMaster-1 ){
  15911. /* Use the entire master */
  15912. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15913. mem3.iMaster = 0;
  15914. mem3.szMaster = 0;
  15915. mem3.mnMaster = 0;
  15916. return p;
  15917. }else{
  15918. /* Split the master block. Return the tail. */
  15919. u32 newi, x;
  15920. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15921. assert( newi > mem3.iMaster+1 );
  15922. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15923. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15924. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15925. mem3.szMaster -= nBlock;
  15926. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  15927. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15928. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15929. if( mem3.szMaster < mem3.mnMaster ){
  15930. mem3.mnMaster = mem3.szMaster;
  15931. }
  15932. return (void*)&mem3.aPool[newi];
  15933. }
  15934. }
  15935. /*
  15936. ** *pRoot is the head of a list of free chunks of the same size
  15937. ** or same size hash. In other words, *pRoot is an entry in either
  15938. ** mem3.aiSmall[] or mem3.aiHash[].
  15939. **
  15940. ** This routine examines all entries on the given list and tries
  15941. ** to coalesce each entries with adjacent free chunks.
  15942. **
  15943. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  15944. ** the current mem3.iMaster with the new larger chunk. In order for
  15945. ** this mem3.iMaster replacement to work, the master chunk must be
  15946. ** linked into the hash tables. That is not the normal state of
  15947. ** affairs, of course. The calling routine must link the master
  15948. ** chunk before invoking this routine, then must unlink the (possibly
  15949. ** changed) master chunk once this routine has finished.
  15950. */
  15951. static void memsys3Merge(u32 *pRoot){
  15952. u32 iNext, prev, size, i, x;
  15953. assert( sqlite3_mutex_held(mem3.mutex) );
  15954. for(i=*pRoot; i>0; i=iNext){
  15955. iNext = mem3.aPool[i].u.list.next;
  15956. size = mem3.aPool[i-1].u.hdr.size4x;
  15957. assert( (size&1)==0 );
  15958. if( (size&2)==0 ){
  15959. memsys3UnlinkFromList(i, pRoot);
  15960. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  15961. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  15962. if( prev==iNext ){
  15963. iNext = mem3.aPool[prev].u.list.next;
  15964. }
  15965. memsys3Unlink(prev);
  15966. size = i + size/4 - prev;
  15967. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  15968. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  15969. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  15970. memsys3Link(prev);
  15971. i = prev;
  15972. }else{
  15973. size /= 4;
  15974. }
  15975. if( size>mem3.szMaster ){
  15976. mem3.iMaster = i;
  15977. mem3.szMaster = size;
  15978. }
  15979. }
  15980. }
  15981. /*
  15982. ** Return a block of memory of at least nBytes in size.
  15983. ** Return NULL if unable.
  15984. **
  15985. ** This function assumes that the necessary mutexes, if any, are
  15986. ** already held by the caller. Hence "Unsafe".
  15987. */
  15988. static void *memsys3MallocUnsafe(int nByte){
  15989. u32 i;
  15990. u32 nBlock;
  15991. u32 toFree;
  15992. assert( sqlite3_mutex_held(mem3.mutex) );
  15993. assert( sizeof(Mem3Block)==8 );
  15994. if( nByte<=12 ){
  15995. nBlock = 2;
  15996. }else{
  15997. nBlock = (nByte + 11)/8;
  15998. }
  15999. assert( nBlock>=2 );
  16000. /* STEP 1:
  16001. ** Look for an entry of the correct size in either the small
  16002. ** chunk table or in the large chunk hash table. This is
  16003. ** successful most of the time (about 9 times out of 10).
  16004. */
  16005. if( nBlock <= MX_SMALL ){
  16006. i = mem3.aiSmall[nBlock-2];
  16007. if( i>0 ){
  16008. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16009. return memsys3Checkout(i, nBlock);
  16010. }
  16011. }else{
  16012. int hash = nBlock % N_HASH;
  16013. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16014. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16015. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16016. return memsys3Checkout(i, nBlock);
  16017. }
  16018. }
  16019. }
  16020. /* STEP 2:
  16021. ** Try to satisfy the allocation by carving a piece off of the end
  16022. ** of the master chunk. This step usually works if step 1 fails.
  16023. */
  16024. if( mem3.szMaster>=nBlock ){
  16025. return memsys3FromMaster(nBlock);
  16026. }
  16027. /* STEP 3:
  16028. ** Loop through the entire memory pool. Coalesce adjacent free
  16029. ** chunks. Recompute the master chunk as the largest free chunk.
  16030. ** Then try again to satisfy the allocation by carving a piece off
  16031. ** of the end of the master chunk. This step happens very
  16032. ** rarely (we hope!)
  16033. */
  16034. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16035. memsys3OutOfMemory(toFree);
  16036. if( mem3.iMaster ){
  16037. memsys3Link(mem3.iMaster);
  16038. mem3.iMaster = 0;
  16039. mem3.szMaster = 0;
  16040. }
  16041. for(i=0; i<N_HASH; i++){
  16042. memsys3Merge(&mem3.aiHash[i]);
  16043. }
  16044. for(i=0; i<MX_SMALL-1; i++){
  16045. memsys3Merge(&mem3.aiSmall[i]);
  16046. }
  16047. if( mem3.szMaster ){
  16048. memsys3Unlink(mem3.iMaster);
  16049. if( mem3.szMaster>=nBlock ){
  16050. return memsys3FromMaster(nBlock);
  16051. }
  16052. }
  16053. }
  16054. /* If none of the above worked, then we fail. */
  16055. return 0;
  16056. }
  16057. /*
  16058. ** Free an outstanding memory allocation.
  16059. **
  16060. ** This function assumes that the necessary mutexes, if any, are
  16061. ** already held by the caller. Hence "Unsafe".
  16062. */
  16063. static void memsys3FreeUnsafe(void *pOld){
  16064. Mem3Block *p = (Mem3Block*)pOld;
  16065. int i;
  16066. u32 size, x;
  16067. assert( sqlite3_mutex_held(mem3.mutex) );
  16068. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16069. i = p - mem3.aPool;
  16070. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16071. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16072. assert( i+size<=mem3.nPool+1 );
  16073. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16074. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16075. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16076. memsys3Link(i);
  16077. /* Try to expand the master using the newly freed chunk */
  16078. if( mem3.iMaster ){
  16079. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16080. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16081. mem3.iMaster -= size;
  16082. mem3.szMaster += size;
  16083. memsys3Unlink(mem3.iMaster);
  16084. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16085. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16086. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16087. }
  16088. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16089. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16090. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16091. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16092. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16093. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16094. }
  16095. }
  16096. }
  16097. /*
  16098. ** Return the size of an outstanding allocation, in bytes. The
  16099. ** size returned omits the 8-byte header overhead. This only
  16100. ** works for chunks that are currently checked out.
  16101. */
  16102. static int memsys3Size(void *p){
  16103. Mem3Block *pBlock;
  16104. if( p==0 ) return 0;
  16105. pBlock = (Mem3Block*)p;
  16106. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16107. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16108. }
  16109. /*
  16110. ** Round up a request size to the next valid allocation size.
  16111. */
  16112. static int memsys3Roundup(int n){
  16113. if( n<=12 ){
  16114. return 12;
  16115. }else{
  16116. return ((n+11)&~7) - 4;
  16117. }
  16118. }
  16119. /*
  16120. ** Allocate nBytes of memory.
  16121. */
  16122. static void *memsys3Malloc(int nBytes){
  16123. sqlite3_int64 *p;
  16124. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16125. memsys3Enter();
  16126. p = memsys3MallocUnsafe(nBytes);
  16127. memsys3Leave();
  16128. return (void*)p;
  16129. }
  16130. /*
  16131. ** Free memory.
  16132. */
  16133. static void memsys3Free(void *pPrior){
  16134. assert( pPrior );
  16135. memsys3Enter();
  16136. memsys3FreeUnsafe(pPrior);
  16137. memsys3Leave();
  16138. }
  16139. /*
  16140. ** Change the size of an existing memory allocation
  16141. */
  16142. static void *memsys3Realloc(void *pPrior, int nBytes){
  16143. int nOld;
  16144. void *p;
  16145. if( pPrior==0 ){
  16146. return sqlite3_malloc(nBytes);
  16147. }
  16148. if( nBytes<=0 ){
  16149. sqlite3_free(pPrior);
  16150. return 0;
  16151. }
  16152. nOld = memsys3Size(pPrior);
  16153. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16154. return pPrior;
  16155. }
  16156. memsys3Enter();
  16157. p = memsys3MallocUnsafe(nBytes);
  16158. if( p ){
  16159. if( nOld<nBytes ){
  16160. memcpy(p, pPrior, nOld);
  16161. }else{
  16162. memcpy(p, pPrior, nBytes);
  16163. }
  16164. memsys3FreeUnsafe(pPrior);
  16165. }
  16166. memsys3Leave();
  16167. return p;
  16168. }
  16169. /*
  16170. ** Initialize this module.
  16171. */
  16172. static int memsys3Init(void *NotUsed){
  16173. UNUSED_PARAMETER(NotUsed);
  16174. if( !sqlite3GlobalConfig.pHeap ){
  16175. return SQLITE_ERROR;
  16176. }
  16177. /* Store a pointer to the memory block in global structure mem3. */
  16178. assert( sizeof(Mem3Block)==8 );
  16179. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16180. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16181. /* Initialize the master block. */
  16182. mem3.szMaster = mem3.nPool;
  16183. mem3.mnMaster = mem3.szMaster;
  16184. mem3.iMaster = 1;
  16185. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16186. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16187. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16188. return SQLITE_OK;
  16189. }
  16190. /*
  16191. ** Deinitialize this module.
  16192. */
  16193. static void memsys3Shutdown(void *NotUsed){
  16194. UNUSED_PARAMETER(NotUsed);
  16195. mem3.mutex = 0;
  16196. return;
  16197. }
  16198. /*
  16199. ** Open the file indicated and write a log of all unfreed memory
  16200. ** allocations into that log.
  16201. */
  16202. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16203. #ifdef SQLITE_DEBUG
  16204. FILE *out;
  16205. u32 i, j;
  16206. u32 size;
  16207. if( zFilename==0 || zFilename[0]==0 ){
  16208. out = stdout;
  16209. }else{
  16210. out = fopen(zFilename, "w");
  16211. if( out==0 ){
  16212. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16213. zFilename);
  16214. return;
  16215. }
  16216. }
  16217. memsys3Enter();
  16218. fprintf(out, "CHUNKS:\n");
  16219. for(i=1; i<=mem3.nPool; i+=size/4){
  16220. size = mem3.aPool[i-1].u.hdr.size4x;
  16221. if( size/4<=1 ){
  16222. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16223. assert( 0 );
  16224. break;
  16225. }
  16226. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16227. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16228. assert( 0 );
  16229. break;
  16230. }
  16231. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16232. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16233. assert( 0 );
  16234. break;
  16235. }
  16236. if( size&1 ){
  16237. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16238. }else{
  16239. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16240. i==mem3.iMaster ? " **master**" : "");
  16241. }
  16242. }
  16243. for(i=0; i<MX_SMALL-1; i++){
  16244. if( mem3.aiSmall[i]==0 ) continue;
  16245. fprintf(out, "small(%2d):", i);
  16246. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16247. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16248. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16249. }
  16250. fprintf(out, "\n");
  16251. }
  16252. for(i=0; i<N_HASH; i++){
  16253. if( mem3.aiHash[i]==0 ) continue;
  16254. fprintf(out, "hash(%2d):", i);
  16255. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16256. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16257. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16258. }
  16259. fprintf(out, "\n");
  16260. }
  16261. fprintf(out, "master=%d\n", mem3.iMaster);
  16262. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16263. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16264. sqlite3_mutex_leave(mem3.mutex);
  16265. if( out==stdout ){
  16266. fflush(stdout);
  16267. }else{
  16268. fclose(out);
  16269. }
  16270. #else
  16271. UNUSED_PARAMETER(zFilename);
  16272. #endif
  16273. }
  16274. /*
  16275. ** This routine is the only routine in this file with external
  16276. ** linkage.
  16277. **
  16278. ** Populate the low-level memory allocation function pointers in
  16279. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16280. ** arguments specify the block of memory to manage.
  16281. **
  16282. ** This routine is only called by sqlite3_config(), and therefore
  16283. ** is not required to be threadsafe (it is not).
  16284. */
  16285. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16286. static const sqlite3_mem_methods mempoolMethods = {
  16287. memsys3Malloc,
  16288. memsys3Free,
  16289. memsys3Realloc,
  16290. memsys3Size,
  16291. memsys3Roundup,
  16292. memsys3Init,
  16293. memsys3Shutdown,
  16294. 0
  16295. };
  16296. return &mempoolMethods;
  16297. }
  16298. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16299. /************** End of mem3.c ************************************************/
  16300. /************** Begin file mem5.c ********************************************/
  16301. /*
  16302. ** 2007 October 14
  16303. **
  16304. ** The author disclaims copyright to this source code. In place of
  16305. ** a legal notice, here is a blessing:
  16306. **
  16307. ** May you do good and not evil.
  16308. ** May you find forgiveness for yourself and forgive others.
  16309. ** May you share freely, never taking more than you give.
  16310. **
  16311. *************************************************************************
  16312. ** This file contains the C functions that implement a memory
  16313. ** allocation subsystem for use by SQLite.
  16314. **
  16315. ** This version of the memory allocation subsystem omits all
  16316. ** use of malloc(). The application gives SQLite a block of memory
  16317. ** before calling sqlite3_initialize() from which allocations
  16318. ** are made and returned by the xMalloc() and xRealloc()
  16319. ** implementations. Once sqlite3_initialize() has been called,
  16320. ** the amount of memory available to SQLite is fixed and cannot
  16321. ** be changed.
  16322. **
  16323. ** This version of the memory allocation subsystem is included
  16324. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16325. **
  16326. ** This memory allocator uses the following algorithm:
  16327. **
  16328. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16329. **
  16330. ** 2. If two adjacent free blocks are the halves of a larger block,
  16331. ** then the two blocks are coalesed into the single larger block.
  16332. **
  16333. ** 3. New memory is allocated from the first available free block.
  16334. **
  16335. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16336. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16337. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16338. **
  16339. ** Let n be the size of the largest allocation divided by the minimum
  16340. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16341. ** be the maximum amount of memory ever outstanding at one time. Let
  16342. ** N be the total amount of memory available for allocation. Robson
  16343. ** proved that this memory allocator will never breakdown due to
  16344. ** fragmentation as long as the following constraint holds:
  16345. **
  16346. ** N >= M*(1 + log2(n)/2) - n + 1
  16347. **
  16348. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16349. ** that an application can, at any time, verify this constraint.
  16350. */
  16351. /*
  16352. ** This version of the memory allocator is used only when
  16353. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16354. */
  16355. #ifdef SQLITE_ENABLE_MEMSYS5
  16356. /*
  16357. ** A minimum allocation is an instance of the following structure.
  16358. ** Larger allocations are an array of these structures where the
  16359. ** size of the array is a power of 2.
  16360. **
  16361. ** The size of this object must be a power of two. That fact is
  16362. ** verified in memsys5Init().
  16363. */
  16364. typedef struct Mem5Link Mem5Link;
  16365. struct Mem5Link {
  16366. int next; /* Index of next free chunk */
  16367. int prev; /* Index of previous free chunk */
  16368. };
  16369. /*
  16370. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16371. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16372. ** it is not actually possible to reach this limit.
  16373. */
  16374. #define LOGMAX 30
  16375. /*
  16376. ** Masks used for mem5.aCtrl[] elements.
  16377. */
  16378. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16379. #define CTRL_FREE 0x20 /* True if not checked out */
  16380. /*
  16381. ** All of the static variables used by this module are collected
  16382. ** into a single structure named "mem5". This is to keep the
  16383. ** static variables organized and to reduce namespace pollution
  16384. ** when this module is combined with other in the amalgamation.
  16385. */
  16386. static SQLITE_WSD struct Mem5Global {
  16387. /*
  16388. ** Memory available for allocation
  16389. */
  16390. int szAtom; /* Smallest possible allocation in bytes */
  16391. int nBlock; /* Number of szAtom sized blocks in zPool */
  16392. u8 *zPool; /* Memory available to be allocated */
  16393. /*
  16394. ** Mutex to control access to the memory allocation subsystem.
  16395. */
  16396. sqlite3_mutex *mutex;
  16397. /*
  16398. ** Performance statistics
  16399. */
  16400. u64 nAlloc; /* Total number of calls to malloc */
  16401. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16402. u64 totalExcess; /* Total internal fragmentation */
  16403. u32 currentOut; /* Current checkout, including internal fragmentation */
  16404. u32 currentCount; /* Current number of distinct checkouts */
  16405. u32 maxOut; /* Maximum instantaneous currentOut */
  16406. u32 maxCount; /* Maximum instantaneous currentCount */
  16407. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16408. /*
  16409. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16410. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16411. ** and so forth.
  16412. */
  16413. int aiFreelist[LOGMAX+1];
  16414. /*
  16415. ** Space for tracking which blocks are checked out and the size
  16416. ** of each block. One byte per block.
  16417. */
  16418. u8 *aCtrl;
  16419. } mem5;
  16420. /*
  16421. ** Access the static variable through a macro for SQLITE_OMIT_WSD
  16422. */
  16423. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16424. /*
  16425. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16426. ** structures, return a pointer to the idx-th such lik.
  16427. */
  16428. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16429. /*
  16430. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16431. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16432. */
  16433. static void memsys5Unlink(int i, int iLogsize){
  16434. int next, prev;
  16435. assert( i>=0 && i<mem5.nBlock );
  16436. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16437. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16438. next = MEM5LINK(i)->next;
  16439. prev = MEM5LINK(i)->prev;
  16440. if( prev<0 ){
  16441. mem5.aiFreelist[iLogsize] = next;
  16442. }else{
  16443. MEM5LINK(prev)->next = next;
  16444. }
  16445. if( next>=0 ){
  16446. MEM5LINK(next)->prev = prev;
  16447. }
  16448. }
  16449. /*
  16450. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16451. ** free list.
  16452. */
  16453. static void memsys5Link(int i, int iLogsize){
  16454. int x;
  16455. assert( sqlite3_mutex_held(mem5.mutex) );
  16456. assert( i>=0 && i<mem5.nBlock );
  16457. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16458. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16459. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16460. MEM5LINK(i)->prev = -1;
  16461. if( x>=0 ){
  16462. assert( x<mem5.nBlock );
  16463. MEM5LINK(x)->prev = i;
  16464. }
  16465. mem5.aiFreelist[iLogsize] = i;
  16466. }
  16467. /*
  16468. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16469. ** will already be held (obtained by code in malloc.c) if
  16470. ** sqlite3GlobalConfig.bMemStat is true.
  16471. */
  16472. static void memsys5Enter(void){
  16473. sqlite3_mutex_enter(mem5.mutex);
  16474. }
  16475. static void memsys5Leave(void){
  16476. sqlite3_mutex_leave(mem5.mutex);
  16477. }
  16478. /*
  16479. ** Return the size of an outstanding allocation, in bytes. The
  16480. ** size returned omits the 8-byte header overhead. This only
  16481. ** works for chunks that are currently checked out.
  16482. */
  16483. static int memsys5Size(void *p){
  16484. int iSize = 0;
  16485. if( p ){
  16486. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16487. assert( i>=0 && i<mem5.nBlock );
  16488. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16489. }
  16490. return iSize;
  16491. }
  16492. /*
  16493. ** Find the first entry on the freelist iLogsize. Unlink that
  16494. ** entry and return its index.
  16495. */
  16496. static int memsys5UnlinkFirst(int iLogsize){
  16497. int i;
  16498. int iFirst;
  16499. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16500. i = iFirst = mem5.aiFreelist[iLogsize];
  16501. assert( iFirst>=0 );
  16502. while( i>0 ){
  16503. if( i<iFirst ) iFirst = i;
  16504. i = MEM5LINK(i)->next;
  16505. }
  16506. memsys5Unlink(iFirst, iLogsize);
  16507. return iFirst;
  16508. }
  16509. /*
  16510. ** Return a block of memory of at least nBytes in size.
  16511. ** Return NULL if unable. Return NULL if nBytes==0.
  16512. **
  16513. ** The caller guarantees that nByte positive.
  16514. **
  16515. ** The caller has obtained a mutex prior to invoking this
  16516. ** routine so there is never any chance that two or more
  16517. ** threads can be in this routine at the same time.
  16518. */
  16519. static void *memsys5MallocUnsafe(int nByte){
  16520. int i; /* Index of a mem5.aPool[] slot */
  16521. int iBin; /* Index into mem5.aiFreelist[] */
  16522. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16523. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16524. /* nByte must be a positive */
  16525. assert( nByte>0 );
  16526. /* Keep track of the maximum allocation request. Even unfulfilled
  16527. ** requests are counted */
  16528. if( (u32)nByte>mem5.maxRequest ){
  16529. mem5.maxRequest = nByte;
  16530. }
  16531. /* Abort if the requested allocation size is larger than the largest
  16532. ** power of two that we can represent using 32-bit signed integers.
  16533. */
  16534. if( nByte > 0x40000000 ){
  16535. return 0;
  16536. }
  16537. /* Round nByte up to the next valid power of two */
  16538. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16539. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16540. ** block. If not, then split a block of the next larger power of
  16541. ** two in order to create a new free block of size iLogsize.
  16542. */
  16543. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16544. if( iBin>LOGMAX ){
  16545. testcase( sqlite3GlobalConfig.xLog!=0 );
  16546. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16547. return 0;
  16548. }
  16549. i = memsys5UnlinkFirst(iBin);
  16550. while( iBin>iLogsize ){
  16551. int newSize;
  16552. iBin--;
  16553. newSize = 1 << iBin;
  16554. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16555. memsys5Link(i+newSize, iBin);
  16556. }
  16557. mem5.aCtrl[i] = iLogsize;
  16558. /* Update allocator performance statistics. */
  16559. mem5.nAlloc++;
  16560. mem5.totalAlloc += iFullSz;
  16561. mem5.totalExcess += iFullSz - nByte;
  16562. mem5.currentCount++;
  16563. mem5.currentOut += iFullSz;
  16564. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16565. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16566. /* Return a pointer to the allocated memory. */
  16567. return (void*)&mem5.zPool[i*mem5.szAtom];
  16568. }
  16569. /*
  16570. ** Free an outstanding memory allocation.
  16571. */
  16572. static void memsys5FreeUnsafe(void *pOld){
  16573. u32 size, iLogsize;
  16574. int iBlock;
  16575. /* Set iBlock to the index of the block pointed to by pOld in
  16576. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16577. */
  16578. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16579. /* Check that the pointer pOld points to a valid, non-free block. */
  16580. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16581. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16582. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16583. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16584. size = 1<<iLogsize;
  16585. assert( iBlock+size-1<(u32)mem5.nBlock );
  16586. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16587. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16588. assert( mem5.currentCount>0 );
  16589. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16590. mem5.currentCount--;
  16591. mem5.currentOut -= size*mem5.szAtom;
  16592. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16593. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16594. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16595. while( ALWAYS(iLogsize<LOGMAX) ){
  16596. int iBuddy;
  16597. if( (iBlock>>iLogsize) & 1 ){
  16598. iBuddy = iBlock - size;
  16599. }else{
  16600. iBuddy = iBlock + size;
  16601. }
  16602. assert( iBuddy>=0 );
  16603. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16604. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16605. memsys5Unlink(iBuddy, iLogsize);
  16606. iLogsize++;
  16607. if( iBuddy<iBlock ){
  16608. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16609. mem5.aCtrl[iBlock] = 0;
  16610. iBlock = iBuddy;
  16611. }else{
  16612. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16613. mem5.aCtrl[iBuddy] = 0;
  16614. }
  16615. size *= 2;
  16616. }
  16617. memsys5Link(iBlock, iLogsize);
  16618. }
  16619. /*
  16620. ** Allocate nBytes of memory
  16621. */
  16622. static void *memsys5Malloc(int nBytes){
  16623. sqlite3_int64 *p = 0;
  16624. if( nBytes>0 ){
  16625. memsys5Enter();
  16626. p = memsys5MallocUnsafe(nBytes);
  16627. memsys5Leave();
  16628. }
  16629. return (void*)p;
  16630. }
  16631. /*
  16632. ** Free memory.
  16633. **
  16634. ** The outer layer memory allocator prevents this routine from
  16635. ** being called with pPrior==0.
  16636. */
  16637. static void memsys5Free(void *pPrior){
  16638. assert( pPrior!=0 );
  16639. memsys5Enter();
  16640. memsys5FreeUnsafe(pPrior);
  16641. memsys5Leave();
  16642. }
  16643. /*
  16644. ** Change the size of an existing memory allocation.
  16645. **
  16646. ** The outer layer memory allocator prevents this routine from
  16647. ** being called with pPrior==0.
  16648. **
  16649. ** nBytes is always a value obtained from a prior call to
  16650. ** memsys5Round(). Hence nBytes is always a non-negative power
  16651. ** of two. If nBytes==0 that means that an oversize allocation
  16652. ** (an allocation larger than 0x40000000) was requested and this
  16653. ** routine should return 0 without freeing pPrior.
  16654. */
  16655. static void *memsys5Realloc(void *pPrior, int nBytes){
  16656. int nOld;
  16657. void *p;
  16658. assert( pPrior!=0 );
  16659. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16660. assert( nBytes>=0 );
  16661. if( nBytes==0 ){
  16662. return 0;
  16663. }
  16664. nOld = memsys5Size(pPrior);
  16665. if( nBytes<=nOld ){
  16666. return pPrior;
  16667. }
  16668. memsys5Enter();
  16669. p = memsys5MallocUnsafe(nBytes);
  16670. if( p ){
  16671. memcpy(p, pPrior, nOld);
  16672. memsys5FreeUnsafe(pPrior);
  16673. }
  16674. memsys5Leave();
  16675. return p;
  16676. }
  16677. /*
  16678. ** Round up a request size to the next valid allocation size. If
  16679. ** the allocation is too large to be handled by this allocation system,
  16680. ** return 0.
  16681. **
  16682. ** All allocations must be a power of two and must be expressed by a
  16683. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16684. ** or 1073741824 bytes.
  16685. */
  16686. static int memsys5Roundup(int n){
  16687. int iFullSz;
  16688. if( n > 0x40000000 ) return 0;
  16689. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16690. return iFullSz;
  16691. }
  16692. /*
  16693. ** Return the ceiling of the logarithm base 2 of iValue.
  16694. **
  16695. ** Examples: memsys5Log(1) -> 0
  16696. ** memsys5Log(2) -> 1
  16697. ** memsys5Log(4) -> 2
  16698. ** memsys5Log(5) -> 3
  16699. ** memsys5Log(8) -> 3
  16700. ** memsys5Log(9) -> 4
  16701. */
  16702. static int memsys5Log(int iValue){
  16703. int iLog;
  16704. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16705. return iLog;
  16706. }
  16707. /*
  16708. ** Initialize the memory allocator.
  16709. **
  16710. ** This routine is not threadsafe. The caller must be holding a mutex
  16711. ** to prevent multiple threads from entering at the same time.
  16712. */
  16713. static int memsys5Init(void *NotUsed){
  16714. int ii; /* Loop counter */
  16715. int nByte; /* Number of bytes of memory available to this allocator */
  16716. u8 *zByte; /* Memory usable by this allocator */
  16717. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16718. int iOffset; /* An offset into mem5.aCtrl[] */
  16719. UNUSED_PARAMETER(NotUsed);
  16720. /* For the purposes of this routine, disable the mutex */
  16721. mem5.mutex = 0;
  16722. /* The size of a Mem5Link object must be a power of two. Verify that
  16723. ** this is case.
  16724. */
  16725. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16726. nByte = sqlite3GlobalConfig.nHeap;
  16727. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16728. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16729. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16730. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16731. mem5.szAtom = (1<<nMinLog);
  16732. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16733. mem5.szAtom = mem5.szAtom << 1;
  16734. }
  16735. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16736. mem5.zPool = zByte;
  16737. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16738. for(ii=0; ii<=LOGMAX; ii++){
  16739. mem5.aiFreelist[ii] = -1;
  16740. }
  16741. iOffset = 0;
  16742. for(ii=LOGMAX; ii>=0; ii--){
  16743. int nAlloc = (1<<ii);
  16744. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16745. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16746. memsys5Link(iOffset, ii);
  16747. iOffset += nAlloc;
  16748. }
  16749. assert((iOffset+nAlloc)>mem5.nBlock);
  16750. }
  16751. /* If a mutex is required for normal operation, allocate one */
  16752. if( sqlite3GlobalConfig.bMemstat==0 ){
  16753. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16754. }
  16755. return SQLITE_OK;
  16756. }
  16757. /*
  16758. ** Deinitialize this module.
  16759. */
  16760. static void memsys5Shutdown(void *NotUsed){
  16761. UNUSED_PARAMETER(NotUsed);
  16762. mem5.mutex = 0;
  16763. return;
  16764. }
  16765. #ifdef SQLITE_TEST
  16766. /*
  16767. ** Open the file indicated and write a log of all unfreed memory
  16768. ** allocations into that log.
  16769. */
  16770. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16771. FILE *out;
  16772. int i, j, n;
  16773. int nMinLog;
  16774. if( zFilename==0 || zFilename[0]==0 ){
  16775. out = stdout;
  16776. }else{
  16777. out = fopen(zFilename, "w");
  16778. if( out==0 ){
  16779. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16780. zFilename);
  16781. return;
  16782. }
  16783. }
  16784. memsys5Enter();
  16785. nMinLog = memsys5Log(mem5.szAtom);
  16786. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16787. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16788. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16789. }
  16790. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16791. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16792. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16793. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16794. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16795. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16796. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16797. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16798. memsys5Leave();
  16799. if( out==stdout ){
  16800. fflush(stdout);
  16801. }else{
  16802. fclose(out);
  16803. }
  16804. }
  16805. #endif
  16806. /*
  16807. ** This routine is the only routine in this file with external
  16808. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16809. ** struct populated with the memsys5 methods.
  16810. */
  16811. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16812. static const sqlite3_mem_methods memsys5Methods = {
  16813. memsys5Malloc,
  16814. memsys5Free,
  16815. memsys5Realloc,
  16816. memsys5Size,
  16817. memsys5Roundup,
  16818. memsys5Init,
  16819. memsys5Shutdown,
  16820. 0
  16821. };
  16822. return &memsys5Methods;
  16823. }
  16824. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16825. /************** End of mem5.c ************************************************/
  16826. /************** Begin file mutex.c *******************************************/
  16827. /*
  16828. ** 2007 August 14
  16829. **
  16830. ** The author disclaims copyright to this source code. In place of
  16831. ** a legal notice, here is a blessing:
  16832. **
  16833. ** May you do good and not evil.
  16834. ** May you find forgiveness for yourself and forgive others.
  16835. ** May you share freely, never taking more than you give.
  16836. **
  16837. *************************************************************************
  16838. ** This file contains the C functions that implement mutexes.
  16839. **
  16840. ** This file contains code that is common across all mutex implementations.
  16841. */
  16842. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16843. /*
  16844. ** For debugging purposes, record when the mutex subsystem is initialized
  16845. ** and uninitialized so that we can assert() if there is an attempt to
  16846. ** allocate a mutex while the system is uninitialized.
  16847. */
  16848. static SQLITE_WSD int mutexIsInit = 0;
  16849. #endif /* SQLITE_DEBUG */
  16850. #ifndef SQLITE_MUTEX_OMIT
  16851. /*
  16852. ** Initialize the mutex system.
  16853. */
  16854. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16855. int rc = SQLITE_OK;
  16856. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16857. /* If the xMutexAlloc method has not been set, then the user did not
  16858. ** install a mutex implementation via sqlite3_config() prior to
  16859. ** sqlite3_initialize() being called. This block copies pointers to
  16860. ** the default implementation into the sqlite3GlobalConfig structure.
  16861. */
  16862. sqlite3_mutex_methods const *pFrom;
  16863. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16864. if( sqlite3GlobalConfig.bCoreMutex ){
  16865. pFrom = sqlite3DefaultMutex();
  16866. }else{
  16867. pFrom = sqlite3NoopMutex();
  16868. }
  16869. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16870. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16871. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16872. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16873. }
  16874. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16875. #ifdef SQLITE_DEBUG
  16876. GLOBAL(int, mutexIsInit) = 1;
  16877. #endif
  16878. return rc;
  16879. }
  16880. /*
  16881. ** Shutdown the mutex system. This call frees resources allocated by
  16882. ** sqlite3MutexInit().
  16883. */
  16884. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16885. int rc = SQLITE_OK;
  16886. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16887. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16888. }
  16889. #ifdef SQLITE_DEBUG
  16890. GLOBAL(int, mutexIsInit) = 0;
  16891. #endif
  16892. return rc;
  16893. }
  16894. /*
  16895. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16896. */
  16897. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16898. #ifndef SQLITE_OMIT_AUTOINIT
  16899. if( sqlite3_initialize() ) return 0;
  16900. #endif
  16901. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16902. }
  16903. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16904. if( !sqlite3GlobalConfig.bCoreMutex ){
  16905. return 0;
  16906. }
  16907. assert( GLOBAL(int, mutexIsInit) );
  16908. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16909. }
  16910. /*
  16911. ** Free a dynamic mutex.
  16912. */
  16913. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16914. if( p ){
  16915. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16916. }
  16917. }
  16918. /*
  16919. ** Obtain the mutex p. If some other thread already has the mutex, block
  16920. ** until it can be obtained.
  16921. */
  16922. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16923. if( p ){
  16924. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16925. }
  16926. }
  16927. /*
  16928. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  16929. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  16930. */
  16931. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  16932. int rc = SQLITE_OK;
  16933. if( p ){
  16934. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  16935. }
  16936. return rc;
  16937. }
  16938. /*
  16939. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  16940. ** entered by the same thread. The behavior is undefined if the mutex
  16941. ** is not currently entered. If a NULL pointer is passed as an argument
  16942. ** this function is a no-op.
  16943. */
  16944. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  16945. if( p ){
  16946. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  16947. }
  16948. }
  16949. #ifndef NDEBUG
  16950. /*
  16951. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16952. ** intended for use inside assert() statements.
  16953. */
  16954. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  16955. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  16956. }
  16957. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  16958. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  16959. }
  16960. #endif
  16961. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  16962. /************** End of mutex.c ***********************************************/
  16963. /************** Begin file mutex_noop.c **************************************/
  16964. /*
  16965. ** 2008 October 07
  16966. **
  16967. ** The author disclaims copyright to this source code. In place of
  16968. ** a legal notice, here is a blessing:
  16969. **
  16970. ** May you do good and not evil.
  16971. ** May you find forgiveness for yourself and forgive others.
  16972. ** May you share freely, never taking more than you give.
  16973. **
  16974. *************************************************************************
  16975. ** This file contains the C functions that implement mutexes.
  16976. **
  16977. ** This implementation in this file does not provide any mutual
  16978. ** exclusion and is thus suitable for use only in applications
  16979. ** that use SQLite in a single thread. The routines defined
  16980. ** here are place-holders. Applications can substitute working
  16981. ** mutex routines at start-time using the
  16982. **
  16983. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  16984. **
  16985. ** interface.
  16986. **
  16987. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  16988. ** that does error checking on mutexes to make sure they are being
  16989. ** called correctly.
  16990. */
  16991. #ifndef SQLITE_MUTEX_OMIT
  16992. #ifndef SQLITE_DEBUG
  16993. /*
  16994. ** Stub routines for all mutex methods.
  16995. **
  16996. ** This routines provide no mutual exclusion or error checking.
  16997. */
  16998. static int noopMutexInit(void){ return SQLITE_OK; }
  16999. static int noopMutexEnd(void){ return SQLITE_OK; }
  17000. static sqlite3_mutex *noopMutexAlloc(int id){
  17001. UNUSED_PARAMETER(id);
  17002. return (sqlite3_mutex*)8;
  17003. }
  17004. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17005. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17006. static int noopMutexTry(sqlite3_mutex *p){
  17007. UNUSED_PARAMETER(p);
  17008. return SQLITE_OK;
  17009. }
  17010. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17011. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17012. static const sqlite3_mutex_methods sMutex = {
  17013. noopMutexInit,
  17014. noopMutexEnd,
  17015. noopMutexAlloc,
  17016. noopMutexFree,
  17017. noopMutexEnter,
  17018. noopMutexTry,
  17019. noopMutexLeave,
  17020. 0,
  17021. 0,
  17022. };
  17023. return &sMutex;
  17024. }
  17025. #endif /* !SQLITE_DEBUG */
  17026. #ifdef SQLITE_DEBUG
  17027. /*
  17028. ** In this implementation, error checking is provided for testing
  17029. ** and debugging purposes. The mutexes still do not provide any
  17030. ** mutual exclusion.
  17031. */
  17032. /*
  17033. ** The mutex object
  17034. */
  17035. typedef struct sqlite3_debug_mutex {
  17036. int id; /* The mutex type */
  17037. int cnt; /* Number of entries without a matching leave */
  17038. } sqlite3_debug_mutex;
  17039. /*
  17040. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17041. ** intended for use inside assert() statements.
  17042. */
  17043. static int debugMutexHeld(sqlite3_mutex *pX){
  17044. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17045. return p==0 || p->cnt>0;
  17046. }
  17047. static int debugMutexNotheld(sqlite3_mutex *pX){
  17048. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17049. return p==0 || p->cnt==0;
  17050. }
  17051. /*
  17052. ** Initialize and deinitialize the mutex subsystem.
  17053. */
  17054. static int debugMutexInit(void){ return SQLITE_OK; }
  17055. static int debugMutexEnd(void){ return SQLITE_OK; }
  17056. /*
  17057. ** The sqlite3_mutex_alloc() routine allocates a new
  17058. ** mutex and returns a pointer to it. If it returns NULL
  17059. ** that means that a mutex could not be allocated.
  17060. */
  17061. static sqlite3_mutex *debugMutexAlloc(int id){
  17062. static sqlite3_debug_mutex aStatic[6];
  17063. sqlite3_debug_mutex *pNew = 0;
  17064. switch( id ){
  17065. case SQLITE_MUTEX_FAST:
  17066. case SQLITE_MUTEX_RECURSIVE: {
  17067. pNew = sqlite3Malloc(sizeof(*pNew));
  17068. if( pNew ){
  17069. pNew->id = id;
  17070. pNew->cnt = 0;
  17071. }
  17072. break;
  17073. }
  17074. default: {
  17075. assert( id-2 >= 0 );
  17076. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17077. pNew = &aStatic[id-2];
  17078. pNew->id = id;
  17079. break;
  17080. }
  17081. }
  17082. return (sqlite3_mutex*)pNew;
  17083. }
  17084. /*
  17085. ** This routine deallocates a previously allocated mutex.
  17086. */
  17087. static void debugMutexFree(sqlite3_mutex *pX){
  17088. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17089. assert( p->cnt==0 );
  17090. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17091. sqlite3_free(p);
  17092. }
  17093. /*
  17094. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17095. ** to enter a mutex. If another thread is already within the mutex,
  17096. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17097. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17098. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17099. ** be entered multiple times by the same thread. In such cases the,
  17100. ** mutex must be exited an equal number of times before another thread
  17101. ** can enter. If the same thread tries to enter any other kind of mutex
  17102. ** more than once, the behavior is undefined.
  17103. */
  17104. static void debugMutexEnter(sqlite3_mutex *pX){
  17105. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17106. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17107. p->cnt++;
  17108. }
  17109. static int debugMutexTry(sqlite3_mutex *pX){
  17110. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17111. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17112. p->cnt++;
  17113. return SQLITE_OK;
  17114. }
  17115. /*
  17116. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17117. ** previously entered by the same thread. The behavior
  17118. ** is undefined if the mutex is not currently entered or
  17119. ** is not currently allocated. SQLite will never do either.
  17120. */
  17121. static void debugMutexLeave(sqlite3_mutex *pX){
  17122. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17123. assert( debugMutexHeld(pX) );
  17124. p->cnt--;
  17125. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17126. }
  17127. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17128. static const sqlite3_mutex_methods sMutex = {
  17129. debugMutexInit,
  17130. debugMutexEnd,
  17131. debugMutexAlloc,
  17132. debugMutexFree,
  17133. debugMutexEnter,
  17134. debugMutexTry,
  17135. debugMutexLeave,
  17136. debugMutexHeld,
  17137. debugMutexNotheld
  17138. };
  17139. return &sMutex;
  17140. }
  17141. #endif /* SQLITE_DEBUG */
  17142. /*
  17143. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17144. ** is used regardless of the run-time threadsafety setting.
  17145. */
  17146. #ifdef SQLITE_MUTEX_NOOP
  17147. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17148. return sqlite3NoopMutex();
  17149. }
  17150. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17151. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17152. /************** End of mutex_noop.c ******************************************/
  17153. /************** Begin file mutex_unix.c **************************************/
  17154. /*
  17155. ** 2007 August 28
  17156. **
  17157. ** The author disclaims copyright to this source code. In place of
  17158. ** a legal notice, here is a blessing:
  17159. **
  17160. ** May you do good and not evil.
  17161. ** May you find forgiveness for yourself and forgive others.
  17162. ** May you share freely, never taking more than you give.
  17163. **
  17164. *************************************************************************
  17165. ** This file contains the C functions that implement mutexes for pthreads
  17166. */
  17167. /*
  17168. ** The code in this file is only used if we are compiling threadsafe
  17169. ** under unix with pthreads.
  17170. **
  17171. ** Note that this implementation requires a version of pthreads that
  17172. ** supports recursive mutexes.
  17173. */
  17174. #ifdef SQLITE_MUTEX_PTHREADS
  17175. #include <pthread.h>
  17176. /*
  17177. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17178. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17179. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17180. */
  17181. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17182. # define SQLITE_MUTEX_NREF 1
  17183. #else
  17184. # define SQLITE_MUTEX_NREF 0
  17185. #endif
  17186. /*
  17187. ** Each recursive mutex is an instance of the following structure.
  17188. */
  17189. struct sqlite3_mutex {
  17190. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17191. #if SQLITE_MUTEX_NREF
  17192. int id; /* Mutex type */
  17193. volatile int nRef; /* Number of entrances */
  17194. volatile pthread_t owner; /* Thread that is within this mutex */
  17195. int trace; /* True to trace changes */
  17196. #endif
  17197. };
  17198. #if SQLITE_MUTEX_NREF
  17199. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17200. #else
  17201. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  17202. #endif
  17203. /*
  17204. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17205. ** intended for use only inside assert() statements. On some platforms,
  17206. ** there might be race conditions that can cause these routines to
  17207. ** deliver incorrect results. In particular, if pthread_equal() is
  17208. ** not an atomic operation, then these routines might delivery
  17209. ** incorrect results. On most platforms, pthread_equal() is a
  17210. ** comparison of two integers and is therefore atomic. But we are
  17211. ** told that HPUX is not such a platform. If so, then these routines
  17212. ** will not always work correctly on HPUX.
  17213. **
  17214. ** On those platforms where pthread_equal() is not atomic, SQLite
  17215. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17216. ** make sure no assert() statements are evaluated and hence these
  17217. ** routines are never called.
  17218. */
  17219. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17220. static int pthreadMutexHeld(sqlite3_mutex *p){
  17221. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  17222. }
  17223. static int pthreadMutexNotheld(sqlite3_mutex *p){
  17224. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  17225. }
  17226. #endif
  17227. /*
  17228. ** Initialize and deinitialize the mutex subsystem.
  17229. */
  17230. static int pthreadMutexInit(void){ return SQLITE_OK; }
  17231. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  17232. /*
  17233. ** The sqlite3_mutex_alloc() routine allocates a new
  17234. ** mutex and returns a pointer to it. If it returns NULL
  17235. ** that means that a mutex could not be allocated. SQLite
  17236. ** will unwind its stack and return an error. The argument
  17237. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17238. **
  17239. ** <ul>
  17240. ** <li> SQLITE_MUTEX_FAST
  17241. ** <li> SQLITE_MUTEX_RECURSIVE
  17242. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17243. ** <li> SQLITE_MUTEX_STATIC_MEM
  17244. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17245. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17246. ** <li> SQLITE_MUTEX_STATIC_LRU
  17247. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17248. ** </ul>
  17249. **
  17250. ** The first two constants cause sqlite3_mutex_alloc() to create
  17251. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17252. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17253. ** The mutex implementation does not need to make a distinction
  17254. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17255. ** not want to. But SQLite will only request a recursive mutex in
  17256. ** cases where it really needs one. If a faster non-recursive mutex
  17257. ** implementation is available on the host platform, the mutex subsystem
  17258. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17259. **
  17260. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17261. ** a pointer to a static preexisting mutex. Six static mutexes are
  17262. ** used by the current version of SQLite. Future versions of SQLite
  17263. ** may add additional static mutexes. Static mutexes are for internal
  17264. ** use by SQLite only. Applications that use SQLite mutexes should
  17265. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17266. ** SQLITE_MUTEX_RECURSIVE.
  17267. **
  17268. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17269. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17270. ** returns a different mutex on every call. But for the static
  17271. ** mutex types, the same mutex is returned on every call that has
  17272. ** the same type number.
  17273. */
  17274. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17275. static sqlite3_mutex staticMutexes[] = {
  17276. SQLITE3_MUTEX_INITIALIZER,
  17277. SQLITE3_MUTEX_INITIALIZER,
  17278. SQLITE3_MUTEX_INITIALIZER,
  17279. SQLITE3_MUTEX_INITIALIZER,
  17280. SQLITE3_MUTEX_INITIALIZER,
  17281. SQLITE3_MUTEX_INITIALIZER
  17282. };
  17283. sqlite3_mutex *p;
  17284. switch( iType ){
  17285. case SQLITE_MUTEX_RECURSIVE: {
  17286. p = sqlite3MallocZero( sizeof(*p) );
  17287. if( p ){
  17288. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17289. /* If recursive mutexes are not available, we will have to
  17290. ** build our own. See below. */
  17291. pthread_mutex_init(&p->mutex, 0);
  17292. #else
  17293. /* Use a recursive mutex if it is available */
  17294. pthread_mutexattr_t recursiveAttr;
  17295. pthread_mutexattr_init(&recursiveAttr);
  17296. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17297. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17298. pthread_mutexattr_destroy(&recursiveAttr);
  17299. #endif
  17300. #if SQLITE_MUTEX_NREF
  17301. p->id = iType;
  17302. #endif
  17303. }
  17304. break;
  17305. }
  17306. case SQLITE_MUTEX_FAST: {
  17307. p = sqlite3MallocZero( sizeof(*p) );
  17308. if( p ){
  17309. #if SQLITE_MUTEX_NREF
  17310. p->id = iType;
  17311. #endif
  17312. pthread_mutex_init(&p->mutex, 0);
  17313. }
  17314. break;
  17315. }
  17316. default: {
  17317. assert( iType-2 >= 0 );
  17318. assert( iType-2 < ArraySize(staticMutexes) );
  17319. p = &staticMutexes[iType-2];
  17320. #if SQLITE_MUTEX_NREF
  17321. p->id = iType;
  17322. #endif
  17323. break;
  17324. }
  17325. }
  17326. return p;
  17327. }
  17328. /*
  17329. ** This routine deallocates a previously
  17330. ** allocated mutex. SQLite is careful to deallocate every
  17331. ** mutex that it allocates.
  17332. */
  17333. static void pthreadMutexFree(sqlite3_mutex *p){
  17334. assert( p->nRef==0 );
  17335. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17336. pthread_mutex_destroy(&p->mutex);
  17337. sqlite3_free(p);
  17338. }
  17339. /*
  17340. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17341. ** to enter a mutex. If another thread is already within the mutex,
  17342. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17343. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17344. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17345. ** be entered multiple times by the same thread. In such cases the,
  17346. ** mutex must be exited an equal number of times before another thread
  17347. ** can enter. If the same thread tries to enter any other kind of mutex
  17348. ** more than once, the behavior is undefined.
  17349. */
  17350. static void pthreadMutexEnter(sqlite3_mutex *p){
  17351. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17352. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17353. /* If recursive mutexes are not available, then we have to grow
  17354. ** our own. This implementation assumes that pthread_equal()
  17355. ** is atomic - that it cannot be deceived into thinking self
  17356. ** and p->owner are equal if p->owner changes between two values
  17357. ** that are not equal to self while the comparison is taking place.
  17358. ** This implementation also assumes a coherent cache - that
  17359. ** separate processes cannot read different values from the same
  17360. ** address at the same time. If either of these two conditions
  17361. ** are not met, then the mutexes will fail and problems will result.
  17362. */
  17363. {
  17364. pthread_t self = pthread_self();
  17365. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17366. p->nRef++;
  17367. }else{
  17368. pthread_mutex_lock(&p->mutex);
  17369. assert( p->nRef==0 );
  17370. p->owner = self;
  17371. p->nRef = 1;
  17372. }
  17373. }
  17374. #else
  17375. /* Use the built-in recursive mutexes if they are available.
  17376. */
  17377. pthread_mutex_lock(&p->mutex);
  17378. #if SQLITE_MUTEX_NREF
  17379. assert( p->nRef>0 || p->owner==0 );
  17380. p->owner = pthread_self();
  17381. p->nRef++;
  17382. #endif
  17383. #endif
  17384. #ifdef SQLITE_DEBUG
  17385. if( p->trace ){
  17386. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17387. }
  17388. #endif
  17389. }
  17390. static int pthreadMutexTry(sqlite3_mutex *p){
  17391. int rc;
  17392. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17393. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17394. /* If recursive mutexes are not available, then we have to grow
  17395. ** our own. This implementation assumes that pthread_equal()
  17396. ** is atomic - that it cannot be deceived into thinking self
  17397. ** and p->owner are equal if p->owner changes between two values
  17398. ** that are not equal to self while the comparison is taking place.
  17399. ** This implementation also assumes a coherent cache - that
  17400. ** separate processes cannot read different values from the same
  17401. ** address at the same time. If either of these two conditions
  17402. ** are not met, then the mutexes will fail and problems will result.
  17403. */
  17404. {
  17405. pthread_t self = pthread_self();
  17406. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17407. p->nRef++;
  17408. rc = SQLITE_OK;
  17409. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17410. assert( p->nRef==0 );
  17411. p->owner = self;
  17412. p->nRef = 1;
  17413. rc = SQLITE_OK;
  17414. }else{
  17415. rc = SQLITE_BUSY;
  17416. }
  17417. }
  17418. #else
  17419. /* Use the built-in recursive mutexes if they are available.
  17420. */
  17421. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17422. #if SQLITE_MUTEX_NREF
  17423. p->owner = pthread_self();
  17424. p->nRef++;
  17425. #endif
  17426. rc = SQLITE_OK;
  17427. }else{
  17428. rc = SQLITE_BUSY;
  17429. }
  17430. #endif
  17431. #ifdef SQLITE_DEBUG
  17432. if( rc==SQLITE_OK && p->trace ){
  17433. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17434. }
  17435. #endif
  17436. return rc;
  17437. }
  17438. /*
  17439. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17440. ** previously entered by the same thread. The behavior
  17441. ** is undefined if the mutex is not currently entered or
  17442. ** is not currently allocated. SQLite will never do either.
  17443. */
  17444. static void pthreadMutexLeave(sqlite3_mutex *p){
  17445. assert( pthreadMutexHeld(p) );
  17446. #if SQLITE_MUTEX_NREF
  17447. p->nRef--;
  17448. if( p->nRef==0 ) p->owner = 0;
  17449. #endif
  17450. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17451. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17452. if( p->nRef==0 ){
  17453. pthread_mutex_unlock(&p->mutex);
  17454. }
  17455. #else
  17456. pthread_mutex_unlock(&p->mutex);
  17457. #endif
  17458. #ifdef SQLITE_DEBUG
  17459. if( p->trace ){
  17460. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17461. }
  17462. #endif
  17463. }
  17464. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17465. static const sqlite3_mutex_methods sMutex = {
  17466. pthreadMutexInit,
  17467. pthreadMutexEnd,
  17468. pthreadMutexAlloc,
  17469. pthreadMutexFree,
  17470. pthreadMutexEnter,
  17471. pthreadMutexTry,
  17472. pthreadMutexLeave,
  17473. #ifdef SQLITE_DEBUG
  17474. pthreadMutexHeld,
  17475. pthreadMutexNotheld
  17476. #else
  17477. 0,
  17478. 0
  17479. #endif
  17480. };
  17481. return &sMutex;
  17482. }
  17483. #endif /* SQLITE_MUTEX_PTHREADS */
  17484. /************** End of mutex_unix.c ******************************************/
  17485. /************** Begin file mutex_w32.c ***************************************/
  17486. /*
  17487. ** 2007 August 14
  17488. **
  17489. ** The author disclaims copyright to this source code. In place of
  17490. ** a legal notice, here is a blessing:
  17491. **
  17492. ** May you do good and not evil.
  17493. ** May you find forgiveness for yourself and forgive others.
  17494. ** May you share freely, never taking more than you give.
  17495. **
  17496. *************************************************************************
  17497. ** This file contains the C functions that implement mutexes for win32
  17498. */
  17499. /*
  17500. ** The code in this file is only used if we are compiling multithreaded
  17501. ** on a win32 system.
  17502. */
  17503. #ifdef SQLITE_MUTEX_W32
  17504. /*
  17505. ** Each recursive mutex is an instance of the following structure.
  17506. */
  17507. struct sqlite3_mutex {
  17508. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17509. int id; /* Mutex type */
  17510. #ifdef SQLITE_DEBUG
  17511. volatile int nRef; /* Number of enterances */
  17512. volatile DWORD owner; /* Thread holding this mutex */
  17513. int trace; /* True to trace changes */
  17514. #endif
  17515. };
  17516. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17517. #ifdef SQLITE_DEBUG
  17518. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17519. #else
  17520. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17521. #endif
  17522. /*
  17523. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17524. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17525. **
  17526. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17527. ** the LockFileEx() API. But we can still statically link against that
  17528. ** API as long as we don't call it win running Win95/98/ME. A call to
  17529. ** this routine is used to determine if the host is Win95/98/ME or
  17530. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17531. ** the LockFileEx() API.
  17532. **
  17533. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17534. ** which is only available if your application was compiled with
  17535. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17536. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17537. ** this out as well.
  17538. */
  17539. #if 0
  17540. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  17541. # define mutexIsNT() (1)
  17542. #else
  17543. static int mutexIsNT(void){
  17544. static int osType = 0;
  17545. if( osType==0 ){
  17546. OSVERSIONINFO sInfo;
  17547. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17548. GetVersionEx(&sInfo);
  17549. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17550. }
  17551. return osType==2;
  17552. }
  17553. #endif /* SQLITE_OS_WINCE */
  17554. #endif
  17555. #ifdef SQLITE_DEBUG
  17556. /*
  17557. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17558. ** intended for use only inside assert() statements.
  17559. */
  17560. static int winMutexHeld(sqlite3_mutex *p){
  17561. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17562. }
  17563. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17564. return p->nRef==0 || p->owner!=tid;
  17565. }
  17566. static int winMutexNotheld(sqlite3_mutex *p){
  17567. DWORD tid = GetCurrentThreadId();
  17568. return winMutexNotheld2(p, tid);
  17569. }
  17570. #endif
  17571. /*
  17572. ** Initialize and deinitialize the mutex subsystem.
  17573. */
  17574. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17575. SQLITE3_MUTEX_INITIALIZER,
  17576. SQLITE3_MUTEX_INITIALIZER,
  17577. SQLITE3_MUTEX_INITIALIZER,
  17578. SQLITE3_MUTEX_INITIALIZER,
  17579. SQLITE3_MUTEX_INITIALIZER,
  17580. SQLITE3_MUTEX_INITIALIZER
  17581. };
  17582. static int winMutex_isInit = 0;
  17583. /* As winMutexInit() and winMutexEnd() are called as part
  17584. ** of the sqlite3_initialize and sqlite3_shutdown()
  17585. ** processing, the "interlocked" magic is probably not
  17586. ** strictly necessary.
  17587. */
  17588. static long winMutex_lock = 0;
  17589. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  17590. static int winMutexInit(void){
  17591. /* The first to increment to 1 does actual initialization */
  17592. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17593. int i;
  17594. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17595. #if SQLITE_OS_WINRT
  17596. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  17597. #else
  17598. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17599. #endif
  17600. }
  17601. winMutex_isInit = 1;
  17602. }else{
  17603. /* Someone else is in the process of initing the static mutexes */
  17604. while( !winMutex_isInit ){
  17605. sqlite3_win32_sleep(1);
  17606. }
  17607. }
  17608. return SQLITE_OK;
  17609. }
  17610. static int winMutexEnd(void){
  17611. /* The first to decrement to 0 does actual shutdown
  17612. ** (which should be the last to shutdown.) */
  17613. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17614. if( winMutex_isInit==1 ){
  17615. int i;
  17616. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17617. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17618. }
  17619. winMutex_isInit = 0;
  17620. }
  17621. }
  17622. return SQLITE_OK;
  17623. }
  17624. /*
  17625. ** The sqlite3_mutex_alloc() routine allocates a new
  17626. ** mutex and returns a pointer to it. If it returns NULL
  17627. ** that means that a mutex could not be allocated. SQLite
  17628. ** will unwind its stack and return an error. The argument
  17629. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17630. **
  17631. ** <ul>
  17632. ** <li> SQLITE_MUTEX_FAST
  17633. ** <li> SQLITE_MUTEX_RECURSIVE
  17634. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17635. ** <li> SQLITE_MUTEX_STATIC_MEM
  17636. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17637. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17638. ** <li> SQLITE_MUTEX_STATIC_LRU
  17639. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17640. ** </ul>
  17641. **
  17642. ** The first two constants cause sqlite3_mutex_alloc() to create
  17643. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17644. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17645. ** The mutex implementation does not need to make a distinction
  17646. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17647. ** not want to. But SQLite will only request a recursive mutex in
  17648. ** cases where it really needs one. If a faster non-recursive mutex
  17649. ** implementation is available on the host platform, the mutex subsystem
  17650. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17651. **
  17652. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17653. ** a pointer to a static preexisting mutex. Six static mutexes are
  17654. ** used by the current version of SQLite. Future versions of SQLite
  17655. ** may add additional static mutexes. Static mutexes are for internal
  17656. ** use by SQLite only. Applications that use SQLite mutexes should
  17657. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17658. ** SQLITE_MUTEX_RECURSIVE.
  17659. **
  17660. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17661. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17662. ** returns a different mutex on every call. But for the static
  17663. ** mutex types, the same mutex is returned on every call that has
  17664. ** the same type number.
  17665. */
  17666. static sqlite3_mutex *winMutexAlloc(int iType){
  17667. sqlite3_mutex *p;
  17668. switch( iType ){
  17669. case SQLITE_MUTEX_FAST:
  17670. case SQLITE_MUTEX_RECURSIVE: {
  17671. p = sqlite3MallocZero( sizeof(*p) );
  17672. if( p ){
  17673. #ifdef SQLITE_DEBUG
  17674. p->id = iType;
  17675. #endif
  17676. #if SQLITE_OS_WINRT
  17677. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  17678. #else
  17679. InitializeCriticalSection(&p->mutex);
  17680. #endif
  17681. }
  17682. break;
  17683. }
  17684. default: {
  17685. assert( winMutex_isInit==1 );
  17686. assert( iType-2 >= 0 );
  17687. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17688. p = &winMutex_staticMutexes[iType-2];
  17689. #ifdef SQLITE_DEBUG
  17690. p->id = iType;
  17691. #endif
  17692. break;
  17693. }
  17694. }
  17695. return p;
  17696. }
  17697. /*
  17698. ** This routine deallocates a previously
  17699. ** allocated mutex. SQLite is careful to deallocate every
  17700. ** mutex that it allocates.
  17701. */
  17702. static void winMutexFree(sqlite3_mutex *p){
  17703. assert( p );
  17704. assert( p->nRef==0 && p->owner==0 );
  17705. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17706. DeleteCriticalSection(&p->mutex);
  17707. sqlite3_free(p);
  17708. }
  17709. /*
  17710. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17711. ** to enter a mutex. If another thread is already within the mutex,
  17712. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17713. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17714. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17715. ** be entered multiple times by the same thread. In such cases the,
  17716. ** mutex must be exited an equal number of times before another thread
  17717. ** can enter. If the same thread tries to enter any other kind of mutex
  17718. ** more than once, the behavior is undefined.
  17719. */
  17720. static void winMutexEnter(sqlite3_mutex *p){
  17721. #ifdef SQLITE_DEBUG
  17722. DWORD tid = GetCurrentThreadId();
  17723. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17724. #endif
  17725. EnterCriticalSection(&p->mutex);
  17726. #ifdef SQLITE_DEBUG
  17727. assert( p->nRef>0 || p->owner==0 );
  17728. p->owner = tid;
  17729. p->nRef++;
  17730. if( p->trace ){
  17731. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17732. }
  17733. #endif
  17734. }
  17735. static int winMutexTry(sqlite3_mutex *p){
  17736. #ifndef NDEBUG
  17737. DWORD tid = GetCurrentThreadId();
  17738. #endif
  17739. int rc = SQLITE_BUSY;
  17740. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17741. /*
  17742. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17743. ** is used it is merely an optimization. So it is OK for it to always
  17744. ** fail.
  17745. **
  17746. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17747. ** And some windows compilers complain if you try to use it without
  17748. ** first doing some #defines that prevent SQLite from building on Win98.
  17749. ** For that reason, we will omit this optimization for now. See
  17750. ** ticket #2685.
  17751. */
  17752. #if 0
  17753. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17754. p->owner = tid;
  17755. p->nRef++;
  17756. rc = SQLITE_OK;
  17757. }
  17758. #else
  17759. UNUSED_PARAMETER(p);
  17760. #endif
  17761. #ifdef SQLITE_DEBUG
  17762. if( rc==SQLITE_OK && p->trace ){
  17763. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17764. }
  17765. #endif
  17766. return rc;
  17767. }
  17768. /*
  17769. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17770. ** previously entered by the same thread. The behavior
  17771. ** is undefined if the mutex is not currently entered or
  17772. ** is not currently allocated. SQLite will never do either.
  17773. */
  17774. static void winMutexLeave(sqlite3_mutex *p){
  17775. #ifndef NDEBUG
  17776. DWORD tid = GetCurrentThreadId();
  17777. assert( p->nRef>0 );
  17778. assert( p->owner==tid );
  17779. p->nRef--;
  17780. if( p->nRef==0 ) p->owner = 0;
  17781. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17782. #endif
  17783. LeaveCriticalSection(&p->mutex);
  17784. #ifdef SQLITE_DEBUG
  17785. if( p->trace ){
  17786. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17787. }
  17788. #endif
  17789. }
  17790. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17791. static const sqlite3_mutex_methods sMutex = {
  17792. winMutexInit,
  17793. winMutexEnd,
  17794. winMutexAlloc,
  17795. winMutexFree,
  17796. winMutexEnter,
  17797. winMutexTry,
  17798. winMutexLeave,
  17799. #ifdef SQLITE_DEBUG
  17800. winMutexHeld,
  17801. winMutexNotheld
  17802. #else
  17803. 0,
  17804. 0
  17805. #endif
  17806. };
  17807. return &sMutex;
  17808. }
  17809. #endif /* SQLITE_MUTEX_W32 */
  17810. /************** End of mutex_w32.c *******************************************/
  17811. /************** Begin file malloc.c ******************************************/
  17812. /*
  17813. ** 2001 September 15
  17814. **
  17815. ** The author disclaims copyright to this source code. In place of
  17816. ** a legal notice, here is a blessing:
  17817. **
  17818. ** May you do good and not evil.
  17819. ** May you find forgiveness for yourself and forgive others.
  17820. ** May you share freely, never taking more than you give.
  17821. **
  17822. *************************************************************************
  17823. **
  17824. ** Memory allocation functions used throughout sqlite.
  17825. */
  17826. /* #include <stdarg.h> */
  17827. /*
  17828. ** Attempt to release up to n bytes of non-essential memory currently
  17829. ** held by SQLite. An example of non-essential memory is memory used to
  17830. ** cache database pages that are not currently in use.
  17831. */
  17832. SQLITE_API int sqlite3_release_memory(int n){
  17833. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17834. return sqlite3PcacheReleaseMemory(n);
  17835. #else
  17836. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  17837. ** is a no-op returning zero if SQLite is not compiled with
  17838. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  17839. UNUSED_PARAMETER(n);
  17840. return 0;
  17841. #endif
  17842. }
  17843. /*
  17844. ** An instance of the following object records the location of
  17845. ** each unused scratch buffer.
  17846. */
  17847. typedef struct ScratchFreeslot {
  17848. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  17849. } ScratchFreeslot;
  17850. /*
  17851. ** State information local to the memory allocation subsystem.
  17852. */
  17853. static SQLITE_WSD struct Mem0Global {
  17854. sqlite3_mutex *mutex; /* Mutex to serialize access */
  17855. /*
  17856. ** The alarm callback and its arguments. The mem0.mutex lock will
  17857. ** be held while the callback is running. Recursive calls into
  17858. ** the memory subsystem are allowed, but no new callbacks will be
  17859. ** issued.
  17860. */
  17861. sqlite3_int64 alarmThreshold;
  17862. void (*alarmCallback)(void*, sqlite3_int64,int);
  17863. void *alarmArg;
  17864. /*
  17865. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  17866. ** (so that a range test can be used to determine if an allocation
  17867. ** being freed came from pScratch) and a pointer to the list of
  17868. ** unused scratch allocations.
  17869. */
  17870. void *pScratchEnd;
  17871. ScratchFreeslot *pScratchFree;
  17872. u32 nScratchFree;
  17873. /*
  17874. ** True if heap is nearly "full" where "full" is defined by the
  17875. ** sqlite3_soft_heap_limit() setting.
  17876. */
  17877. int nearlyFull;
  17878. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  17879. #define mem0 GLOBAL(struct Mem0Global, mem0)
  17880. /*
  17881. ** This routine runs when the memory allocator sees that the
  17882. ** total memory allocation is about to exceed the soft heap
  17883. ** limit.
  17884. */
  17885. static void softHeapLimitEnforcer(
  17886. void *NotUsed,
  17887. sqlite3_int64 NotUsed2,
  17888. int allocSize
  17889. ){
  17890. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  17891. sqlite3_release_memory(allocSize);
  17892. }
  17893. /*
  17894. ** Change the alarm callback
  17895. */
  17896. static int sqlite3MemoryAlarm(
  17897. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17898. void *pArg,
  17899. sqlite3_int64 iThreshold
  17900. ){
  17901. int nUsed;
  17902. sqlite3_mutex_enter(mem0.mutex);
  17903. mem0.alarmCallback = xCallback;
  17904. mem0.alarmArg = pArg;
  17905. mem0.alarmThreshold = iThreshold;
  17906. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17907. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  17908. sqlite3_mutex_leave(mem0.mutex);
  17909. return SQLITE_OK;
  17910. }
  17911. #ifndef SQLITE_OMIT_DEPRECATED
  17912. /*
  17913. ** Deprecated external interface. Internal/core SQLite code
  17914. ** should call sqlite3MemoryAlarm.
  17915. */
  17916. SQLITE_API int sqlite3_memory_alarm(
  17917. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17918. void *pArg,
  17919. sqlite3_int64 iThreshold
  17920. ){
  17921. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  17922. }
  17923. #endif
  17924. /*
  17925. ** Set the soft heap-size limit for the library. Passing a zero or
  17926. ** negative value indicates no limit.
  17927. */
  17928. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  17929. sqlite3_int64 priorLimit;
  17930. sqlite3_int64 excess;
  17931. #ifndef SQLITE_OMIT_AUTOINIT
  17932. int rc = sqlite3_initialize();
  17933. if( rc ) return -1;
  17934. #endif
  17935. sqlite3_mutex_enter(mem0.mutex);
  17936. priorLimit = mem0.alarmThreshold;
  17937. sqlite3_mutex_leave(mem0.mutex);
  17938. if( n<0 ) return priorLimit;
  17939. if( n>0 ){
  17940. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  17941. }else{
  17942. sqlite3MemoryAlarm(0, 0, 0);
  17943. }
  17944. excess = sqlite3_memory_used() - n;
  17945. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  17946. return priorLimit;
  17947. }
  17948. SQLITE_API void sqlite3_soft_heap_limit(int n){
  17949. if( n<0 ) n = 0;
  17950. sqlite3_soft_heap_limit64(n);
  17951. }
  17952. /*
  17953. ** Initialize the memory allocation subsystem.
  17954. */
  17955. SQLITE_PRIVATE int sqlite3MallocInit(void){
  17956. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  17957. sqlite3MemSetDefault();
  17958. }
  17959. memset(&mem0, 0, sizeof(mem0));
  17960. if( sqlite3GlobalConfig.bCoreMutex ){
  17961. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17962. }
  17963. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  17964. && sqlite3GlobalConfig.nScratch>0 ){
  17965. int i, n, sz;
  17966. ScratchFreeslot *pSlot;
  17967. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  17968. sqlite3GlobalConfig.szScratch = sz;
  17969. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  17970. n = sqlite3GlobalConfig.nScratch;
  17971. mem0.pScratchFree = pSlot;
  17972. mem0.nScratchFree = n;
  17973. for(i=0; i<n-1; i++){
  17974. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  17975. pSlot = pSlot->pNext;
  17976. }
  17977. pSlot->pNext = 0;
  17978. mem0.pScratchEnd = (void*)&pSlot[1];
  17979. }else{
  17980. mem0.pScratchEnd = 0;
  17981. sqlite3GlobalConfig.pScratch = 0;
  17982. sqlite3GlobalConfig.szScratch = 0;
  17983. sqlite3GlobalConfig.nScratch = 0;
  17984. }
  17985. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  17986. || sqlite3GlobalConfig.nPage<1 ){
  17987. sqlite3GlobalConfig.pPage = 0;
  17988. sqlite3GlobalConfig.szPage = 0;
  17989. sqlite3GlobalConfig.nPage = 0;
  17990. }
  17991. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  17992. }
  17993. /*
  17994. ** Return true if the heap is currently under memory pressure - in other
  17995. ** words if the amount of heap used is close to the limit set by
  17996. ** sqlite3_soft_heap_limit().
  17997. */
  17998. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  17999. return mem0.nearlyFull;
  18000. }
  18001. /*
  18002. ** Deinitialize the memory allocation subsystem.
  18003. */
  18004. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  18005. if( sqlite3GlobalConfig.m.xShutdown ){
  18006. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  18007. }
  18008. memset(&mem0, 0, sizeof(mem0));
  18009. }
  18010. /*
  18011. ** Return the amount of memory currently checked out.
  18012. */
  18013. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  18014. int n, mx;
  18015. sqlite3_int64 res;
  18016. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  18017. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  18018. return res;
  18019. }
  18020. /*
  18021. ** Return the maximum amount of memory that has ever been
  18022. ** checked out since either the beginning of this process
  18023. ** or since the most recent reset.
  18024. */
  18025. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  18026. int n, mx;
  18027. sqlite3_int64 res;
  18028. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  18029. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  18030. return res;
  18031. }
  18032. /*
  18033. ** Trigger the alarm
  18034. */
  18035. static void sqlite3MallocAlarm(int nByte){
  18036. void (*xCallback)(void*,sqlite3_int64,int);
  18037. sqlite3_int64 nowUsed;
  18038. void *pArg;
  18039. if( mem0.alarmCallback==0 ) return;
  18040. xCallback = mem0.alarmCallback;
  18041. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18042. pArg = mem0.alarmArg;
  18043. mem0.alarmCallback = 0;
  18044. sqlite3_mutex_leave(mem0.mutex);
  18045. xCallback(pArg, nowUsed, nByte);
  18046. sqlite3_mutex_enter(mem0.mutex);
  18047. mem0.alarmCallback = xCallback;
  18048. mem0.alarmArg = pArg;
  18049. }
  18050. /*
  18051. ** Do a memory allocation with statistics and alarms. Assume the
  18052. ** lock is already held.
  18053. */
  18054. static int mallocWithAlarm(int n, void **pp){
  18055. int nFull;
  18056. void *p;
  18057. assert( sqlite3_mutex_held(mem0.mutex) );
  18058. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  18059. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  18060. if( mem0.alarmCallback!=0 ){
  18061. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18062. if( nUsed >= mem0.alarmThreshold - nFull ){
  18063. mem0.nearlyFull = 1;
  18064. sqlite3MallocAlarm(nFull);
  18065. }else{
  18066. mem0.nearlyFull = 0;
  18067. }
  18068. }
  18069. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18070. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18071. if( p==0 && mem0.alarmCallback ){
  18072. sqlite3MallocAlarm(nFull);
  18073. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18074. }
  18075. #endif
  18076. if( p ){
  18077. nFull = sqlite3MallocSize(p);
  18078. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  18079. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  18080. }
  18081. *pp = p;
  18082. return nFull;
  18083. }
  18084. /*
  18085. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  18086. ** assumes the memory subsystem has already been initialized.
  18087. */
  18088. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  18089. void *p;
  18090. if( n<=0 /* IMP: R-65312-04917 */
  18091. || n>=0x7fffff00
  18092. ){
  18093. /* A memory allocation of a number of bytes which is near the maximum
  18094. ** signed integer value might cause an integer overflow inside of the
  18095. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  18096. ** 255 bytes of overhead. SQLite itself will never use anything near
  18097. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  18098. p = 0;
  18099. }else if( sqlite3GlobalConfig.bMemstat ){
  18100. sqlite3_mutex_enter(mem0.mutex);
  18101. mallocWithAlarm(n, &p);
  18102. sqlite3_mutex_leave(mem0.mutex);
  18103. }else{
  18104. p = sqlite3GlobalConfig.m.xMalloc(n);
  18105. }
  18106. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  18107. return p;
  18108. }
  18109. /*
  18110. ** This version of the memory allocation is for use by the application.
  18111. ** First make sure the memory subsystem is initialized, then do the
  18112. ** allocation.
  18113. */
  18114. SQLITE_API void *sqlite3_malloc(int n){
  18115. #ifndef SQLITE_OMIT_AUTOINIT
  18116. if( sqlite3_initialize() ) return 0;
  18117. #endif
  18118. return sqlite3Malloc(n);
  18119. }
  18120. /*
  18121. ** Each thread may only have a single outstanding allocation from
  18122. ** xScratchMalloc(). We verify this constraint in the single-threaded
  18123. ** case by setting scratchAllocOut to 1 when an allocation
  18124. ** is outstanding clearing it when the allocation is freed.
  18125. */
  18126. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18127. static int scratchAllocOut = 0;
  18128. #endif
  18129. /*
  18130. ** Allocate memory that is to be used and released right away.
  18131. ** This routine is similar to alloca() in that it is not intended
  18132. ** for situations where the memory might be held long-term. This
  18133. ** routine is intended to get memory to old large transient data
  18134. ** structures that would not normally fit on the stack of an
  18135. ** embedded processor.
  18136. */
  18137. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  18138. void *p;
  18139. assert( n>0 );
  18140. sqlite3_mutex_enter(mem0.mutex);
  18141. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  18142. p = mem0.pScratchFree;
  18143. mem0.pScratchFree = mem0.pScratchFree->pNext;
  18144. mem0.nScratchFree--;
  18145. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  18146. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18147. sqlite3_mutex_leave(mem0.mutex);
  18148. }else{
  18149. if( sqlite3GlobalConfig.bMemstat ){
  18150. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18151. n = mallocWithAlarm(n, &p);
  18152. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  18153. sqlite3_mutex_leave(mem0.mutex);
  18154. }else{
  18155. sqlite3_mutex_leave(mem0.mutex);
  18156. p = sqlite3GlobalConfig.m.xMalloc(n);
  18157. }
  18158. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  18159. }
  18160. assert( sqlite3_mutex_notheld(mem0.mutex) );
  18161. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18162. /* Verify that no more than two scratch allocations per thread
  18163. ** are outstanding at one time. (This is only checked in the
  18164. ** single-threaded case since checking in the multi-threaded case
  18165. ** would be much more complicated.) */
  18166. assert( scratchAllocOut<=1 );
  18167. if( p ) scratchAllocOut++;
  18168. #endif
  18169. return p;
  18170. }
  18171. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  18172. if( p ){
  18173. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18174. /* Verify that no more than two scratch allocation per thread
  18175. ** is outstanding at one time. (This is only checked in the
  18176. ** single-threaded case since checking in the multi-threaded case
  18177. ** would be much more complicated.) */
  18178. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  18179. scratchAllocOut--;
  18180. #endif
  18181. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  18182. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  18183. ScratchFreeslot *pSlot;
  18184. pSlot = (ScratchFreeslot*)p;
  18185. sqlite3_mutex_enter(mem0.mutex);
  18186. pSlot->pNext = mem0.pScratchFree;
  18187. mem0.pScratchFree = pSlot;
  18188. mem0.nScratchFree++;
  18189. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  18190. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  18191. sqlite3_mutex_leave(mem0.mutex);
  18192. }else{
  18193. /* Release memory back to the heap */
  18194. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  18195. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  18196. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18197. if( sqlite3GlobalConfig.bMemstat ){
  18198. int iSize = sqlite3MallocSize(p);
  18199. sqlite3_mutex_enter(mem0.mutex);
  18200. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  18201. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  18202. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18203. sqlite3GlobalConfig.m.xFree(p);
  18204. sqlite3_mutex_leave(mem0.mutex);
  18205. }else{
  18206. sqlite3GlobalConfig.m.xFree(p);
  18207. }
  18208. }
  18209. }
  18210. }
  18211. /*
  18212. ** TRUE if p is a lookaside memory allocation from db
  18213. */
  18214. #ifndef SQLITE_OMIT_LOOKASIDE
  18215. static int isLookaside(sqlite3 *db, void *p){
  18216. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18217. }
  18218. #else
  18219. #define isLookaside(A,B) 0
  18220. #endif
  18221. /*
  18222. ** Return the size of a memory allocation previously obtained from
  18223. ** sqlite3Malloc() or sqlite3_malloc().
  18224. */
  18225. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18226. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18227. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18228. return sqlite3GlobalConfig.m.xSize(p);
  18229. }
  18230. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18231. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18232. if( db && isLookaside(db, p) ){
  18233. return db->lookaside.sz;
  18234. }else{
  18235. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18236. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18237. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18238. return sqlite3GlobalConfig.m.xSize(p);
  18239. }
  18240. }
  18241. /*
  18242. ** Free memory previously obtained from sqlite3Malloc().
  18243. */
  18244. SQLITE_API void sqlite3_free(void *p){
  18245. if( p==0 ) return; /* IMP: R-49053-54554 */
  18246. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18247. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18248. if( sqlite3GlobalConfig.bMemstat ){
  18249. sqlite3_mutex_enter(mem0.mutex);
  18250. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18251. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18252. sqlite3GlobalConfig.m.xFree(p);
  18253. sqlite3_mutex_leave(mem0.mutex);
  18254. }else{
  18255. sqlite3GlobalConfig.m.xFree(p);
  18256. }
  18257. }
  18258. /*
  18259. ** Free memory that might be associated with a particular database
  18260. ** connection.
  18261. */
  18262. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18263. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18264. if( db ){
  18265. if( db->pnBytesFreed ){
  18266. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18267. return;
  18268. }
  18269. if( isLookaside(db, p) ){
  18270. LookasideSlot *pBuf = (LookasideSlot*)p;
  18271. #if SQLITE_DEBUG
  18272. /* Trash all content in the buffer being freed */
  18273. memset(p, 0xaa, db->lookaside.sz);
  18274. #endif
  18275. pBuf->pNext = db->lookaside.pFree;
  18276. db->lookaside.pFree = pBuf;
  18277. db->lookaside.nOut--;
  18278. return;
  18279. }
  18280. }
  18281. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18282. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18283. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18284. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18285. sqlite3_free(p);
  18286. }
  18287. /*
  18288. ** Change the size of an existing memory allocation
  18289. */
  18290. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18291. int nOld, nNew, nDiff;
  18292. void *pNew;
  18293. if( pOld==0 ){
  18294. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18295. }
  18296. if( nBytes<=0 ){
  18297. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18298. return 0;
  18299. }
  18300. if( nBytes>=0x7fffff00 ){
  18301. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18302. return 0;
  18303. }
  18304. nOld = sqlite3MallocSize(pOld);
  18305. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18306. ** argument to xRealloc is always a value returned by a prior call to
  18307. ** xRoundup. */
  18308. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18309. if( nOld==nNew ){
  18310. pNew = pOld;
  18311. }else if( sqlite3GlobalConfig.bMemstat ){
  18312. sqlite3_mutex_enter(mem0.mutex);
  18313. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18314. nDiff = nNew - nOld;
  18315. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18316. mem0.alarmThreshold-nDiff ){
  18317. sqlite3MallocAlarm(nDiff);
  18318. }
  18319. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18320. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18321. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18322. if( pNew==0 && mem0.alarmCallback ){
  18323. sqlite3MallocAlarm(nBytes);
  18324. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18325. }
  18326. if( pNew ){
  18327. nNew = sqlite3MallocSize(pNew);
  18328. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18329. }
  18330. sqlite3_mutex_leave(mem0.mutex);
  18331. }else{
  18332. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18333. }
  18334. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18335. return pNew;
  18336. }
  18337. /*
  18338. ** The public interface to sqlite3Realloc. Make sure that the memory
  18339. ** subsystem is initialized prior to invoking sqliteRealloc.
  18340. */
  18341. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18342. #ifndef SQLITE_OMIT_AUTOINIT
  18343. if( sqlite3_initialize() ) return 0;
  18344. #endif
  18345. return sqlite3Realloc(pOld, n);
  18346. }
  18347. /*
  18348. ** Allocate and zero memory.
  18349. */
  18350. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18351. void *p = sqlite3Malloc(n);
  18352. if( p ){
  18353. memset(p, 0, n);
  18354. }
  18355. return p;
  18356. }
  18357. /*
  18358. ** Allocate and zero memory. If the allocation fails, make
  18359. ** the mallocFailed flag in the connection pointer.
  18360. */
  18361. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18362. void *p = sqlite3DbMallocRaw(db, n);
  18363. if( p ){
  18364. memset(p, 0, n);
  18365. }
  18366. return p;
  18367. }
  18368. /*
  18369. ** Allocate and zero memory. If the allocation fails, make
  18370. ** the mallocFailed flag in the connection pointer.
  18371. **
  18372. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18373. ** failure on the same database connection) then always return 0.
  18374. ** Hence for a particular database connection, once malloc starts
  18375. ** failing, it fails consistently until mallocFailed is reset.
  18376. ** This is an important assumption. There are many places in the
  18377. ** code that do things like this:
  18378. **
  18379. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18380. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18381. ** if( b ) a[10] = 9;
  18382. **
  18383. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18384. ** that all prior mallocs (ex: "a") worked too.
  18385. */
  18386. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18387. void *p;
  18388. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18389. assert( db==0 || db->pnBytesFreed==0 );
  18390. #ifndef SQLITE_OMIT_LOOKASIDE
  18391. if( db ){
  18392. LookasideSlot *pBuf;
  18393. if( db->mallocFailed ){
  18394. return 0;
  18395. }
  18396. if( db->lookaside.bEnabled ){
  18397. if( n>db->lookaside.sz ){
  18398. db->lookaside.anStat[1]++;
  18399. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18400. db->lookaside.anStat[2]++;
  18401. }else{
  18402. db->lookaside.pFree = pBuf->pNext;
  18403. db->lookaside.nOut++;
  18404. db->lookaside.anStat[0]++;
  18405. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18406. db->lookaside.mxOut = db->lookaside.nOut;
  18407. }
  18408. return (void*)pBuf;
  18409. }
  18410. }
  18411. }
  18412. #else
  18413. if( db && db->mallocFailed ){
  18414. return 0;
  18415. }
  18416. #endif
  18417. p = sqlite3Malloc(n);
  18418. if( !p && db ){
  18419. db->mallocFailed = 1;
  18420. }
  18421. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18422. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18423. return p;
  18424. }
  18425. /*
  18426. ** Resize the block of memory pointed to by p to n bytes. If the
  18427. ** resize fails, set the mallocFailed flag in the connection object.
  18428. */
  18429. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18430. void *pNew = 0;
  18431. assert( db!=0 );
  18432. assert( sqlite3_mutex_held(db->mutex) );
  18433. if( db->mallocFailed==0 ){
  18434. if( p==0 ){
  18435. return sqlite3DbMallocRaw(db, n);
  18436. }
  18437. if( isLookaside(db, p) ){
  18438. if( n<=db->lookaside.sz ){
  18439. return p;
  18440. }
  18441. pNew = sqlite3DbMallocRaw(db, n);
  18442. if( pNew ){
  18443. memcpy(pNew, p, db->lookaside.sz);
  18444. sqlite3DbFree(db, p);
  18445. }
  18446. }else{
  18447. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18448. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18449. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18450. pNew = sqlite3_realloc(p, n);
  18451. if( !pNew ){
  18452. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18453. db->mallocFailed = 1;
  18454. }
  18455. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18456. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18457. }
  18458. }
  18459. return pNew;
  18460. }
  18461. /*
  18462. ** Attempt to reallocate p. If the reallocation fails, then free p
  18463. ** and set the mallocFailed flag in the database connection.
  18464. */
  18465. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18466. void *pNew;
  18467. pNew = sqlite3DbRealloc(db, p, n);
  18468. if( !pNew ){
  18469. sqlite3DbFree(db, p);
  18470. }
  18471. return pNew;
  18472. }
  18473. /*
  18474. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18475. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18476. ** is because when memory debugging is turned on, these two functions are
  18477. ** called via macros that record the current file and line number in the
  18478. ** ThreadData structure.
  18479. */
  18480. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18481. char *zNew;
  18482. size_t n;
  18483. if( z==0 ){
  18484. return 0;
  18485. }
  18486. n = sqlite3Strlen30(z) + 1;
  18487. assert( (n&0x7fffffff)==n );
  18488. zNew = sqlite3DbMallocRaw(db, (int)n);
  18489. if( zNew ){
  18490. memcpy(zNew, z, n);
  18491. }
  18492. return zNew;
  18493. }
  18494. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18495. char *zNew;
  18496. if( z==0 ){
  18497. return 0;
  18498. }
  18499. assert( (n&0x7fffffff)==n );
  18500. zNew = sqlite3DbMallocRaw(db, n+1);
  18501. if( zNew ){
  18502. memcpy(zNew, z, n);
  18503. zNew[n] = 0;
  18504. }
  18505. return zNew;
  18506. }
  18507. /*
  18508. ** Create a string from the zFromat argument and the va_list that follows.
  18509. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18510. ** point to that string.
  18511. */
  18512. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18513. va_list ap;
  18514. char *z;
  18515. va_start(ap, zFormat);
  18516. z = sqlite3VMPrintf(db, zFormat, ap);
  18517. va_end(ap);
  18518. sqlite3DbFree(db, *pz);
  18519. *pz = z;
  18520. }
  18521. /*
  18522. ** This function must be called before exiting any API function (i.e.
  18523. ** returning control to the user) that has called sqlite3_malloc or
  18524. ** sqlite3_realloc.
  18525. **
  18526. ** The returned value is normally a copy of the second argument to this
  18527. ** function. However, if a malloc() failure has occurred since the previous
  18528. ** invocation SQLITE_NOMEM is returned instead.
  18529. **
  18530. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18531. ** then the connection error-code (the value returned by sqlite3_errcode())
  18532. ** is set to SQLITE_NOMEM.
  18533. */
  18534. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18535. /* If the db handle is not NULL, then we must hold the connection handle
  18536. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18537. ** is unsafe, as is the call to sqlite3Error().
  18538. */
  18539. assert( !db || sqlite3_mutex_held(db->mutex) );
  18540. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18541. sqlite3Error(db, SQLITE_NOMEM, 0);
  18542. db->mallocFailed = 0;
  18543. rc = SQLITE_NOMEM;
  18544. }
  18545. return rc & (db ? db->errMask : 0xff);
  18546. }
  18547. /************** End of malloc.c **********************************************/
  18548. /************** Begin file printf.c ******************************************/
  18549. /*
  18550. ** The "printf" code that follows dates from the 1980's. It is in
  18551. ** the public domain. The original comments are included here for
  18552. ** completeness. They are very out-of-date but might be useful as
  18553. ** an historical reference. Most of the "enhancements" have been backed
  18554. ** out so that the functionality is now the same as standard printf().
  18555. **
  18556. **************************************************************************
  18557. **
  18558. ** This file contains code for a set of "printf"-like routines. These
  18559. ** routines format strings much like the printf() from the standard C
  18560. ** library, though the implementation here has enhancements to support
  18561. ** SQLlite.
  18562. */
  18563. /*
  18564. ** Conversion types fall into various categories as defined by the
  18565. ** following enumeration.
  18566. */
  18567. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18568. #define etFLOAT 2 /* Floating point. %f */
  18569. #define etEXP 3 /* Exponentional notation. %e and %E */
  18570. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18571. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18572. #define etSTRING 6 /* Strings. %s */
  18573. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18574. #define etPERCENT 8 /* Percent symbol. %% */
  18575. #define etCHARX 9 /* Characters. %c */
  18576. /* The rest are extensions, not normally found in printf() */
  18577. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18578. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18579. NULL pointers replaced by SQL NULL. %Q */
  18580. #define etTOKEN 12 /* a pointer to a Token structure */
  18581. #define etSRCLIST 13 /* a pointer to a SrcList */
  18582. #define etPOINTER 14 /* The %p conversion */
  18583. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18584. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18585. #define etINVALID 0 /* Any unrecognized conversion type */
  18586. /*
  18587. ** An "etByte" is an 8-bit unsigned value.
  18588. */
  18589. typedef unsigned char etByte;
  18590. /*
  18591. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18592. ** by an instance of the following structure
  18593. */
  18594. typedef struct et_info { /* Information about each format field */
  18595. char fmttype; /* The format field code letter */
  18596. etByte base; /* The base for radix conversion */
  18597. etByte flags; /* One or more of FLAG_ constants below */
  18598. etByte type; /* Conversion paradigm */
  18599. etByte charset; /* Offset into aDigits[] of the digits string */
  18600. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18601. } et_info;
  18602. /*
  18603. ** Allowed values for et_info.flags
  18604. */
  18605. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  18606. #define FLAG_INTERN 2 /* True if for internal use only */
  18607. #define FLAG_STRING 4 /* Allow infinity precision */
  18608. /*
  18609. ** The following table is searched linearly, so it is good to put the
  18610. ** most frequently used conversion types first.
  18611. */
  18612. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  18613. static const char aPrefix[] = "-x0\000X0";
  18614. static const et_info fmtinfo[] = {
  18615. { 'd', 10, 1, etRADIX, 0, 0 },
  18616. { 's', 0, 4, etSTRING, 0, 0 },
  18617. { 'g', 0, 1, etGENERIC, 30, 0 },
  18618. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  18619. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  18620. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  18621. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  18622. { 'c', 0, 0, etCHARX, 0, 0 },
  18623. { 'o', 8, 0, etRADIX, 0, 2 },
  18624. { 'u', 10, 0, etRADIX, 0, 0 },
  18625. { 'x', 16, 0, etRADIX, 16, 1 },
  18626. { 'X', 16, 0, etRADIX, 0, 4 },
  18627. #ifndef SQLITE_OMIT_FLOATING_POINT
  18628. { 'f', 0, 1, etFLOAT, 0, 0 },
  18629. { 'e', 0, 1, etEXP, 30, 0 },
  18630. { 'E', 0, 1, etEXP, 14, 0 },
  18631. { 'G', 0, 1, etGENERIC, 14, 0 },
  18632. #endif
  18633. { 'i', 10, 1, etRADIX, 0, 0 },
  18634. { 'n', 0, 0, etSIZE, 0, 0 },
  18635. { '%', 0, 0, etPERCENT, 0, 0 },
  18636. { 'p', 16, 0, etPOINTER, 0, 1 },
  18637. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  18638. ** use only */
  18639. { 'T', 0, 2, etTOKEN, 0, 0 },
  18640. { 'S', 0, 2, etSRCLIST, 0, 0 },
  18641. { 'r', 10, 3, etORDINAL, 0, 0 },
  18642. };
  18643. /*
  18644. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  18645. ** conversions will work.
  18646. */
  18647. #ifndef SQLITE_OMIT_FLOATING_POINT
  18648. /*
  18649. ** "*val" is a double such that 0.1 <= *val < 10.0
  18650. ** Return the ascii code for the leading digit of *val, then
  18651. ** multiply "*val" by 10.0 to renormalize.
  18652. **
  18653. ** Example:
  18654. ** input: *val = 3.14159
  18655. ** output: *val = 1.4159 function return = '3'
  18656. **
  18657. ** The counter *cnt is incremented each time. After counter exceeds
  18658. ** 16 (the number of significant digits in a 64-bit float) '0' is
  18659. ** always returned.
  18660. */
  18661. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  18662. int digit;
  18663. LONGDOUBLE_TYPE d;
  18664. if( (*cnt)<=0 ) return '0';
  18665. (*cnt)--;
  18666. digit = (int)*val;
  18667. d = digit;
  18668. digit += '0';
  18669. *val = (*val - d)*10.0;
  18670. return (char)digit;
  18671. }
  18672. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18673. /*
  18674. ** Append N space characters to the given string buffer.
  18675. */
  18676. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  18677. static const char zSpaces[] = " ";
  18678. while( N>=(int)sizeof(zSpaces)-1 ){
  18679. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  18680. N -= sizeof(zSpaces)-1;
  18681. }
  18682. if( N>0 ){
  18683. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  18684. }
  18685. }
  18686. /*
  18687. ** On machines with a small stack size, you can redefine the
  18688. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  18689. */
  18690. #ifndef SQLITE_PRINT_BUF_SIZE
  18691. # define SQLITE_PRINT_BUF_SIZE 70
  18692. #endif
  18693. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  18694. /*
  18695. ** Render a string given by "fmt" into the StrAccum object.
  18696. */
  18697. SQLITE_PRIVATE void sqlite3VXPrintf(
  18698. StrAccum *pAccum, /* Accumulate results here */
  18699. int useExtended, /* Allow extended %-conversions */
  18700. const char *fmt, /* Format string */
  18701. va_list ap /* arguments */
  18702. ){
  18703. int c; /* Next character in the format string */
  18704. char *bufpt; /* Pointer to the conversion buffer */
  18705. int precision; /* Precision of the current field */
  18706. int length; /* Length of the field */
  18707. int idx; /* A general purpose loop counter */
  18708. int width; /* Width of the current field */
  18709. etByte flag_leftjustify; /* True if "-" flag is present */
  18710. etByte flag_plussign; /* True if "+" flag is present */
  18711. etByte flag_blanksign; /* True if " " flag is present */
  18712. etByte flag_alternateform; /* True if "#" flag is present */
  18713. etByte flag_altform2; /* True if "!" flag is present */
  18714. etByte flag_zeropad; /* True if field width constant starts with zero */
  18715. etByte flag_long; /* True if "l" flag is present */
  18716. etByte flag_longlong; /* True if the "ll" flag is present */
  18717. etByte done; /* Loop termination flag */
  18718. etByte xtype = 0; /* Conversion paradigm */
  18719. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  18720. sqlite_uint64 longvalue; /* Value for integer types */
  18721. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  18722. const et_info *infop; /* Pointer to the appropriate info structure */
  18723. char *zOut; /* Rendering buffer */
  18724. int nOut; /* Size of the rendering buffer */
  18725. char *zExtra; /* Malloced memory used by some conversion */
  18726. #ifndef SQLITE_OMIT_FLOATING_POINT
  18727. int exp, e2; /* exponent of real numbers */
  18728. int nsd; /* Number of significant digits returned */
  18729. double rounder; /* Used for rounding floating point values */
  18730. etByte flag_dp; /* True if decimal point should be shown */
  18731. etByte flag_rtz; /* True if trailing zeros should be removed */
  18732. #endif
  18733. char buf[etBUFSIZE]; /* Conversion buffer */
  18734. bufpt = 0;
  18735. for(; (c=(*fmt))!=0; ++fmt){
  18736. if( c!='%' ){
  18737. int amt;
  18738. bufpt = (char *)fmt;
  18739. amt = 1;
  18740. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  18741. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  18742. if( c==0 ) break;
  18743. }
  18744. if( (c=(*++fmt))==0 ){
  18745. sqlite3StrAccumAppend(pAccum, "%", 1);
  18746. break;
  18747. }
  18748. /* Find out what flags are present */
  18749. flag_leftjustify = flag_plussign = flag_blanksign =
  18750. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  18751. done = 0;
  18752. do{
  18753. switch( c ){
  18754. case '-': flag_leftjustify = 1; break;
  18755. case '+': flag_plussign = 1; break;
  18756. case ' ': flag_blanksign = 1; break;
  18757. case '#': flag_alternateform = 1; break;
  18758. case '!': flag_altform2 = 1; break;
  18759. case '0': flag_zeropad = 1; break;
  18760. default: done = 1; break;
  18761. }
  18762. }while( !done && (c=(*++fmt))!=0 );
  18763. /* Get the field width */
  18764. width = 0;
  18765. if( c=='*' ){
  18766. width = va_arg(ap,int);
  18767. if( width<0 ){
  18768. flag_leftjustify = 1;
  18769. width = -width;
  18770. }
  18771. c = *++fmt;
  18772. }else{
  18773. while( c>='0' && c<='9' ){
  18774. width = width*10 + c - '0';
  18775. c = *++fmt;
  18776. }
  18777. }
  18778. /* Get the precision */
  18779. if( c=='.' ){
  18780. precision = 0;
  18781. c = *++fmt;
  18782. if( c=='*' ){
  18783. precision = va_arg(ap,int);
  18784. if( precision<0 ) precision = -precision;
  18785. c = *++fmt;
  18786. }else{
  18787. while( c>='0' && c<='9' ){
  18788. precision = precision*10 + c - '0';
  18789. c = *++fmt;
  18790. }
  18791. }
  18792. }else{
  18793. precision = -1;
  18794. }
  18795. /* Get the conversion type modifier */
  18796. if( c=='l' ){
  18797. flag_long = 1;
  18798. c = *++fmt;
  18799. if( c=='l' ){
  18800. flag_longlong = 1;
  18801. c = *++fmt;
  18802. }else{
  18803. flag_longlong = 0;
  18804. }
  18805. }else{
  18806. flag_long = flag_longlong = 0;
  18807. }
  18808. /* Fetch the info entry for the field */
  18809. infop = &fmtinfo[0];
  18810. xtype = etINVALID;
  18811. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  18812. if( c==fmtinfo[idx].fmttype ){
  18813. infop = &fmtinfo[idx];
  18814. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  18815. xtype = infop->type;
  18816. }else{
  18817. return;
  18818. }
  18819. break;
  18820. }
  18821. }
  18822. zExtra = 0;
  18823. /*
  18824. ** At this point, variables are initialized as follows:
  18825. **
  18826. ** flag_alternateform TRUE if a '#' is present.
  18827. ** flag_altform2 TRUE if a '!' is present.
  18828. ** flag_plussign TRUE if a '+' is present.
  18829. ** flag_leftjustify TRUE if a '-' is present or if the
  18830. ** field width was negative.
  18831. ** flag_zeropad TRUE if the width began with 0.
  18832. ** flag_long TRUE if the letter 'l' (ell) prefixed
  18833. ** the conversion character.
  18834. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  18835. ** the conversion character.
  18836. ** flag_blanksign TRUE if a ' ' is present.
  18837. ** width The specified field width. This is
  18838. ** always non-negative. Zero is the default.
  18839. ** precision The specified precision. The default
  18840. ** is -1.
  18841. ** xtype The class of the conversion.
  18842. ** infop Pointer to the appropriate info struct.
  18843. */
  18844. switch( xtype ){
  18845. case etPOINTER:
  18846. flag_longlong = sizeof(char*)==sizeof(i64);
  18847. flag_long = sizeof(char*)==sizeof(long int);
  18848. /* Fall through into the next case */
  18849. case etORDINAL:
  18850. case etRADIX:
  18851. if( infop->flags & FLAG_SIGNED ){
  18852. i64 v;
  18853. if( flag_longlong ){
  18854. v = va_arg(ap,i64);
  18855. }else if( flag_long ){
  18856. v = va_arg(ap,long int);
  18857. }else{
  18858. v = va_arg(ap,int);
  18859. }
  18860. if( v<0 ){
  18861. if( v==SMALLEST_INT64 ){
  18862. longvalue = ((u64)1)<<63;
  18863. }else{
  18864. longvalue = -v;
  18865. }
  18866. prefix = '-';
  18867. }else{
  18868. longvalue = v;
  18869. if( flag_plussign ) prefix = '+';
  18870. else if( flag_blanksign ) prefix = ' ';
  18871. else prefix = 0;
  18872. }
  18873. }else{
  18874. if( flag_longlong ){
  18875. longvalue = va_arg(ap,u64);
  18876. }else if( flag_long ){
  18877. longvalue = va_arg(ap,unsigned long int);
  18878. }else{
  18879. longvalue = va_arg(ap,unsigned int);
  18880. }
  18881. prefix = 0;
  18882. }
  18883. if( longvalue==0 ) flag_alternateform = 0;
  18884. if( flag_zeropad && precision<width-(prefix!=0) ){
  18885. precision = width-(prefix!=0);
  18886. }
  18887. if( precision<etBUFSIZE-10 ){
  18888. nOut = etBUFSIZE;
  18889. zOut = buf;
  18890. }else{
  18891. nOut = precision + 10;
  18892. zOut = zExtra = sqlite3Malloc( nOut );
  18893. if( zOut==0 ){
  18894. pAccum->mallocFailed = 1;
  18895. return;
  18896. }
  18897. }
  18898. bufpt = &zOut[nOut-1];
  18899. if( xtype==etORDINAL ){
  18900. static const char zOrd[] = "thstndrd";
  18901. int x = (int)(longvalue % 10);
  18902. if( x>=4 || (longvalue/10)%10==1 ){
  18903. x = 0;
  18904. }
  18905. *(--bufpt) = zOrd[x*2+1];
  18906. *(--bufpt) = zOrd[x*2];
  18907. }
  18908. {
  18909. register const char *cset; /* Use registers for speed */
  18910. register int base;
  18911. cset = &aDigits[infop->charset];
  18912. base = infop->base;
  18913. do{ /* Convert to ascii */
  18914. *(--bufpt) = cset[longvalue%base];
  18915. longvalue = longvalue/base;
  18916. }while( longvalue>0 );
  18917. }
  18918. length = (int)(&zOut[nOut-1]-bufpt);
  18919. for(idx=precision-length; idx>0; idx--){
  18920. *(--bufpt) = '0'; /* Zero pad */
  18921. }
  18922. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  18923. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  18924. const char *pre;
  18925. char x;
  18926. pre = &aPrefix[infop->prefix];
  18927. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  18928. }
  18929. length = (int)(&zOut[nOut-1]-bufpt);
  18930. break;
  18931. case etFLOAT:
  18932. case etEXP:
  18933. case etGENERIC:
  18934. realvalue = va_arg(ap,double);
  18935. #ifdef SQLITE_OMIT_FLOATING_POINT
  18936. length = 0;
  18937. #else
  18938. if( precision<0 ) precision = 6; /* Set default precision */
  18939. if( realvalue<0.0 ){
  18940. realvalue = -realvalue;
  18941. prefix = '-';
  18942. }else{
  18943. if( flag_plussign ) prefix = '+';
  18944. else if( flag_blanksign ) prefix = ' ';
  18945. else prefix = 0;
  18946. }
  18947. if( xtype==etGENERIC && precision>0 ) precision--;
  18948. #if 0
  18949. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  18950. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  18951. #else
  18952. /* It makes more sense to use 0.5 */
  18953. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  18954. #endif
  18955. if( xtype==etFLOAT ) realvalue += rounder;
  18956. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  18957. exp = 0;
  18958. if( sqlite3IsNaN((double)realvalue) ){
  18959. bufpt = "NaN";
  18960. length = 3;
  18961. break;
  18962. }
  18963. if( realvalue>0.0 ){
  18964. LONGDOUBLE_TYPE scale = 1.0;
  18965. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  18966. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  18967. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  18968. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  18969. realvalue /= scale;
  18970. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  18971. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  18972. if( exp>350 ){
  18973. if( prefix=='-' ){
  18974. bufpt = "-Inf";
  18975. }else if( prefix=='+' ){
  18976. bufpt = "+Inf";
  18977. }else{
  18978. bufpt = "Inf";
  18979. }
  18980. length = sqlite3Strlen30(bufpt);
  18981. break;
  18982. }
  18983. }
  18984. bufpt = buf;
  18985. /*
  18986. ** If the field type is etGENERIC, then convert to either etEXP
  18987. ** or etFLOAT, as appropriate.
  18988. */
  18989. if( xtype!=etFLOAT ){
  18990. realvalue += rounder;
  18991. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  18992. }
  18993. if( xtype==etGENERIC ){
  18994. flag_rtz = !flag_alternateform;
  18995. if( exp<-4 || exp>precision ){
  18996. xtype = etEXP;
  18997. }else{
  18998. precision = precision - exp;
  18999. xtype = etFLOAT;
  19000. }
  19001. }else{
  19002. flag_rtz = flag_altform2;
  19003. }
  19004. if( xtype==etEXP ){
  19005. e2 = 0;
  19006. }else{
  19007. e2 = exp;
  19008. }
  19009. if( e2+precision+width > etBUFSIZE - 15 ){
  19010. bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
  19011. if( bufpt==0 ){
  19012. pAccum->mallocFailed = 1;
  19013. return;
  19014. }
  19015. }
  19016. zOut = bufpt;
  19017. nsd = 16 + flag_altform2*10;
  19018. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  19019. /* The sign in front of the number */
  19020. if( prefix ){
  19021. *(bufpt++) = prefix;
  19022. }
  19023. /* Digits prior to the decimal point */
  19024. if( e2<0 ){
  19025. *(bufpt++) = '0';
  19026. }else{
  19027. for(; e2>=0; e2--){
  19028. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19029. }
  19030. }
  19031. /* The decimal point */
  19032. if( flag_dp ){
  19033. *(bufpt++) = '.';
  19034. }
  19035. /* "0" digits after the decimal point but before the first
  19036. ** significant digit of the number */
  19037. for(e2++; e2<0; precision--, e2++){
  19038. assert( precision>0 );
  19039. *(bufpt++) = '0';
  19040. }
  19041. /* Significant digits after the decimal point */
  19042. while( (precision--)>0 ){
  19043. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19044. }
  19045. /* Remove trailing zeros and the "." if no digits follow the "." */
  19046. if( flag_rtz && flag_dp ){
  19047. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  19048. assert( bufpt>zOut );
  19049. if( bufpt[-1]=='.' ){
  19050. if( flag_altform2 ){
  19051. *(bufpt++) = '0';
  19052. }else{
  19053. *(--bufpt) = 0;
  19054. }
  19055. }
  19056. }
  19057. /* Add the "eNNN" suffix */
  19058. if( xtype==etEXP ){
  19059. *(bufpt++) = aDigits[infop->charset];
  19060. if( exp<0 ){
  19061. *(bufpt++) = '-'; exp = -exp;
  19062. }else{
  19063. *(bufpt++) = '+';
  19064. }
  19065. if( exp>=100 ){
  19066. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  19067. exp %= 100;
  19068. }
  19069. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  19070. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  19071. }
  19072. *bufpt = 0;
  19073. /* The converted number is in buf[] and zero terminated. Output it.
  19074. ** Note that the number is in the usual order, not reversed as with
  19075. ** integer conversions. */
  19076. length = (int)(bufpt-zOut);
  19077. bufpt = zOut;
  19078. /* Special case: Add leading zeros if the flag_zeropad flag is
  19079. ** set and we are not left justified */
  19080. if( flag_zeropad && !flag_leftjustify && length < width){
  19081. int i;
  19082. int nPad = width - length;
  19083. for(i=width; i>=nPad; i--){
  19084. bufpt[i] = bufpt[i-nPad];
  19085. }
  19086. i = prefix!=0;
  19087. while( nPad-- ) bufpt[i++] = '0';
  19088. length = width;
  19089. }
  19090. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  19091. break;
  19092. case etSIZE:
  19093. *(va_arg(ap,int*)) = pAccum->nChar;
  19094. length = width = 0;
  19095. break;
  19096. case etPERCENT:
  19097. buf[0] = '%';
  19098. bufpt = buf;
  19099. length = 1;
  19100. break;
  19101. case etCHARX:
  19102. c = va_arg(ap,int);
  19103. buf[0] = (char)c;
  19104. if( precision>=0 ){
  19105. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  19106. length = precision;
  19107. }else{
  19108. length =1;
  19109. }
  19110. bufpt = buf;
  19111. break;
  19112. case etSTRING:
  19113. case etDYNSTRING:
  19114. bufpt = va_arg(ap,char*);
  19115. if( bufpt==0 ){
  19116. bufpt = "";
  19117. }else if( xtype==etDYNSTRING ){
  19118. zExtra = bufpt;
  19119. }
  19120. if( precision>=0 ){
  19121. for(length=0; length<precision && bufpt[length]; length++){}
  19122. }else{
  19123. length = sqlite3Strlen30(bufpt);
  19124. }
  19125. break;
  19126. case etSQLESCAPE:
  19127. case etSQLESCAPE2:
  19128. case etSQLESCAPE3: {
  19129. int i, j, k, n, isnull;
  19130. int needQuote;
  19131. char ch;
  19132. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  19133. char *escarg = va_arg(ap,char*);
  19134. isnull = escarg==0;
  19135. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  19136. k = precision;
  19137. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  19138. if( ch==q ) n++;
  19139. }
  19140. needQuote = !isnull && xtype==etSQLESCAPE2;
  19141. n += i + 1 + needQuote*2;
  19142. if( n>etBUFSIZE ){
  19143. bufpt = zExtra = sqlite3Malloc( n );
  19144. if( bufpt==0 ){
  19145. pAccum->mallocFailed = 1;
  19146. return;
  19147. }
  19148. }else{
  19149. bufpt = buf;
  19150. }
  19151. j = 0;
  19152. if( needQuote ) bufpt[j++] = q;
  19153. k = i;
  19154. for(i=0; i<k; i++){
  19155. bufpt[j++] = ch = escarg[i];
  19156. if( ch==q ) bufpt[j++] = ch;
  19157. }
  19158. if( needQuote ) bufpt[j++] = q;
  19159. bufpt[j] = 0;
  19160. length = j;
  19161. /* The precision in %q and %Q means how many input characters to
  19162. ** consume, not the length of the output...
  19163. ** if( precision>=0 && precision<length ) length = precision; */
  19164. break;
  19165. }
  19166. case etTOKEN: {
  19167. Token *pToken = va_arg(ap, Token*);
  19168. if( pToken ){
  19169. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  19170. }
  19171. length = width = 0;
  19172. break;
  19173. }
  19174. case etSRCLIST: {
  19175. SrcList *pSrc = va_arg(ap, SrcList*);
  19176. int k = va_arg(ap, int);
  19177. struct SrcList_item *pItem = &pSrc->a[k];
  19178. assert( k>=0 && k<pSrc->nSrc );
  19179. if( pItem->zDatabase ){
  19180. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  19181. sqlite3StrAccumAppend(pAccum, ".", 1);
  19182. }
  19183. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  19184. length = width = 0;
  19185. break;
  19186. }
  19187. default: {
  19188. assert( xtype==etINVALID );
  19189. return;
  19190. }
  19191. }/* End switch over the format type */
  19192. /*
  19193. ** The text of the conversion is pointed to by "bufpt" and is
  19194. ** "length" characters long. The field width is "width". Do
  19195. ** the output.
  19196. */
  19197. if( !flag_leftjustify ){
  19198. register int nspace;
  19199. nspace = width-length;
  19200. if( nspace>0 ){
  19201. sqlite3AppendSpace(pAccum, nspace);
  19202. }
  19203. }
  19204. if( length>0 ){
  19205. sqlite3StrAccumAppend(pAccum, bufpt, length);
  19206. }
  19207. if( flag_leftjustify ){
  19208. register int nspace;
  19209. nspace = width-length;
  19210. if( nspace>0 ){
  19211. sqlite3AppendSpace(pAccum, nspace);
  19212. }
  19213. }
  19214. sqlite3_free(zExtra);
  19215. }/* End for loop over the format string */
  19216. } /* End of function */
  19217. /*
  19218. ** Append N bytes of text from z to the StrAccum object.
  19219. */
  19220. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19221. assert( z!=0 || N==0 );
  19222. if( p->tooBig | p->mallocFailed ){
  19223. testcase(p->tooBig);
  19224. testcase(p->mallocFailed);
  19225. return;
  19226. }
  19227. assert( p->zText!=0 || p->nChar==0 );
  19228. if( N<0 ){
  19229. N = sqlite3Strlen30(z);
  19230. }
  19231. if( N==0 || NEVER(z==0) ){
  19232. return;
  19233. }
  19234. if( p->nChar+N >= p->nAlloc ){
  19235. char *zNew;
  19236. if( !p->useMalloc ){
  19237. p->tooBig = 1;
  19238. N = p->nAlloc - p->nChar - 1;
  19239. if( N<=0 ){
  19240. return;
  19241. }
  19242. }else{
  19243. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19244. i64 szNew = p->nChar;
  19245. szNew += N + 1;
  19246. if( szNew > p->mxAlloc ){
  19247. sqlite3StrAccumReset(p);
  19248. p->tooBig = 1;
  19249. return;
  19250. }else{
  19251. p->nAlloc = (int)szNew;
  19252. }
  19253. if( p->useMalloc==1 ){
  19254. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19255. }else{
  19256. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19257. }
  19258. if( zNew ){
  19259. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19260. p->zText = zNew;
  19261. }else{
  19262. p->mallocFailed = 1;
  19263. sqlite3StrAccumReset(p);
  19264. return;
  19265. }
  19266. }
  19267. }
  19268. assert( p->zText );
  19269. memcpy(&p->zText[p->nChar], z, N);
  19270. p->nChar += N;
  19271. }
  19272. /*
  19273. ** Finish off a string by making sure it is zero-terminated.
  19274. ** Return a pointer to the resulting string. Return a NULL
  19275. ** pointer if any kind of error was encountered.
  19276. */
  19277. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19278. if( p->zText ){
  19279. p->zText[p->nChar] = 0;
  19280. if( p->useMalloc && p->zText==p->zBase ){
  19281. if( p->useMalloc==1 ){
  19282. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19283. }else{
  19284. p->zText = sqlite3_malloc(p->nChar+1);
  19285. }
  19286. if( p->zText ){
  19287. memcpy(p->zText, p->zBase, p->nChar+1);
  19288. }else{
  19289. p->mallocFailed = 1;
  19290. }
  19291. }
  19292. }
  19293. return p->zText;
  19294. }
  19295. /*
  19296. ** Reset an StrAccum string. Reclaim all malloced memory.
  19297. */
  19298. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19299. if( p->zText!=p->zBase ){
  19300. if( p->useMalloc==1 ){
  19301. sqlite3DbFree(p->db, p->zText);
  19302. }else{
  19303. sqlite3_free(p->zText);
  19304. }
  19305. }
  19306. p->zText = 0;
  19307. }
  19308. /*
  19309. ** Initialize a string accumulator
  19310. */
  19311. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19312. p->zText = p->zBase = zBase;
  19313. p->db = 0;
  19314. p->nChar = 0;
  19315. p->nAlloc = n;
  19316. p->mxAlloc = mx;
  19317. p->useMalloc = 1;
  19318. p->tooBig = 0;
  19319. p->mallocFailed = 0;
  19320. }
  19321. /*
  19322. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19323. ** %-conversion extensions.
  19324. */
  19325. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19326. char *z;
  19327. char zBase[SQLITE_PRINT_BUF_SIZE];
  19328. StrAccum acc;
  19329. assert( db!=0 );
  19330. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19331. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19332. acc.db = db;
  19333. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19334. z = sqlite3StrAccumFinish(&acc);
  19335. if( acc.mallocFailed ){
  19336. db->mallocFailed = 1;
  19337. }
  19338. return z;
  19339. }
  19340. /*
  19341. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19342. ** %-conversion extensions.
  19343. */
  19344. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19345. va_list ap;
  19346. char *z;
  19347. va_start(ap, zFormat);
  19348. z = sqlite3VMPrintf(db, zFormat, ap);
  19349. va_end(ap);
  19350. return z;
  19351. }
  19352. /*
  19353. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19354. ** the string and before returnning. This routine is intended to be used
  19355. ** to modify an existing string. For example:
  19356. **
  19357. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19358. **
  19359. */
  19360. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19361. va_list ap;
  19362. char *z;
  19363. va_start(ap, zFormat);
  19364. z = sqlite3VMPrintf(db, zFormat, ap);
  19365. va_end(ap);
  19366. sqlite3DbFree(db, zStr);
  19367. return z;
  19368. }
  19369. /*
  19370. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19371. ** %-conversion extensions.
  19372. */
  19373. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19374. char *z;
  19375. char zBase[SQLITE_PRINT_BUF_SIZE];
  19376. StrAccum acc;
  19377. #ifndef SQLITE_OMIT_AUTOINIT
  19378. if( sqlite3_initialize() ) return 0;
  19379. #endif
  19380. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19381. acc.useMalloc = 2;
  19382. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19383. z = sqlite3StrAccumFinish(&acc);
  19384. return z;
  19385. }
  19386. /*
  19387. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19388. ** %-conversion extensions.
  19389. */
  19390. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19391. va_list ap;
  19392. char *z;
  19393. #ifndef SQLITE_OMIT_AUTOINIT
  19394. if( sqlite3_initialize() ) return 0;
  19395. #endif
  19396. va_start(ap, zFormat);
  19397. z = sqlite3_vmprintf(zFormat, ap);
  19398. va_end(ap);
  19399. return z;
  19400. }
  19401. /*
  19402. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19403. ** current locale settings. This is important for SQLite because we
  19404. ** are not able to use a "," as the decimal point in place of "." as
  19405. ** specified by some locales.
  19406. **
  19407. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19408. ** from the snprintf() standard. Unfortunately, it is too late to change
  19409. ** this without breaking compatibility, so we just have to live with the
  19410. ** mistake.
  19411. **
  19412. ** sqlite3_vsnprintf() is the varargs version.
  19413. */
  19414. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19415. StrAccum acc;
  19416. if( n<=0 ) return zBuf;
  19417. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19418. acc.useMalloc = 0;
  19419. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19420. return sqlite3StrAccumFinish(&acc);
  19421. }
  19422. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19423. char *z;
  19424. va_list ap;
  19425. va_start(ap,zFormat);
  19426. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19427. va_end(ap);
  19428. return z;
  19429. }
  19430. /*
  19431. ** This is the routine that actually formats the sqlite3_log() message.
  19432. ** We house it in a separate routine from sqlite3_log() to avoid using
  19433. ** stack space on small-stack systems when logging is disabled.
  19434. **
  19435. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19436. ** allocate memory because it might be called while the memory allocator
  19437. ** mutex is held.
  19438. */
  19439. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19440. StrAccum acc; /* String accumulator */
  19441. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19442. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19443. acc.useMalloc = 0;
  19444. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19445. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19446. sqlite3StrAccumFinish(&acc));
  19447. }
  19448. /*
  19449. ** Format and write a message to the log if logging is enabled.
  19450. */
  19451. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19452. va_list ap; /* Vararg list */
  19453. if( sqlite3GlobalConfig.xLog ){
  19454. va_start(ap, zFormat);
  19455. renderLogMsg(iErrCode, zFormat, ap);
  19456. va_end(ap);
  19457. }
  19458. }
  19459. #if defined(SQLITE_DEBUG)
  19460. /*
  19461. ** A version of printf() that understands %lld. Used for debugging.
  19462. ** The printf() built into some versions of windows does not understand %lld
  19463. ** and segfaults if you give it a long long int.
  19464. */
  19465. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19466. va_list ap;
  19467. StrAccum acc;
  19468. char zBuf[500];
  19469. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19470. acc.useMalloc = 0;
  19471. va_start(ap,zFormat);
  19472. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19473. va_end(ap);
  19474. sqlite3StrAccumFinish(&acc);
  19475. fprintf(stdout,"%s", zBuf);
  19476. fflush(stdout);
  19477. }
  19478. #endif
  19479. #ifndef SQLITE_OMIT_TRACE
  19480. /*
  19481. ** variable-argument wrapper around sqlite3VXPrintf().
  19482. */
  19483. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19484. va_list ap;
  19485. va_start(ap,zFormat);
  19486. sqlite3VXPrintf(p, 1, zFormat, ap);
  19487. va_end(ap);
  19488. }
  19489. #endif
  19490. /************** End of printf.c **********************************************/
  19491. /************** Begin file random.c ******************************************/
  19492. /*
  19493. ** 2001 September 15
  19494. **
  19495. ** The author disclaims copyright to this source code. In place of
  19496. ** a legal notice, here is a blessing:
  19497. **
  19498. ** May you do good and not evil.
  19499. ** May you find forgiveness for yourself and forgive others.
  19500. ** May you share freely, never taking more than you give.
  19501. **
  19502. *************************************************************************
  19503. ** This file contains code to implement a pseudo-random number
  19504. ** generator (PRNG) for SQLite.
  19505. **
  19506. ** Random numbers are used by some of the database backends in order
  19507. ** to generate random integer keys for tables or random filenames.
  19508. */
  19509. /* All threads share a single random number generator.
  19510. ** This structure is the current state of the generator.
  19511. */
  19512. static SQLITE_WSD struct sqlite3PrngType {
  19513. unsigned char isInit; /* True if initialized */
  19514. unsigned char i, j; /* State variables */
  19515. unsigned char s[256]; /* State variables */
  19516. } sqlite3Prng;
  19517. /*
  19518. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  19519. ** must be held while executing this routine.
  19520. **
  19521. ** Why not just use a library random generator like lrand48() for this?
  19522. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  19523. ** good source of random numbers. The lrand48() library function may
  19524. ** well be good enough. But maybe not. Or maybe lrand48() has some
  19525. ** subtle problems on some systems that could cause problems. It is hard
  19526. ** to know. To minimize the risk of problems due to bad lrand48()
  19527. ** implementations, SQLite uses this random number generator based
  19528. ** on RC4, which we know works very well.
  19529. **
  19530. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  19531. ** randomness any more. But we will leave this code in all the same.
  19532. */
  19533. static u8 randomByte(void){
  19534. unsigned char t;
  19535. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19536. ** state vector. If writable static data is unsupported on the target,
  19537. ** we have to locate the state vector at run-time. In the more common
  19538. ** case where writable static data is supported, wsdPrng can refer directly
  19539. ** to the "sqlite3Prng" state vector declared above.
  19540. */
  19541. #ifdef SQLITE_OMIT_WSD
  19542. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19543. # define wsdPrng p[0]
  19544. #else
  19545. # define wsdPrng sqlite3Prng
  19546. #endif
  19547. /* Initialize the state of the random number generator once,
  19548. ** the first time this routine is called. The seed value does
  19549. ** not need to contain a lot of randomness since we are not
  19550. ** trying to do secure encryption or anything like that...
  19551. **
  19552. ** Nothing in this file or anywhere else in SQLite does any kind of
  19553. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19554. ** number generator) not as an encryption device.
  19555. */
  19556. if( !wsdPrng.isInit ){
  19557. int i;
  19558. char k[256];
  19559. wsdPrng.j = 0;
  19560. wsdPrng.i = 0;
  19561. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19562. for(i=0; i<256; i++){
  19563. wsdPrng.s[i] = (u8)i;
  19564. }
  19565. for(i=0; i<256; i++){
  19566. wsdPrng.j += wsdPrng.s[i] + k[i];
  19567. t = wsdPrng.s[wsdPrng.j];
  19568. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19569. wsdPrng.s[i] = t;
  19570. }
  19571. wsdPrng.isInit = 1;
  19572. }
  19573. /* Generate and return single random byte
  19574. */
  19575. wsdPrng.i++;
  19576. t = wsdPrng.s[wsdPrng.i];
  19577. wsdPrng.j += t;
  19578. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19579. wsdPrng.s[wsdPrng.j] = t;
  19580. t += wsdPrng.s[wsdPrng.i];
  19581. return wsdPrng.s[t];
  19582. }
  19583. /*
  19584. ** Return N random bytes.
  19585. */
  19586. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19587. unsigned char *zBuf = pBuf;
  19588. #if SQLITE_THREADSAFE
  19589. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19590. #endif
  19591. sqlite3_mutex_enter(mutex);
  19592. while( N-- ){
  19593. *(zBuf++) = randomByte();
  19594. }
  19595. sqlite3_mutex_leave(mutex);
  19596. }
  19597. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19598. /*
  19599. ** For testing purposes, we sometimes want to preserve the state of
  19600. ** PRNG and restore the PRNG to its saved state at a later time, or
  19601. ** to reset the PRNG to its initial state. These routines accomplish
  19602. ** those tasks.
  19603. **
  19604. ** The sqlite3_test_control() interface calls these routines to
  19605. ** control the PRNG.
  19606. */
  19607. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19608. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19609. memcpy(
  19610. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19611. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19612. sizeof(sqlite3Prng)
  19613. );
  19614. }
  19615. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19616. memcpy(
  19617. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19618. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19619. sizeof(sqlite3Prng)
  19620. );
  19621. }
  19622. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19623. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19624. }
  19625. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19626. /************** End of random.c **********************************************/
  19627. /************** Begin file utf.c *********************************************/
  19628. /*
  19629. ** 2004 April 13
  19630. **
  19631. ** The author disclaims copyright to this source code. In place of
  19632. ** a legal notice, here is a blessing:
  19633. **
  19634. ** May you do good and not evil.
  19635. ** May you find forgiveness for yourself and forgive others.
  19636. ** May you share freely, never taking more than you give.
  19637. **
  19638. *************************************************************************
  19639. ** This file contains routines used to translate between UTF-8,
  19640. ** UTF-16, UTF-16BE, and UTF-16LE.
  19641. **
  19642. ** Notes on UTF-8:
  19643. **
  19644. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  19645. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  19646. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  19647. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  19648. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19649. **
  19650. **
  19651. ** Notes on UTF-16: (with wwww+1==uuuuu)
  19652. **
  19653. ** Word-0 Word-1 Value
  19654. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19655. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  19656. **
  19657. **
  19658. ** BOM or Byte Order Mark:
  19659. ** 0xff 0xfe little-endian utf-16 follows
  19660. ** 0xfe 0xff big-endian utf-16 follows
  19661. **
  19662. */
  19663. /* #include <assert.h> */
  19664. #ifndef SQLITE_AMALGAMATION
  19665. /*
  19666. ** The following constant value is used by the SQLITE_BIGENDIAN and
  19667. ** SQLITE_LITTLEENDIAN macros.
  19668. */
  19669. SQLITE_PRIVATE const int sqlite3one = 1;
  19670. #endif /* SQLITE_AMALGAMATION */
  19671. /*
  19672. ** This lookup table is used to help decode the first byte of
  19673. ** a multi-byte UTF8 character.
  19674. */
  19675. static const unsigned char sqlite3Utf8Trans1[] = {
  19676. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19677. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19678. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  19679. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  19680. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19681. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19682. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19683. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  19684. };
  19685. #define WRITE_UTF8(zOut, c) { \
  19686. if( c<0x00080 ){ \
  19687. *zOut++ = (u8)(c&0xFF); \
  19688. } \
  19689. else if( c<0x00800 ){ \
  19690. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  19691. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19692. } \
  19693. else if( c<0x10000 ){ \
  19694. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  19695. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19696. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19697. }else{ \
  19698. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  19699. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  19700. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19701. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19702. } \
  19703. }
  19704. #define WRITE_UTF16LE(zOut, c) { \
  19705. if( c<=0xFFFF ){ \
  19706. *zOut++ = (u8)(c&0x00FF); \
  19707. *zOut++ = (u8)((c>>8)&0x00FF); \
  19708. }else{ \
  19709. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19710. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19711. *zOut++ = (u8)(c&0x00FF); \
  19712. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19713. } \
  19714. }
  19715. #define WRITE_UTF16BE(zOut, c) { \
  19716. if( c<=0xFFFF ){ \
  19717. *zOut++ = (u8)((c>>8)&0x00FF); \
  19718. *zOut++ = (u8)(c&0x00FF); \
  19719. }else{ \
  19720. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19721. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19722. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19723. *zOut++ = (u8)(c&0x00FF); \
  19724. } \
  19725. }
  19726. #define READ_UTF16LE(zIn, TERM, c){ \
  19727. c = (*zIn++); \
  19728. c += ((*zIn++)<<8); \
  19729. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19730. int c2 = (*zIn++); \
  19731. c2 += ((*zIn++)<<8); \
  19732. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19733. } \
  19734. }
  19735. #define READ_UTF16BE(zIn, TERM, c){ \
  19736. c = ((*zIn++)<<8); \
  19737. c += (*zIn++); \
  19738. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19739. int c2 = ((*zIn++)<<8); \
  19740. c2 += (*zIn++); \
  19741. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19742. } \
  19743. }
  19744. /*
  19745. ** Translate a single UTF-8 character. Return the unicode value.
  19746. **
  19747. ** During translation, assume that the byte that zTerm points
  19748. ** is a 0x00.
  19749. **
  19750. ** Write a pointer to the next unread byte back into *pzNext.
  19751. **
  19752. ** Notes On Invalid UTF-8:
  19753. **
  19754. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  19755. ** be encoded as a multi-byte character. Any multi-byte character that
  19756. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  19757. **
  19758. ** * This routine never allows a UTF16 surrogate value to be encoded.
  19759. ** If a multi-byte character attempts to encode a value between
  19760. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  19761. **
  19762. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  19763. ** byte of a character are interpreted as single-byte characters
  19764. ** and rendered as themselves even though they are technically
  19765. ** invalid characters.
  19766. **
  19767. ** * This routine accepts an infinite number of different UTF8 encodings
  19768. ** for unicode values 0x80 and greater. It do not change over-length
  19769. ** encodings to 0xfffd as some systems recommend.
  19770. */
  19771. #define READ_UTF8(zIn, zTerm, c) \
  19772. c = *(zIn++); \
  19773. if( c>=0xc0 ){ \
  19774. c = sqlite3Utf8Trans1[c-0xc0]; \
  19775. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  19776. c = (c<<6) + (0x3f & *(zIn++)); \
  19777. } \
  19778. if( c<0x80 \
  19779. || (c&0xFFFFF800)==0xD800 \
  19780. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  19781. }
  19782. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  19783. const unsigned char **pz /* Pointer to string from which to read char */
  19784. ){
  19785. unsigned int c;
  19786. /* Same as READ_UTF8() above but without the zTerm parameter.
  19787. ** For this routine, we assume the UTF8 string is always zero-terminated.
  19788. */
  19789. c = *((*pz)++);
  19790. if( c>=0xc0 ){
  19791. c = sqlite3Utf8Trans1[c-0xc0];
  19792. while( (*(*pz) & 0xc0)==0x80 ){
  19793. c = (c<<6) + (0x3f & *((*pz)++));
  19794. }
  19795. if( c<0x80
  19796. || (c&0xFFFFF800)==0xD800
  19797. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  19798. }
  19799. return c;
  19800. }
  19801. /*
  19802. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  19803. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  19804. */
  19805. /* #define TRANSLATE_TRACE 1 */
  19806. #ifndef SQLITE_OMIT_UTF16
  19807. /*
  19808. ** This routine transforms the internal text encoding used by pMem to
  19809. ** desiredEnc. It is an error if the string is already of the desired
  19810. ** encoding, or if *pMem does not contain a string value.
  19811. */
  19812. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  19813. int len; /* Maximum length of output string in bytes */
  19814. unsigned char *zOut; /* Output buffer */
  19815. unsigned char *zIn; /* Input iterator */
  19816. unsigned char *zTerm; /* End of input */
  19817. unsigned char *z; /* Output iterator */
  19818. unsigned int c;
  19819. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  19820. assert( pMem->flags&MEM_Str );
  19821. assert( pMem->enc!=desiredEnc );
  19822. assert( pMem->enc!=0 );
  19823. assert( pMem->n>=0 );
  19824. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19825. {
  19826. char zBuf[100];
  19827. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19828. fprintf(stderr, "INPUT: %s\n", zBuf);
  19829. }
  19830. #endif
  19831. /* If the translation is between UTF-16 little and big endian, then
  19832. ** all that is required is to swap the byte order. This case is handled
  19833. ** differently from the others.
  19834. */
  19835. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  19836. u8 temp;
  19837. int rc;
  19838. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19839. if( rc!=SQLITE_OK ){
  19840. assert( rc==SQLITE_NOMEM );
  19841. return SQLITE_NOMEM;
  19842. }
  19843. zIn = (u8*)pMem->z;
  19844. zTerm = &zIn[pMem->n&~1];
  19845. while( zIn<zTerm ){
  19846. temp = *zIn;
  19847. *zIn = *(zIn+1);
  19848. zIn++;
  19849. *zIn++ = temp;
  19850. }
  19851. pMem->enc = desiredEnc;
  19852. goto translate_out;
  19853. }
  19854. /* Set len to the maximum number of bytes required in the output buffer. */
  19855. if( desiredEnc==SQLITE_UTF8 ){
  19856. /* When converting from UTF-16, the maximum growth results from
  19857. ** translating a 2-byte character to a 4-byte UTF-8 character.
  19858. ** A single byte is required for the output string
  19859. ** nul-terminator.
  19860. */
  19861. pMem->n &= ~1;
  19862. len = pMem->n * 2 + 1;
  19863. }else{
  19864. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  19865. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  19866. ** character. Two bytes are required in the output buffer for the
  19867. ** nul-terminator.
  19868. */
  19869. len = pMem->n * 2 + 2;
  19870. }
  19871. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  19872. ** byte past the end.
  19873. **
  19874. ** Variable zOut is set to point at the output buffer, space obtained
  19875. ** from sqlite3_malloc().
  19876. */
  19877. zIn = (u8*)pMem->z;
  19878. zTerm = &zIn[pMem->n];
  19879. zOut = sqlite3DbMallocRaw(pMem->db, len);
  19880. if( !zOut ){
  19881. return SQLITE_NOMEM;
  19882. }
  19883. z = zOut;
  19884. if( pMem->enc==SQLITE_UTF8 ){
  19885. if( desiredEnc==SQLITE_UTF16LE ){
  19886. /* UTF-8 -> UTF-16 Little-endian */
  19887. while( zIn<zTerm ){
  19888. READ_UTF8(zIn, zTerm, c);
  19889. WRITE_UTF16LE(z, c);
  19890. }
  19891. }else{
  19892. assert( desiredEnc==SQLITE_UTF16BE );
  19893. /* UTF-8 -> UTF-16 Big-endian */
  19894. while( zIn<zTerm ){
  19895. READ_UTF8(zIn, zTerm, c);
  19896. WRITE_UTF16BE(z, c);
  19897. }
  19898. }
  19899. pMem->n = (int)(z - zOut);
  19900. *z++ = 0;
  19901. }else{
  19902. assert( desiredEnc==SQLITE_UTF8 );
  19903. if( pMem->enc==SQLITE_UTF16LE ){
  19904. /* UTF-16 Little-endian -> UTF-8 */
  19905. while( zIn<zTerm ){
  19906. READ_UTF16LE(zIn, zIn<zTerm, c);
  19907. WRITE_UTF8(z, c);
  19908. }
  19909. }else{
  19910. /* UTF-16 Big-endian -> UTF-8 */
  19911. while( zIn<zTerm ){
  19912. READ_UTF16BE(zIn, zIn<zTerm, c);
  19913. WRITE_UTF8(z, c);
  19914. }
  19915. }
  19916. pMem->n = (int)(z - zOut);
  19917. }
  19918. *z = 0;
  19919. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  19920. sqlite3VdbeMemRelease(pMem);
  19921. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  19922. pMem->enc = desiredEnc;
  19923. pMem->flags |= (MEM_Term|MEM_Dyn);
  19924. pMem->z = (char*)zOut;
  19925. pMem->zMalloc = pMem->z;
  19926. translate_out:
  19927. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19928. {
  19929. char zBuf[100];
  19930. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19931. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  19932. }
  19933. #endif
  19934. return SQLITE_OK;
  19935. }
  19936. /*
  19937. ** This routine checks for a byte-order mark at the beginning of the
  19938. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  19939. ** the encoding of the Mem adjusted. This routine does not do any
  19940. ** byte-swapping, it just sets Mem.enc appropriately.
  19941. **
  19942. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  19943. ** changed by this function.
  19944. */
  19945. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  19946. int rc = SQLITE_OK;
  19947. u8 bom = 0;
  19948. assert( pMem->n>=0 );
  19949. if( pMem->n>1 ){
  19950. u8 b1 = *(u8 *)pMem->z;
  19951. u8 b2 = *(((u8 *)pMem->z) + 1);
  19952. if( b1==0xFE && b2==0xFF ){
  19953. bom = SQLITE_UTF16BE;
  19954. }
  19955. if( b1==0xFF && b2==0xFE ){
  19956. bom = SQLITE_UTF16LE;
  19957. }
  19958. }
  19959. if( bom ){
  19960. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19961. if( rc==SQLITE_OK ){
  19962. pMem->n -= 2;
  19963. memmove(pMem->z, &pMem->z[2], pMem->n);
  19964. pMem->z[pMem->n] = '\0';
  19965. pMem->z[pMem->n+1] = '\0';
  19966. pMem->flags |= MEM_Term;
  19967. pMem->enc = bom;
  19968. }
  19969. }
  19970. return rc;
  19971. }
  19972. #endif /* SQLITE_OMIT_UTF16 */
  19973. /*
  19974. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  19975. ** return the number of unicode characters in pZ up to (but not including)
  19976. ** the first 0x00 byte. If nByte is not less than zero, return the
  19977. ** number of unicode characters in the first nByte of pZ (or up to
  19978. ** the first 0x00, whichever comes first).
  19979. */
  19980. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  19981. int r = 0;
  19982. const u8 *z = (const u8*)zIn;
  19983. const u8 *zTerm;
  19984. if( nByte>=0 ){
  19985. zTerm = &z[nByte];
  19986. }else{
  19987. zTerm = (const u8*)(-1);
  19988. }
  19989. assert( z<=zTerm );
  19990. while( *z!=0 && z<zTerm ){
  19991. SQLITE_SKIP_UTF8(z);
  19992. r++;
  19993. }
  19994. return r;
  19995. }
  19996. /* This test function is not currently used by the automated test-suite.
  19997. ** Hence it is only available in debug builds.
  19998. */
  19999. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  20000. /*
  20001. ** Translate UTF-8 to UTF-8.
  20002. **
  20003. ** This has the effect of making sure that the string is well-formed
  20004. ** UTF-8. Miscoded characters are removed.
  20005. **
  20006. ** The translation is done in-place and aborted if the output
  20007. ** overruns the input.
  20008. */
  20009. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  20010. unsigned char *zOut = zIn;
  20011. unsigned char *zStart = zIn;
  20012. u32 c;
  20013. while( zIn[0] && zOut<=zIn ){
  20014. c = sqlite3Utf8Read((const u8**)&zIn);
  20015. if( c!=0xfffd ){
  20016. WRITE_UTF8(zOut, c);
  20017. }
  20018. }
  20019. *zOut = 0;
  20020. return (int)(zOut - zStart);
  20021. }
  20022. #endif
  20023. #ifndef SQLITE_OMIT_UTF16
  20024. /*
  20025. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  20026. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  20027. ** be freed by the calling function.
  20028. **
  20029. ** NULL is returned if there is an allocation error.
  20030. */
  20031. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  20032. Mem m;
  20033. memset(&m, 0, sizeof(m));
  20034. m.db = db;
  20035. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  20036. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  20037. if( db->mallocFailed ){
  20038. sqlite3VdbeMemRelease(&m);
  20039. m.z = 0;
  20040. }
  20041. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  20042. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  20043. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  20044. assert( m.z || db->mallocFailed );
  20045. return m.z;
  20046. }
  20047. /*
  20048. ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
  20049. ** enc. A pointer to the new string is returned, and the value of *pnOut
  20050. ** is set to the length of the returned string in bytes. The call should
  20051. ** arrange to call sqlite3DbFree() on the returned pointer when it is
  20052. ** no longer required.
  20053. **
  20054. ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
  20055. ** flag set.
  20056. */
  20057. #ifdef SQLITE_ENABLE_STAT3
  20058. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
  20059. Mem m;
  20060. memset(&m, 0, sizeof(m));
  20061. m.db = db;
  20062. sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
  20063. if( sqlite3VdbeMemTranslate(&m, enc) ){
  20064. assert( db->mallocFailed );
  20065. return 0;
  20066. }
  20067. assert( m.z==m.zMalloc );
  20068. *pnOut = m.n;
  20069. return m.z;
  20070. }
  20071. #endif
  20072. /*
  20073. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  20074. ** Return the number of bytes in the first nChar unicode characters
  20075. ** in pZ. nChar must be non-negative.
  20076. */
  20077. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  20078. int c;
  20079. unsigned char const *z = zIn;
  20080. int n = 0;
  20081. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  20082. while( n<nChar ){
  20083. READ_UTF16BE(z, 1, c);
  20084. n++;
  20085. }
  20086. }else{
  20087. while( n<nChar ){
  20088. READ_UTF16LE(z, 1, c);
  20089. n++;
  20090. }
  20091. }
  20092. return (int)(z-(unsigned char const *)zIn);
  20093. }
  20094. #if defined(SQLITE_TEST)
  20095. /*
  20096. ** This routine is called from the TCL test function "translate_selftest".
  20097. ** It checks that the primitives for serializing and deserializing
  20098. ** characters in each encoding are inverses of each other.
  20099. */
  20100. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  20101. unsigned int i, t;
  20102. unsigned char zBuf[20];
  20103. unsigned char *z;
  20104. int n;
  20105. unsigned int c;
  20106. for(i=0; i<0x00110000; i++){
  20107. z = zBuf;
  20108. WRITE_UTF8(z, i);
  20109. n = (int)(z-zBuf);
  20110. assert( n>0 && n<=4 );
  20111. z[0] = 0;
  20112. z = zBuf;
  20113. c = sqlite3Utf8Read((const u8**)&z);
  20114. t = i;
  20115. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  20116. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  20117. assert( c==t );
  20118. assert( (z-zBuf)==n );
  20119. }
  20120. for(i=0; i<0x00110000; i++){
  20121. if( i>=0xD800 && i<0xE000 ) continue;
  20122. z = zBuf;
  20123. WRITE_UTF16LE(z, i);
  20124. n = (int)(z-zBuf);
  20125. assert( n>0 && n<=4 );
  20126. z[0] = 0;
  20127. z = zBuf;
  20128. READ_UTF16LE(z, 1, c);
  20129. assert( c==i );
  20130. assert( (z-zBuf)==n );
  20131. }
  20132. for(i=0; i<0x00110000; i++){
  20133. if( i>=0xD800 && i<0xE000 ) continue;
  20134. z = zBuf;
  20135. WRITE_UTF16BE(z, i);
  20136. n = (int)(z-zBuf);
  20137. assert( n>0 && n<=4 );
  20138. z[0] = 0;
  20139. z = zBuf;
  20140. READ_UTF16BE(z, 1, c);
  20141. assert( c==i );
  20142. assert( (z-zBuf)==n );
  20143. }
  20144. }
  20145. #endif /* SQLITE_TEST */
  20146. #endif /* SQLITE_OMIT_UTF16 */
  20147. /************** End of utf.c *************************************************/
  20148. /************** Begin file util.c ********************************************/
  20149. /*
  20150. ** 2001 September 15
  20151. **
  20152. ** The author disclaims copyright to this source code. In place of
  20153. ** a legal notice, here is a blessing:
  20154. **
  20155. ** May you do good and not evil.
  20156. ** May you find forgiveness for yourself and forgive others.
  20157. ** May you share freely, never taking more than you give.
  20158. **
  20159. *************************************************************************
  20160. ** Utility functions used throughout sqlite.
  20161. **
  20162. ** This file contains functions for allocating memory, comparing
  20163. ** strings, and stuff like that.
  20164. **
  20165. */
  20166. /* #include <stdarg.h> */
  20167. #ifdef SQLITE_HAVE_ISNAN
  20168. # include <math.h>
  20169. #endif
  20170. /*
  20171. ** Routine needed to support the testcase() macro.
  20172. */
  20173. #ifdef SQLITE_COVERAGE_TEST
  20174. SQLITE_PRIVATE void sqlite3Coverage(int x){
  20175. static unsigned dummy = 0;
  20176. dummy += (unsigned)x;
  20177. }
  20178. #endif
  20179. #ifndef SQLITE_OMIT_FLOATING_POINT
  20180. /*
  20181. ** Return true if the floating point value is Not a Number (NaN).
  20182. **
  20183. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  20184. ** Otherwise, we have our own implementation that works on most systems.
  20185. */
  20186. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  20187. int rc; /* The value return */
  20188. #if !defined(SQLITE_HAVE_ISNAN)
  20189. /*
  20190. ** Systems that support the isnan() library function should probably
  20191. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  20192. ** found that many systems do not have a working isnan() function so
  20193. ** this implementation is provided as an alternative.
  20194. **
  20195. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  20196. ** On the other hand, the use of -ffast-math comes with the following
  20197. ** warning:
  20198. **
  20199. ** This option [-ffast-math] should never be turned on by any
  20200. ** -O option since it can result in incorrect output for programs
  20201. ** which depend on an exact implementation of IEEE or ISO
  20202. ** rules/specifications for math functions.
  20203. **
  20204. ** Under MSVC, this NaN test may fail if compiled with a floating-
  20205. ** point precision mode other than /fp:precise. From the MSDN
  20206. ** documentation:
  20207. **
  20208. ** The compiler [with /fp:precise] will properly handle comparisons
  20209. ** involving NaN. For example, x != x evaluates to true if x is NaN
  20210. ** ...
  20211. */
  20212. #ifdef __FAST_MATH__
  20213. # error SQLite will not work correctly with the -ffast-math option of GCC.
  20214. #endif
  20215. volatile double y = x;
  20216. volatile double z = y;
  20217. rc = (y!=z);
  20218. #else /* if defined(SQLITE_HAVE_ISNAN) */
  20219. rc = isnan(x);
  20220. #endif /* SQLITE_HAVE_ISNAN */
  20221. testcase( rc );
  20222. return rc;
  20223. }
  20224. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20225. /*
  20226. ** Compute a string length that is limited to what can be stored in
  20227. ** lower 30 bits of a 32-bit signed integer.
  20228. **
  20229. ** The value returned will never be negative. Nor will it ever be greater
  20230. ** than the actual length of the string. For very long strings (greater
  20231. ** than 1GiB) the value returned might be less than the true string length.
  20232. */
  20233. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  20234. const char *z2 = z;
  20235. if( z==0 ) return 0;
  20236. while( *z2 ){ z2++; }
  20237. return 0x3fffffff & (int)(z2 - z);
  20238. }
  20239. /*
  20240. ** Set the most recent error code and error string for the sqlite
  20241. ** handle "db". The error code is set to "err_code".
  20242. **
  20243. ** If it is not NULL, string zFormat specifies the format of the
  20244. ** error string in the style of the printf functions: The following
  20245. ** format characters are allowed:
  20246. **
  20247. ** %s Insert a string
  20248. ** %z A string that should be freed after use
  20249. ** %d Insert an integer
  20250. ** %T Insert a token
  20251. ** %S Insert the first element of a SrcList
  20252. **
  20253. ** zFormat and any string tokens that follow it are assumed to be
  20254. ** encoded in UTF-8.
  20255. **
  20256. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20257. ** should be called with err_code set to SQLITE_OK and zFormat set
  20258. ** to NULL.
  20259. */
  20260. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20261. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20262. db->errCode = err_code;
  20263. if( zFormat ){
  20264. char *z;
  20265. va_list ap;
  20266. va_start(ap, zFormat);
  20267. z = sqlite3VMPrintf(db, zFormat, ap);
  20268. va_end(ap);
  20269. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20270. }else{
  20271. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20272. }
  20273. }
  20274. }
  20275. /*
  20276. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20277. ** The following formatting characters are allowed:
  20278. **
  20279. ** %s Insert a string
  20280. ** %z A string that should be freed after use
  20281. ** %d Insert an integer
  20282. ** %T Insert a token
  20283. ** %S Insert the first element of a SrcList
  20284. **
  20285. ** This function should be used to report any error that occurs whilst
  20286. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20287. ** last thing the sqlite3_prepare() function does is copy the error
  20288. ** stored by this function into the database handle using sqlite3Error().
  20289. ** Function sqlite3Error() should be used during statement execution
  20290. ** (sqlite3_step() etc.).
  20291. */
  20292. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20293. char *zMsg;
  20294. va_list ap;
  20295. sqlite3 *db = pParse->db;
  20296. va_start(ap, zFormat);
  20297. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20298. va_end(ap);
  20299. if( db->suppressErr ){
  20300. sqlite3DbFree(db, zMsg);
  20301. }else{
  20302. pParse->nErr++;
  20303. sqlite3DbFree(db, pParse->zErrMsg);
  20304. pParse->zErrMsg = zMsg;
  20305. pParse->rc = SQLITE_ERROR;
  20306. }
  20307. }
  20308. /*
  20309. ** Convert an SQL-style quoted string into a normal string by removing
  20310. ** the quote characters. The conversion is done in-place. If the
  20311. ** input does not begin with a quote character, then this routine
  20312. ** is a no-op.
  20313. **
  20314. ** The input string must be zero-terminated. A new zero-terminator
  20315. ** is added to the dequoted string.
  20316. **
  20317. ** The return value is -1 if no dequoting occurs or the length of the
  20318. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20319. ** occur.
  20320. **
  20321. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20322. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20323. ** "a-b-c".
  20324. */
  20325. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20326. char quote;
  20327. int i, j;
  20328. if( z==0 ) return -1;
  20329. quote = z[0];
  20330. switch( quote ){
  20331. case '\'': break;
  20332. case '"': break;
  20333. case '`': break; /* For MySQL compatibility */
  20334. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20335. default: return -1;
  20336. }
  20337. for(i=1, j=0; ALWAYS(z[i]); i++){
  20338. if( z[i]==quote ){
  20339. if( z[i+1]==quote ){
  20340. z[j++] = quote;
  20341. i++;
  20342. }else{
  20343. break;
  20344. }
  20345. }else{
  20346. z[j++] = z[i];
  20347. }
  20348. }
  20349. z[j] = 0;
  20350. return j;
  20351. }
  20352. /* Convenient short-hand */
  20353. #define UpperToLower sqlite3UpperToLower
  20354. /*
  20355. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20356. ** there is no consistency, we will define our own.
  20357. **
  20358. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20359. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20360. ** the contents of two buffers containing UTF-8 strings in a
  20361. ** case-independent fashion, using the same definition of "case
  20362. ** independence" that SQLite uses internally when comparing identifiers.
  20363. */
  20364. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20365. register unsigned char *a, *b;
  20366. a = (unsigned char *)zLeft;
  20367. b = (unsigned char *)zRight;
  20368. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20369. return UpperToLower[*a] - UpperToLower[*b];
  20370. }
  20371. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20372. register unsigned char *a, *b;
  20373. a = (unsigned char *)zLeft;
  20374. b = (unsigned char *)zRight;
  20375. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20376. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20377. }
  20378. /*
  20379. ** The string z[] is an text representation of a real number.
  20380. ** Convert this string to a double and write it into *pResult.
  20381. **
  20382. ** The string z[] is length bytes in length (bytes, not characters) and
  20383. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20384. **
  20385. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20386. ** if the string is empty or contains extraneous text. Valid numbers
  20387. ** are in one of these formats:
  20388. **
  20389. ** [+-]digits[E[+-]digits]
  20390. ** [+-]digits.[digits][E[+-]digits]
  20391. ** [+-].digits[E[+-]digits]
  20392. **
  20393. ** Leading and trailing whitespace is ignored for the purpose of determining
  20394. ** validity.
  20395. **
  20396. ** If some prefix of the input string is a valid number, this routine
  20397. ** returns FALSE but it still converts the prefix and writes the result
  20398. ** into *pResult.
  20399. */
  20400. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20401. #ifndef SQLITE_OMIT_FLOATING_POINT
  20402. int incr;
  20403. const char *zEnd = z + length;
  20404. /* sign * significand * (10 ^ (esign * exponent)) */
  20405. int sign = 1; /* sign of significand */
  20406. i64 s = 0; /* significand */
  20407. int d = 0; /* adjust exponent for shifting decimal point */
  20408. int esign = 1; /* sign of exponent */
  20409. int e = 0; /* exponent */
  20410. int eValid = 1; /* True exponent is either not used or is well-formed */
  20411. double result;
  20412. int nDigits = 0;
  20413. int nonNum = 0;
  20414. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20415. *pResult = 0.0; /* Default return value, in case of an error */
  20416. if( enc==SQLITE_UTF8 ){
  20417. incr = 1;
  20418. }else{
  20419. int i;
  20420. incr = 2;
  20421. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20422. for(i=3-enc; i<length && z[i]==0; i+=2){}
  20423. nonNum = i<length;
  20424. zEnd = z+i+enc-3;
  20425. z += (enc&1);
  20426. }
  20427. /* skip leading spaces */
  20428. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20429. if( z>=zEnd ) return 0;
  20430. /* get sign of significand */
  20431. if( *z=='-' ){
  20432. sign = -1;
  20433. z+=incr;
  20434. }else if( *z=='+' ){
  20435. z+=incr;
  20436. }
  20437. /* skip leading zeroes */
  20438. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20439. /* copy max significant digits to significand */
  20440. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20441. s = s*10 + (*z - '0');
  20442. z+=incr, nDigits++;
  20443. }
  20444. /* skip non-significant significand digits
  20445. ** (increase exponent by d to shift decimal left) */
  20446. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20447. if( z>=zEnd ) goto do_atof_calc;
  20448. /* if decimal point is present */
  20449. if( *z=='.' ){
  20450. z+=incr;
  20451. /* copy digits from after decimal to significand
  20452. ** (decrease exponent by d to shift decimal right) */
  20453. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20454. s = s*10 + (*z - '0');
  20455. z+=incr, nDigits++, d--;
  20456. }
  20457. /* skip non-significant digits */
  20458. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20459. }
  20460. if( z>=zEnd ) goto do_atof_calc;
  20461. /* if exponent is present */
  20462. if( *z=='e' || *z=='E' ){
  20463. z+=incr;
  20464. eValid = 0;
  20465. if( z>=zEnd ) goto do_atof_calc;
  20466. /* get sign of exponent */
  20467. if( *z=='-' ){
  20468. esign = -1;
  20469. z+=incr;
  20470. }else if( *z=='+' ){
  20471. z+=incr;
  20472. }
  20473. /* copy digits to exponent */
  20474. while( z<zEnd && sqlite3Isdigit(*z) ){
  20475. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20476. z+=incr;
  20477. eValid = 1;
  20478. }
  20479. }
  20480. /* skip trailing spaces */
  20481. if( nDigits && eValid ){
  20482. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20483. }
  20484. do_atof_calc:
  20485. /* adjust exponent by d, and update sign */
  20486. e = (e*esign) + d;
  20487. if( e<0 ) {
  20488. esign = -1;
  20489. e *= -1;
  20490. } else {
  20491. esign = 1;
  20492. }
  20493. /* if 0 significand */
  20494. if( !s ) {
  20495. /* In the IEEE 754 standard, zero is signed.
  20496. ** Add the sign if we've seen at least one digit */
  20497. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20498. } else {
  20499. /* attempt to reduce exponent */
  20500. if( esign>0 ){
  20501. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20502. }else{
  20503. while( !(s%10) && e>0 ) e--,s/=10;
  20504. }
  20505. /* adjust the sign of significand */
  20506. s = sign<0 ? -s : s;
  20507. /* if exponent, scale significand as appropriate
  20508. ** and store in result. */
  20509. if( e ){
  20510. LONGDOUBLE_TYPE scale = 1.0;
  20511. /* attempt to handle extremely small/large numbers better */
  20512. if( e>307 && e<342 ){
  20513. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20514. if( esign<0 ){
  20515. result = s / scale;
  20516. result /= 1.0e+308;
  20517. }else{
  20518. result = s * scale;
  20519. result *= 1.0e+308;
  20520. }
  20521. }else if( e>=342 ){
  20522. if( esign<0 ){
  20523. result = 0.0*s;
  20524. }else{
  20525. result = 1e308*1e308*s; /* Infinity */
  20526. }
  20527. }else{
  20528. /* 1.0e+22 is the largest power of 10 than can be
  20529. ** represented exactly. */
  20530. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20531. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20532. if( esign<0 ){
  20533. result = s / scale;
  20534. }else{
  20535. result = s * scale;
  20536. }
  20537. }
  20538. } else {
  20539. result = (double)s;
  20540. }
  20541. }
  20542. /* store the result */
  20543. *pResult = result;
  20544. /* return true if number and no extra non-whitespace chracters after */
  20545. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  20546. #else
  20547. return !sqlite3Atoi64(z, pResult, length, enc);
  20548. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20549. }
  20550. /*
  20551. ** Compare the 19-character string zNum against the text representation
  20552. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20553. ** if zNum is less than, equal to, or greater than the string.
  20554. ** Note that zNum must contain exactly 19 characters.
  20555. **
  20556. ** Unlike memcmp() this routine is guaranteed to return the difference
  20557. ** in the values of the last digit if the only difference is in the
  20558. ** last digit. So, for example,
  20559. **
  20560. ** compare2pow63("9223372036854775800", 1)
  20561. **
  20562. ** will return -8.
  20563. */
  20564. static int compare2pow63(const char *zNum, int incr){
  20565. int c = 0;
  20566. int i;
  20567. /* 012345678901234567 */
  20568. const char *pow63 = "922337203685477580";
  20569. for(i=0; c==0 && i<18; i++){
  20570. c = (zNum[i*incr]-pow63[i])*10;
  20571. }
  20572. if( c==0 ){
  20573. c = zNum[18*incr] - '8';
  20574. testcase( c==(-1) );
  20575. testcase( c==0 );
  20576. testcase( c==(+1) );
  20577. }
  20578. return c;
  20579. }
  20580. /*
  20581. ** Convert zNum to a 64-bit signed integer.
  20582. **
  20583. ** If the zNum value is representable as a 64-bit twos-complement
  20584. ** integer, then write that value into *pNum and return 0.
  20585. **
  20586. ** If zNum is exactly 9223372036854665808, return 2. This special
  20587. ** case is broken out because while 9223372036854665808 cannot be a
  20588. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20589. **
  20590. ** If zNum is too big for a 64-bit integer and is not
  20591. ** 9223372036854665808 or if zNum contains any non-numeric text,
  20592. ** then return 1.
  20593. **
  20594. ** length is the number of bytes in the string (bytes, not characters).
  20595. ** The string is not necessarily zero-terminated. The encoding is
  20596. ** given by enc.
  20597. */
  20598. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20599. int incr;
  20600. u64 u = 0;
  20601. int neg = 0; /* assume positive */
  20602. int i;
  20603. int c = 0;
  20604. int nonNum = 0;
  20605. const char *zStart;
  20606. const char *zEnd = zNum + length;
  20607. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20608. if( enc==SQLITE_UTF8 ){
  20609. incr = 1;
  20610. }else{
  20611. incr = 2;
  20612. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20613. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  20614. nonNum = i<length;
  20615. zEnd = zNum+i+enc-3;
  20616. zNum += (enc&1);
  20617. }
  20618. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20619. if( zNum<zEnd ){
  20620. if( *zNum=='-' ){
  20621. neg = 1;
  20622. zNum+=incr;
  20623. }else if( *zNum=='+' ){
  20624. zNum+=incr;
  20625. }
  20626. }
  20627. zStart = zNum;
  20628. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20629. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20630. u = u*10 + c - '0';
  20631. }
  20632. if( u>LARGEST_INT64 ){
  20633. *pNum = SMALLEST_INT64;
  20634. }else if( neg ){
  20635. *pNum = -(i64)u;
  20636. }else{
  20637. *pNum = (i64)u;
  20638. }
  20639. testcase( i==18 );
  20640. testcase( i==19 );
  20641. testcase( i==20 );
  20642. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  20643. /* zNum is empty or contains non-numeric text or is longer
  20644. ** than 19 digits (thus guaranteeing that it is too large) */
  20645. return 1;
  20646. }else if( i<19*incr ){
  20647. /* Less than 19 digits, so we know that it fits in 64 bits */
  20648. assert( u<=LARGEST_INT64 );
  20649. return 0;
  20650. }else{
  20651. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20652. c = compare2pow63(zNum, incr);
  20653. if( c<0 ){
  20654. /* zNum is less than 9223372036854775808 so it fits */
  20655. assert( u<=LARGEST_INT64 );
  20656. return 0;
  20657. }else if( c>0 ){
  20658. /* zNum is greater than 9223372036854775808 so it overflows */
  20659. return 1;
  20660. }else{
  20661. /* zNum is exactly 9223372036854775808. Fits if negative. The
  20662. ** special case 2 overflow if positive */
  20663. assert( u-1==LARGEST_INT64 );
  20664. assert( (*pNum)==SMALLEST_INT64 );
  20665. return neg ? 0 : 2;
  20666. }
  20667. }
  20668. }
  20669. /*
  20670. ** If zNum represents an integer that will fit in 32-bits, then set
  20671. ** *pValue to that integer and return true. Otherwise return false.
  20672. **
  20673. ** Any non-numeric characters that following zNum are ignored.
  20674. ** This is different from sqlite3Atoi64() which requires the
  20675. ** input number to be zero-terminated.
  20676. */
  20677. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  20678. sqlite_int64 v = 0;
  20679. int i, c;
  20680. int neg = 0;
  20681. if( zNum[0]=='-' ){
  20682. neg = 1;
  20683. zNum++;
  20684. }else if( zNum[0]=='+' ){
  20685. zNum++;
  20686. }
  20687. while( zNum[0]=='0' ) zNum++;
  20688. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  20689. v = v*10 + c;
  20690. }
  20691. /* The longest decimal representation of a 32 bit integer is 10 digits:
  20692. **
  20693. ** 1234567890
  20694. ** 2^31 -> 2147483648
  20695. */
  20696. testcase( i==10 );
  20697. if( i>10 ){
  20698. return 0;
  20699. }
  20700. testcase( v-neg==2147483647 );
  20701. if( v-neg>2147483647 ){
  20702. return 0;
  20703. }
  20704. if( neg ){
  20705. v = -v;
  20706. }
  20707. *pValue = (int)v;
  20708. return 1;
  20709. }
  20710. /*
  20711. ** Return a 32-bit integer value extracted from a string. If the
  20712. ** string is not an integer, just return 0.
  20713. */
  20714. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  20715. int x = 0;
  20716. if( z ) sqlite3GetInt32(z, &x);
  20717. return x;
  20718. }
  20719. /*
  20720. ** The variable-length integer encoding is as follows:
  20721. **
  20722. ** KEY:
  20723. ** A = 0xxxxxxx 7 bits of data and one flag bit
  20724. ** B = 1xxxxxxx 7 bits of data and one flag bit
  20725. ** C = xxxxxxxx 8 bits of data
  20726. **
  20727. ** 7 bits - A
  20728. ** 14 bits - BA
  20729. ** 21 bits - BBA
  20730. ** 28 bits - BBBA
  20731. ** 35 bits - BBBBA
  20732. ** 42 bits - BBBBBA
  20733. ** 49 bits - BBBBBBA
  20734. ** 56 bits - BBBBBBBA
  20735. ** 64 bits - BBBBBBBBC
  20736. */
  20737. /*
  20738. ** Write a 64-bit variable-length integer to memory starting at p[0].
  20739. ** The length of data write will be between 1 and 9 bytes. The number
  20740. ** of bytes written is returned.
  20741. **
  20742. ** A variable-length integer consists of the lower 7 bits of each byte
  20743. ** for all bytes that have the 8th bit set and one byte with the 8th
  20744. ** bit clear. Except, if we get to the 9th byte, it stores the full
  20745. ** 8 bits and is the last byte.
  20746. */
  20747. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  20748. int i, j, n;
  20749. u8 buf[10];
  20750. if( v & (((u64)0xff000000)<<32) ){
  20751. p[8] = (u8)v;
  20752. v >>= 8;
  20753. for(i=7; i>=0; i--){
  20754. p[i] = (u8)((v & 0x7f) | 0x80);
  20755. v >>= 7;
  20756. }
  20757. return 9;
  20758. }
  20759. n = 0;
  20760. do{
  20761. buf[n++] = (u8)((v & 0x7f) | 0x80);
  20762. v >>= 7;
  20763. }while( v!=0 );
  20764. buf[0] &= 0x7f;
  20765. assert( n<=9 );
  20766. for(i=0, j=n-1; j>=0; j--, i++){
  20767. p[i] = buf[j];
  20768. }
  20769. return n;
  20770. }
  20771. /*
  20772. ** This routine is a faster version of sqlite3PutVarint() that only
  20773. ** works for 32-bit positive integers and which is optimized for
  20774. ** the common case of small integers. A MACRO version, putVarint32,
  20775. ** is provided which inlines the single-byte case. All code should use
  20776. ** the MACRO version as this function assumes the single-byte case has
  20777. ** already been handled.
  20778. */
  20779. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  20780. #ifndef putVarint32
  20781. if( (v & ~0x7f)==0 ){
  20782. p[0] = v;
  20783. return 1;
  20784. }
  20785. #endif
  20786. if( (v & ~0x3fff)==0 ){
  20787. p[0] = (u8)((v>>7) | 0x80);
  20788. p[1] = (u8)(v & 0x7f);
  20789. return 2;
  20790. }
  20791. return sqlite3PutVarint(p, v);
  20792. }
  20793. /*
  20794. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  20795. ** are defined here rather than simply putting the constant expressions
  20796. ** inline in order to work around bugs in the RVT compiler.
  20797. **
  20798. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  20799. **
  20800. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  20801. */
  20802. #define SLOT_2_0 0x001fc07f
  20803. #define SLOT_4_2_0 0xf01fc07f
  20804. /*
  20805. ** Read a 64-bit variable-length integer from memory starting at p[0].
  20806. ** Return the number of bytes read. The value is stored in *v.
  20807. */
  20808. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  20809. u32 a,b,s;
  20810. a = *p;
  20811. /* a: p0 (unmasked) */
  20812. if (!(a&0x80))
  20813. {
  20814. *v = a;
  20815. return 1;
  20816. }
  20817. p++;
  20818. b = *p;
  20819. /* b: p1 (unmasked) */
  20820. if (!(b&0x80))
  20821. {
  20822. a &= 0x7f;
  20823. a = a<<7;
  20824. a |= b;
  20825. *v = a;
  20826. return 2;
  20827. }
  20828. /* Verify that constants are precomputed correctly */
  20829. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  20830. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  20831. p++;
  20832. a = a<<14;
  20833. a |= *p;
  20834. /* a: p0<<14 | p2 (unmasked) */
  20835. if (!(a&0x80))
  20836. {
  20837. a &= SLOT_2_0;
  20838. b &= 0x7f;
  20839. b = b<<7;
  20840. a |= b;
  20841. *v = a;
  20842. return 3;
  20843. }
  20844. /* CSE1 from below */
  20845. a &= SLOT_2_0;
  20846. p++;
  20847. b = b<<14;
  20848. b |= *p;
  20849. /* b: p1<<14 | p3 (unmasked) */
  20850. if (!(b&0x80))
  20851. {
  20852. b &= SLOT_2_0;
  20853. /* moved CSE1 up */
  20854. /* a &= (0x7f<<14)|(0x7f); */
  20855. a = a<<7;
  20856. a |= b;
  20857. *v = a;
  20858. return 4;
  20859. }
  20860. /* a: p0<<14 | p2 (masked) */
  20861. /* b: p1<<14 | p3 (unmasked) */
  20862. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20863. /* moved CSE1 up */
  20864. /* a &= (0x7f<<14)|(0x7f); */
  20865. b &= SLOT_2_0;
  20866. s = a;
  20867. /* s: p0<<14 | p2 (masked) */
  20868. p++;
  20869. a = a<<14;
  20870. a |= *p;
  20871. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20872. if (!(a&0x80))
  20873. {
  20874. /* we can skip these cause they were (effectively) done above in calc'ing s */
  20875. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20876. /* b &= (0x7f<<14)|(0x7f); */
  20877. b = b<<7;
  20878. a |= b;
  20879. s = s>>18;
  20880. *v = ((u64)s)<<32 | a;
  20881. return 5;
  20882. }
  20883. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20884. s = s<<7;
  20885. s |= b;
  20886. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20887. p++;
  20888. b = b<<14;
  20889. b |= *p;
  20890. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  20891. if (!(b&0x80))
  20892. {
  20893. /* we can skip this cause it was (effectively) done above in calc'ing s */
  20894. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20895. a &= SLOT_2_0;
  20896. a = a<<7;
  20897. a |= b;
  20898. s = s>>18;
  20899. *v = ((u64)s)<<32 | a;
  20900. return 6;
  20901. }
  20902. p++;
  20903. a = a<<14;
  20904. a |= *p;
  20905. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  20906. if (!(a&0x80))
  20907. {
  20908. a &= SLOT_4_2_0;
  20909. b &= SLOT_2_0;
  20910. b = b<<7;
  20911. a |= b;
  20912. s = s>>11;
  20913. *v = ((u64)s)<<32 | a;
  20914. return 7;
  20915. }
  20916. /* CSE2 from below */
  20917. a &= SLOT_2_0;
  20918. p++;
  20919. b = b<<14;
  20920. b |= *p;
  20921. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  20922. if (!(b&0x80))
  20923. {
  20924. b &= SLOT_4_2_0;
  20925. /* moved CSE2 up */
  20926. /* a &= (0x7f<<14)|(0x7f); */
  20927. a = a<<7;
  20928. a |= b;
  20929. s = s>>4;
  20930. *v = ((u64)s)<<32 | a;
  20931. return 8;
  20932. }
  20933. p++;
  20934. a = a<<15;
  20935. a |= *p;
  20936. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  20937. /* moved CSE2 up */
  20938. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  20939. b &= SLOT_2_0;
  20940. b = b<<8;
  20941. a |= b;
  20942. s = s<<4;
  20943. b = p[-4];
  20944. b &= 0x7f;
  20945. b = b>>3;
  20946. s |= b;
  20947. *v = ((u64)s)<<32 | a;
  20948. return 9;
  20949. }
  20950. /*
  20951. ** Read a 32-bit variable-length integer from memory starting at p[0].
  20952. ** Return the number of bytes read. The value is stored in *v.
  20953. **
  20954. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  20955. ** integer, then set *v to 0xffffffff.
  20956. **
  20957. ** A MACRO version, getVarint32, is provided which inlines the
  20958. ** single-byte case. All code should use the MACRO version as
  20959. ** this function assumes the single-byte case has already been handled.
  20960. */
  20961. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  20962. u32 a,b;
  20963. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  20964. ** by the getVarin32() macro */
  20965. a = *p;
  20966. /* a: p0 (unmasked) */
  20967. #ifndef getVarint32
  20968. if (!(a&0x80))
  20969. {
  20970. /* Values between 0 and 127 */
  20971. *v = a;
  20972. return 1;
  20973. }
  20974. #endif
  20975. /* The 2-byte case */
  20976. p++;
  20977. b = *p;
  20978. /* b: p1 (unmasked) */
  20979. if (!(b&0x80))
  20980. {
  20981. /* Values between 128 and 16383 */
  20982. a &= 0x7f;
  20983. a = a<<7;
  20984. *v = a | b;
  20985. return 2;
  20986. }
  20987. /* The 3-byte case */
  20988. p++;
  20989. a = a<<14;
  20990. a |= *p;
  20991. /* a: p0<<14 | p2 (unmasked) */
  20992. if (!(a&0x80))
  20993. {
  20994. /* Values between 16384 and 2097151 */
  20995. a &= (0x7f<<14)|(0x7f);
  20996. b &= 0x7f;
  20997. b = b<<7;
  20998. *v = a | b;
  20999. return 3;
  21000. }
  21001. /* A 32-bit varint is used to store size information in btrees.
  21002. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  21003. ** A 3-byte varint is sufficient, for example, to record the size
  21004. ** of a 1048569-byte BLOB or string.
  21005. **
  21006. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  21007. ** rare larger cases can be handled by the slower 64-bit varint
  21008. ** routine.
  21009. */
  21010. #if 1
  21011. {
  21012. u64 v64;
  21013. u8 n;
  21014. p -= 2;
  21015. n = sqlite3GetVarint(p, &v64);
  21016. assert( n>3 && n<=9 );
  21017. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  21018. *v = 0xffffffff;
  21019. }else{
  21020. *v = (u32)v64;
  21021. }
  21022. return n;
  21023. }
  21024. #else
  21025. /* For following code (kept for historical record only) shows an
  21026. ** unrolling for the 3- and 4-byte varint cases. This code is
  21027. ** slightly faster, but it is also larger and much harder to test.
  21028. */
  21029. p++;
  21030. b = b<<14;
  21031. b |= *p;
  21032. /* b: p1<<14 | p3 (unmasked) */
  21033. if (!(b&0x80))
  21034. {
  21035. /* Values between 2097152 and 268435455 */
  21036. b &= (0x7f<<14)|(0x7f);
  21037. a &= (0x7f<<14)|(0x7f);
  21038. a = a<<7;
  21039. *v = a | b;
  21040. return 4;
  21041. }
  21042. p++;
  21043. a = a<<14;
  21044. a |= *p;
  21045. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21046. if (!(a&0x80))
  21047. {
  21048. /* Values between 268435456 and 34359738367 */
  21049. a &= SLOT_4_2_0;
  21050. b &= SLOT_4_2_0;
  21051. b = b<<7;
  21052. *v = a | b;
  21053. return 5;
  21054. }
  21055. /* We can only reach this point when reading a corrupt database
  21056. ** file. In that case we are not in any hurry. Use the (relatively
  21057. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  21058. ** value. */
  21059. {
  21060. u64 v64;
  21061. u8 n;
  21062. p -= 4;
  21063. n = sqlite3GetVarint(p, &v64);
  21064. assert( n>5 && n<=9 );
  21065. *v = (u32)v64;
  21066. return n;
  21067. }
  21068. #endif
  21069. }
  21070. /*
  21071. ** Return the number of bytes that will be needed to store the given
  21072. ** 64-bit integer.
  21073. */
  21074. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  21075. int i = 0;
  21076. do{
  21077. i++;
  21078. v >>= 7;
  21079. }while( v!=0 && ALWAYS(i<9) );
  21080. return i;
  21081. }
  21082. /*
  21083. ** Read or write a four-byte big-endian integer value.
  21084. */
  21085. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  21086. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  21087. }
  21088. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  21089. p[0] = (u8)(v>>24);
  21090. p[1] = (u8)(v>>16);
  21091. p[2] = (u8)(v>>8);
  21092. p[3] = (u8)v;
  21093. }
  21094. /*
  21095. ** Translate a single byte of Hex into an integer.
  21096. ** This routine only works if h really is a valid hexadecimal
  21097. ** character: 0..9a..fA..F
  21098. */
  21099. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  21100. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  21101. #ifdef SQLITE_ASCII
  21102. h += 9*(1&(h>>6));
  21103. #endif
  21104. #ifdef SQLITE_EBCDIC
  21105. h += 9*(1&~(h>>4));
  21106. #endif
  21107. return (u8)(h & 0xf);
  21108. }
  21109. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  21110. /*
  21111. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  21112. ** value. Return a pointer to its binary value. Space to hold the
  21113. ** binary value has been obtained from malloc and must be freed by
  21114. ** the calling routine.
  21115. */
  21116. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  21117. char *zBlob;
  21118. int i;
  21119. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  21120. n--;
  21121. if( zBlob ){
  21122. for(i=0; i<n; i+=2){
  21123. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  21124. }
  21125. zBlob[i/2] = 0;
  21126. }
  21127. return zBlob;
  21128. }
  21129. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  21130. /*
  21131. ** Log an error that is an API call on a connection pointer that should
  21132. ** not have been used. The "type" of connection pointer is given as the
  21133. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  21134. */
  21135. static void logBadConnection(const char *zType){
  21136. sqlite3_log(SQLITE_MISUSE,
  21137. "API call with %s database connection pointer",
  21138. zType
  21139. );
  21140. }
  21141. /*
  21142. ** Check to make sure we have a valid db pointer. This test is not
  21143. ** foolproof but it does provide some measure of protection against
  21144. ** misuse of the interface such as passing in db pointers that are
  21145. ** NULL or which have been previously closed. If this routine returns
  21146. ** 1 it means that the db pointer is valid and 0 if it should not be
  21147. ** dereferenced for any reason. The calling function should invoke
  21148. ** SQLITE_MISUSE immediately.
  21149. **
  21150. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  21151. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  21152. ** open properly and is not fit for general use but which can be
  21153. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  21154. */
  21155. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  21156. u32 magic;
  21157. if( db==0 ){
  21158. logBadConnection("NULL");
  21159. return 0;
  21160. }
  21161. magic = db->magic;
  21162. if( magic!=SQLITE_MAGIC_OPEN ){
  21163. if( sqlite3SafetyCheckSickOrOk(db) ){
  21164. testcase( sqlite3GlobalConfig.xLog!=0 );
  21165. logBadConnection("unopened");
  21166. }
  21167. return 0;
  21168. }else{
  21169. return 1;
  21170. }
  21171. }
  21172. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  21173. u32 magic;
  21174. magic = db->magic;
  21175. if( magic!=SQLITE_MAGIC_SICK &&
  21176. magic!=SQLITE_MAGIC_OPEN &&
  21177. magic!=SQLITE_MAGIC_BUSY ){
  21178. testcase( sqlite3GlobalConfig.xLog!=0 );
  21179. logBadConnection("invalid");
  21180. return 0;
  21181. }else{
  21182. return 1;
  21183. }
  21184. }
  21185. /*
  21186. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  21187. ** the other 64-bit signed integer at *pA and store the result in *pA.
  21188. ** Return 0 on success. Or if the operation would have resulted in an
  21189. ** overflow, leave *pA unchanged and return 1.
  21190. */
  21191. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  21192. i64 iA = *pA;
  21193. testcase( iA==0 ); testcase( iA==1 );
  21194. testcase( iB==-1 ); testcase( iB==0 );
  21195. if( iB>=0 ){
  21196. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  21197. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  21198. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  21199. *pA += iB;
  21200. }else{
  21201. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  21202. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  21203. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  21204. *pA += iB;
  21205. }
  21206. return 0;
  21207. }
  21208. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  21209. testcase( iB==SMALLEST_INT64+1 );
  21210. if( iB==SMALLEST_INT64 ){
  21211. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  21212. if( (*pA)>=0 ) return 1;
  21213. *pA -= iB;
  21214. return 0;
  21215. }else{
  21216. return sqlite3AddInt64(pA, -iB);
  21217. }
  21218. }
  21219. #define TWOPOWER32 (((i64)1)<<32)
  21220. #define TWOPOWER31 (((i64)1)<<31)
  21221. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  21222. i64 iA = *pA;
  21223. i64 iA1, iA0, iB1, iB0, r;
  21224. iA1 = iA/TWOPOWER32;
  21225. iA0 = iA % TWOPOWER32;
  21226. iB1 = iB/TWOPOWER32;
  21227. iB0 = iB % TWOPOWER32;
  21228. if( iA1*iB1 != 0 ) return 1;
  21229. assert( iA1*iB0==0 || iA0*iB1==0 );
  21230. r = iA1*iB0 + iA0*iB1;
  21231. testcase( r==(-TWOPOWER31)-1 );
  21232. testcase( r==(-TWOPOWER31) );
  21233. testcase( r==TWOPOWER31 );
  21234. testcase( r==TWOPOWER31-1 );
  21235. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  21236. r *= TWOPOWER32;
  21237. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  21238. *pA = r;
  21239. return 0;
  21240. }
  21241. /*
  21242. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  21243. ** if the integer has a value of -2147483648, return +2147483647
  21244. */
  21245. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  21246. if( x>=0 ) return x;
  21247. if( x==(int)0x80000000 ) return 0x7fffffff;
  21248. return -x;
  21249. }
  21250. #ifdef SQLITE_ENABLE_8_3_NAMES
  21251. /*
  21252. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  21253. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  21254. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  21255. ** three characters, then shorten the suffix on z[] to be the last three
  21256. ** characters of the original suffix.
  21257. **
  21258. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  21259. ** do the suffix shortening regardless of URI parameter.
  21260. **
  21261. ** Examples:
  21262. **
  21263. ** test.db-journal => test.nal
  21264. ** test.db-wal => test.wal
  21265. ** test.db-shm => test.shm
  21266. ** test.db-mj7f3319fa => test.9fa
  21267. */
  21268. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21269. #if SQLITE_ENABLE_8_3_NAMES<2
  21270. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21271. #endif
  21272. {
  21273. int i, sz;
  21274. sz = sqlite3Strlen30(z);
  21275. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21276. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21277. }
  21278. }
  21279. #endif
  21280. /************** End of util.c ************************************************/
  21281. /************** Begin file hash.c ********************************************/
  21282. /*
  21283. ** 2001 September 22
  21284. **
  21285. ** The author disclaims copyright to this source code. In place of
  21286. ** a legal notice, here is a blessing:
  21287. **
  21288. ** May you do good and not evil.
  21289. ** May you find forgiveness for yourself and forgive others.
  21290. ** May you share freely, never taking more than you give.
  21291. **
  21292. *************************************************************************
  21293. ** This is the implementation of generic hash-tables
  21294. ** used in SQLite.
  21295. */
  21296. /* #include <assert.h> */
  21297. /* Turn bulk memory into a hash table object by initializing the
  21298. ** fields of the Hash structure.
  21299. **
  21300. ** "pNew" is a pointer to the hash table that is to be initialized.
  21301. */
  21302. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21303. assert( pNew!=0 );
  21304. pNew->first = 0;
  21305. pNew->count = 0;
  21306. pNew->htsize = 0;
  21307. pNew->ht = 0;
  21308. }
  21309. /* Remove all entries from a hash table. Reclaim all memory.
  21310. ** Call this routine to delete a hash table or to reset a hash table
  21311. ** to the empty state.
  21312. */
  21313. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21314. HashElem *elem; /* For looping over all elements of the table */
  21315. assert( pH!=0 );
  21316. elem = pH->first;
  21317. pH->first = 0;
  21318. sqlite3_free(pH->ht);
  21319. pH->ht = 0;
  21320. pH->htsize = 0;
  21321. while( elem ){
  21322. HashElem *next_elem = elem->next;
  21323. sqlite3_free(elem);
  21324. elem = next_elem;
  21325. }
  21326. pH->count = 0;
  21327. }
  21328. /*
  21329. ** The hashing function.
  21330. */
  21331. static unsigned int strHash(const char *z, int nKey){
  21332. int h = 0;
  21333. assert( nKey>=0 );
  21334. while( nKey > 0 ){
  21335. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21336. nKey--;
  21337. }
  21338. return h;
  21339. }
  21340. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21341. ** insert pNew into the pEntry hash bucket.
  21342. */
  21343. static void insertElement(
  21344. Hash *pH, /* The complete hash table */
  21345. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21346. HashElem *pNew /* The element to be inserted */
  21347. ){
  21348. HashElem *pHead; /* First element already in pEntry */
  21349. if( pEntry ){
  21350. pHead = pEntry->count ? pEntry->chain : 0;
  21351. pEntry->count++;
  21352. pEntry->chain = pNew;
  21353. }else{
  21354. pHead = 0;
  21355. }
  21356. if( pHead ){
  21357. pNew->next = pHead;
  21358. pNew->prev = pHead->prev;
  21359. if( pHead->prev ){ pHead->prev->next = pNew; }
  21360. else { pH->first = pNew; }
  21361. pHead->prev = pNew;
  21362. }else{
  21363. pNew->next = pH->first;
  21364. if( pH->first ){ pH->first->prev = pNew; }
  21365. pNew->prev = 0;
  21366. pH->first = pNew;
  21367. }
  21368. }
  21369. /* Resize the hash table so that it cantains "new_size" buckets.
  21370. **
  21371. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21372. ** if the new size is the same as the prior size.
  21373. ** Return TRUE if the resize occurs and false if not.
  21374. */
  21375. static int rehash(Hash *pH, unsigned int new_size){
  21376. struct _ht *new_ht; /* The new hash table */
  21377. HashElem *elem, *next_elem; /* For looping over existing elements */
  21378. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21379. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21380. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21381. }
  21382. if( new_size==pH->htsize ) return 0;
  21383. #endif
  21384. /* The inability to allocates space for a larger hash table is
  21385. ** a performance hit but it is not a fatal error. So mark the
  21386. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21387. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21388. ** only zeroes the requested number of bytes whereas this module will
  21389. ** use the actual amount of space allocated for the hash table (which
  21390. ** may be larger than the requested amount).
  21391. */
  21392. sqlite3BeginBenignMalloc();
  21393. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21394. sqlite3EndBenignMalloc();
  21395. if( new_ht==0 ) return 0;
  21396. sqlite3_free(pH->ht);
  21397. pH->ht = new_ht;
  21398. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21399. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21400. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21401. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21402. next_elem = elem->next;
  21403. insertElement(pH, &new_ht[h], elem);
  21404. }
  21405. return 1;
  21406. }
  21407. /* This function (for internal use only) locates an element in an
  21408. ** hash table that matches the given key. The hash for this key has
  21409. ** already been computed and is passed as the 4th parameter.
  21410. */
  21411. static HashElem *findElementGivenHash(
  21412. const Hash *pH, /* The pH to be searched */
  21413. const char *pKey, /* The key we are searching for */
  21414. int nKey, /* Bytes in key (not counting zero terminator) */
  21415. unsigned int h /* The hash for this key. */
  21416. ){
  21417. HashElem *elem; /* Used to loop thru the element list */
  21418. int count; /* Number of elements left to test */
  21419. if( pH->ht ){
  21420. struct _ht *pEntry = &pH->ht[h];
  21421. elem = pEntry->chain;
  21422. count = pEntry->count;
  21423. }else{
  21424. elem = pH->first;
  21425. count = pH->count;
  21426. }
  21427. while( count-- && ALWAYS(elem) ){
  21428. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21429. return elem;
  21430. }
  21431. elem = elem->next;
  21432. }
  21433. return 0;
  21434. }
  21435. /* Remove a single entry from the hash table given a pointer to that
  21436. ** element and a hash on the element's key.
  21437. */
  21438. static void removeElementGivenHash(
  21439. Hash *pH, /* The pH containing "elem" */
  21440. HashElem* elem, /* The element to be removed from the pH */
  21441. unsigned int h /* Hash value for the element */
  21442. ){
  21443. struct _ht *pEntry;
  21444. if( elem->prev ){
  21445. elem->prev->next = elem->next;
  21446. }else{
  21447. pH->first = elem->next;
  21448. }
  21449. if( elem->next ){
  21450. elem->next->prev = elem->prev;
  21451. }
  21452. if( pH->ht ){
  21453. pEntry = &pH->ht[h];
  21454. if( pEntry->chain==elem ){
  21455. pEntry->chain = elem->next;
  21456. }
  21457. pEntry->count--;
  21458. assert( pEntry->count>=0 );
  21459. }
  21460. sqlite3_free( elem );
  21461. pH->count--;
  21462. if( pH->count==0 ){
  21463. assert( pH->first==0 );
  21464. assert( pH->count==0 );
  21465. sqlite3HashClear(pH);
  21466. }
  21467. }
  21468. /* Attempt to locate an element of the hash table pH with a key
  21469. ** that matches pKey,nKey. Return the data for this element if it is
  21470. ** found, or NULL if there is no match.
  21471. */
  21472. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21473. HashElem *elem; /* The element that matches key */
  21474. unsigned int h; /* A hash on key */
  21475. assert( pH!=0 );
  21476. assert( pKey!=0 );
  21477. assert( nKey>=0 );
  21478. if( pH->ht ){
  21479. h = strHash(pKey, nKey) % pH->htsize;
  21480. }else{
  21481. h = 0;
  21482. }
  21483. elem = findElementGivenHash(pH, pKey, nKey, h);
  21484. return elem ? elem->data : 0;
  21485. }
  21486. /* Insert an element into the hash table pH. The key is pKey,nKey
  21487. ** and the data is "data".
  21488. **
  21489. ** If no element exists with a matching key, then a new
  21490. ** element is created and NULL is returned.
  21491. **
  21492. ** If another element already exists with the same key, then the
  21493. ** new data replaces the old data and the old data is returned.
  21494. ** The key is not copied in this instance. If a malloc fails, then
  21495. ** the new data is returned and the hash table is unchanged.
  21496. **
  21497. ** If the "data" parameter to this function is NULL, then the
  21498. ** element corresponding to "key" is removed from the hash table.
  21499. */
  21500. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21501. unsigned int h; /* the hash of the key modulo hash table size */
  21502. HashElem *elem; /* Used to loop thru the element list */
  21503. HashElem *new_elem; /* New element added to the pH */
  21504. assert( pH!=0 );
  21505. assert( pKey!=0 );
  21506. assert( nKey>=0 );
  21507. if( pH->htsize ){
  21508. h = strHash(pKey, nKey) % pH->htsize;
  21509. }else{
  21510. h = 0;
  21511. }
  21512. elem = findElementGivenHash(pH,pKey,nKey,h);
  21513. if( elem ){
  21514. void *old_data = elem->data;
  21515. if( data==0 ){
  21516. removeElementGivenHash(pH,elem,h);
  21517. }else{
  21518. elem->data = data;
  21519. elem->pKey = pKey;
  21520. assert(nKey==elem->nKey);
  21521. }
  21522. return old_data;
  21523. }
  21524. if( data==0 ) return 0;
  21525. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21526. if( new_elem==0 ) return data;
  21527. new_elem->pKey = pKey;
  21528. new_elem->nKey = nKey;
  21529. new_elem->data = data;
  21530. pH->count++;
  21531. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21532. if( rehash(pH, pH->count*2) ){
  21533. assert( pH->htsize>0 );
  21534. h = strHash(pKey, nKey) % pH->htsize;
  21535. }
  21536. }
  21537. if( pH->ht ){
  21538. insertElement(pH, &pH->ht[h], new_elem);
  21539. }else{
  21540. insertElement(pH, 0, new_elem);
  21541. }
  21542. return 0;
  21543. }
  21544. /************** End of hash.c ************************************************/
  21545. /************** Begin file opcodes.c *****************************************/
  21546. /* Automatically generated. Do not edit */
  21547. /* See the mkopcodec.awk script for details. */
  21548. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21549. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21550. static const char *const azName[] = { "?",
  21551. /* 1 */ "Goto",
  21552. /* 2 */ "Gosub",
  21553. /* 3 */ "Return",
  21554. /* 4 */ "Yield",
  21555. /* 5 */ "HaltIfNull",
  21556. /* 6 */ "Halt",
  21557. /* 7 */ "Integer",
  21558. /* 8 */ "Int64",
  21559. /* 9 */ "String",
  21560. /* 10 */ "Null",
  21561. /* 11 */ "Blob",
  21562. /* 12 */ "Variable",
  21563. /* 13 */ "Move",
  21564. /* 14 */ "Copy",
  21565. /* 15 */ "SCopy",
  21566. /* 16 */ "ResultRow",
  21567. /* 17 */ "CollSeq",
  21568. /* 18 */ "Function",
  21569. /* 19 */ "Not",
  21570. /* 20 */ "AddImm",
  21571. /* 21 */ "MustBeInt",
  21572. /* 22 */ "RealAffinity",
  21573. /* 23 */ "Permutation",
  21574. /* 24 */ "Compare",
  21575. /* 25 */ "Jump",
  21576. /* 26 */ "Once",
  21577. /* 27 */ "If",
  21578. /* 28 */ "IfNot",
  21579. /* 29 */ "Column",
  21580. /* 30 */ "Affinity",
  21581. /* 31 */ "MakeRecord",
  21582. /* 32 */ "Count",
  21583. /* 33 */ "Savepoint",
  21584. /* 34 */ "AutoCommit",
  21585. /* 35 */ "Transaction",
  21586. /* 36 */ "ReadCookie",
  21587. /* 37 */ "SetCookie",
  21588. /* 38 */ "VerifyCookie",
  21589. /* 39 */ "OpenRead",
  21590. /* 40 */ "OpenWrite",
  21591. /* 41 */ "OpenAutoindex",
  21592. /* 42 */ "OpenEphemeral",
  21593. /* 43 */ "SorterOpen",
  21594. /* 44 */ "OpenPseudo",
  21595. /* 45 */ "Close",
  21596. /* 46 */ "SeekLt",
  21597. /* 47 */ "SeekLe",
  21598. /* 48 */ "SeekGe",
  21599. /* 49 */ "SeekGt",
  21600. /* 50 */ "Seek",
  21601. /* 51 */ "NotFound",
  21602. /* 52 */ "Found",
  21603. /* 53 */ "IsUnique",
  21604. /* 54 */ "NotExists",
  21605. /* 55 */ "Sequence",
  21606. /* 56 */ "NewRowid",
  21607. /* 57 */ "Insert",
  21608. /* 58 */ "InsertInt",
  21609. /* 59 */ "Delete",
  21610. /* 60 */ "ResetCount",
  21611. /* 61 */ "SorterCompare",
  21612. /* 62 */ "SorterData",
  21613. /* 63 */ "RowKey",
  21614. /* 64 */ "RowData",
  21615. /* 65 */ "Rowid",
  21616. /* 66 */ "NullRow",
  21617. /* 67 */ "Last",
  21618. /* 68 */ "Or",
  21619. /* 69 */ "And",
  21620. /* 70 */ "SorterSort",
  21621. /* 71 */ "Sort",
  21622. /* 72 */ "Rewind",
  21623. /* 73 */ "IsNull",
  21624. /* 74 */ "NotNull",
  21625. /* 75 */ "Ne",
  21626. /* 76 */ "Eq",
  21627. /* 77 */ "Gt",
  21628. /* 78 */ "Le",
  21629. /* 79 */ "Lt",
  21630. /* 80 */ "Ge",
  21631. /* 81 */ "SorterNext",
  21632. /* 82 */ "BitAnd",
  21633. /* 83 */ "BitOr",
  21634. /* 84 */ "ShiftLeft",
  21635. /* 85 */ "ShiftRight",
  21636. /* 86 */ "Add",
  21637. /* 87 */ "Subtract",
  21638. /* 88 */ "Multiply",
  21639. /* 89 */ "Divide",
  21640. /* 90 */ "Remainder",
  21641. /* 91 */ "Concat",
  21642. /* 92 */ "Prev",
  21643. /* 93 */ "BitNot",
  21644. /* 94 */ "String8",
  21645. /* 95 */ "Next",
  21646. /* 96 */ "SorterInsert",
  21647. /* 97 */ "IdxInsert",
  21648. /* 98 */ "IdxDelete",
  21649. /* 99 */ "IdxRowid",
  21650. /* 100 */ "IdxLT",
  21651. /* 101 */ "IdxGE",
  21652. /* 102 */ "Destroy",
  21653. /* 103 */ "Clear",
  21654. /* 104 */ "CreateIndex",
  21655. /* 105 */ "CreateTable",
  21656. /* 106 */ "ParseSchema",
  21657. /* 107 */ "LoadAnalysis",
  21658. /* 108 */ "DropTable",
  21659. /* 109 */ "DropIndex",
  21660. /* 110 */ "DropTrigger",
  21661. /* 111 */ "IntegrityCk",
  21662. /* 112 */ "RowSetAdd",
  21663. /* 113 */ "RowSetRead",
  21664. /* 114 */ "RowSetTest",
  21665. /* 115 */ "Program",
  21666. /* 116 */ "Param",
  21667. /* 117 */ "FkCounter",
  21668. /* 118 */ "FkIfZero",
  21669. /* 119 */ "MemMax",
  21670. /* 120 */ "IfPos",
  21671. /* 121 */ "IfNeg",
  21672. /* 122 */ "IfZero",
  21673. /* 123 */ "AggStep",
  21674. /* 124 */ "AggFinal",
  21675. /* 125 */ "Checkpoint",
  21676. /* 126 */ "JournalMode",
  21677. /* 127 */ "Vacuum",
  21678. /* 128 */ "IncrVacuum",
  21679. /* 129 */ "Expire",
  21680. /* 130 */ "Real",
  21681. /* 131 */ "TableLock",
  21682. /* 132 */ "VBegin",
  21683. /* 133 */ "VCreate",
  21684. /* 134 */ "VDestroy",
  21685. /* 135 */ "VOpen",
  21686. /* 136 */ "VFilter",
  21687. /* 137 */ "VColumn",
  21688. /* 138 */ "VNext",
  21689. /* 139 */ "VRename",
  21690. /* 140 */ "VUpdate",
  21691. /* 141 */ "ToText",
  21692. /* 142 */ "ToBlob",
  21693. /* 143 */ "ToNumeric",
  21694. /* 144 */ "ToInt",
  21695. /* 145 */ "ToReal",
  21696. /* 146 */ "Pagecount",
  21697. /* 147 */ "MaxPgcnt",
  21698. /* 148 */ "Trace",
  21699. /* 149 */ "Noop",
  21700. /* 150 */ "Explain",
  21701. };
  21702. return azName[i];
  21703. }
  21704. #endif
  21705. /************** End of opcodes.c *********************************************/
  21706. /************** Begin file os_unix.c *****************************************/
  21707. /*
  21708. ** 2004 May 22
  21709. **
  21710. ** The author disclaims copyright to this source code. In place of
  21711. ** a legal notice, here is a blessing:
  21712. **
  21713. ** May you do good and not evil.
  21714. ** May you find forgiveness for yourself and forgive others.
  21715. ** May you share freely, never taking more than you give.
  21716. **
  21717. ******************************************************************************
  21718. **
  21719. ** This file contains the VFS implementation for unix-like operating systems
  21720. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  21721. **
  21722. ** There are actually several different VFS implementations in this file.
  21723. ** The differences are in the way that file locking is done. The default
  21724. ** implementation uses Posix Advisory Locks. Alternative implementations
  21725. ** use flock(), dot-files, various proprietary locking schemas, or simply
  21726. ** skip locking all together.
  21727. **
  21728. ** This source file is organized into divisions where the logic for various
  21729. ** subfunctions is contained within the appropriate division. PLEASE
  21730. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  21731. ** in the correct division and should be clearly labeled.
  21732. **
  21733. ** The layout of divisions is as follows:
  21734. **
  21735. ** * General-purpose declarations and utility functions.
  21736. ** * Unique file ID logic used by VxWorks.
  21737. ** * Various locking primitive implementations (all except proxy locking):
  21738. ** + for Posix Advisory Locks
  21739. ** + for no-op locks
  21740. ** + for dot-file locks
  21741. ** + for flock() locking
  21742. ** + for named semaphore locks (VxWorks only)
  21743. ** + for AFP filesystem locks (MacOSX only)
  21744. ** * sqlite3_file methods not associated with locking.
  21745. ** * Definitions of sqlite3_io_methods objects for all locking
  21746. ** methods plus "finder" functions for each locking method.
  21747. ** * sqlite3_vfs method implementations.
  21748. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  21749. ** * Definitions of sqlite3_vfs objects for all locking methods
  21750. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  21751. */
  21752. #if SQLITE_OS_UNIX /* This file is used on unix only */
  21753. /* Use posix_fallocate() if it is available
  21754. */
  21755. #if !defined(HAVE_POSIX_FALLOCATE) \
  21756. && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
  21757. # define HAVE_POSIX_FALLOCATE 1
  21758. #endif
  21759. /*
  21760. ** There are various methods for file locking used for concurrency
  21761. ** control:
  21762. **
  21763. ** 1. POSIX locking (the default),
  21764. ** 2. No locking,
  21765. ** 3. Dot-file locking,
  21766. ** 4. flock() locking,
  21767. ** 5. AFP locking (OSX only),
  21768. ** 6. Named POSIX semaphores (VXWorks only),
  21769. ** 7. proxy locking. (OSX only)
  21770. **
  21771. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  21772. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  21773. ** selection of the appropriate locking style based on the filesystem
  21774. ** where the database is located.
  21775. */
  21776. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  21777. # if defined(__APPLE__)
  21778. # define SQLITE_ENABLE_LOCKING_STYLE 1
  21779. # else
  21780. # define SQLITE_ENABLE_LOCKING_STYLE 0
  21781. # endif
  21782. #endif
  21783. /*
  21784. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  21785. ** vxworks, or 0 otherwise.
  21786. */
  21787. #ifndef OS_VXWORKS
  21788. # if defined(__RTP__) || defined(_WRS_KERNEL)
  21789. # define OS_VXWORKS 1
  21790. # else
  21791. # define OS_VXWORKS 0
  21792. # endif
  21793. #endif
  21794. /*
  21795. ** These #defines should enable >2GB file support on Posix if the
  21796. ** underlying operating system supports it. If the OS lacks
  21797. ** large file support, these should be no-ops.
  21798. **
  21799. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  21800. ** on the compiler command line. This is necessary if you are compiling
  21801. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  21802. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  21803. ** without this option, LFS is enable. But LFS does not exist in the kernel
  21804. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  21805. ** portability you should omit LFS.
  21806. **
  21807. ** The previous paragraph was written in 2005. (This paragraph is written
  21808. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  21809. ** you should probably leave LFS enabled. But some embedded platforms might
  21810. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  21811. */
  21812. #ifndef SQLITE_DISABLE_LFS
  21813. # define _LARGE_FILE 1
  21814. # ifndef _FILE_OFFSET_BITS
  21815. # define _FILE_OFFSET_BITS 64
  21816. # endif
  21817. # define _LARGEFILE_SOURCE 1
  21818. #endif
  21819. /*
  21820. ** standard include files.
  21821. */
  21822. #include <sys/types.h>
  21823. #include <sys/stat.h>
  21824. #include <fcntl.h>
  21825. #include <unistd.h>
  21826. /* #include <time.h> */
  21827. #include <sys/time.h>
  21828. #include <errno.h>
  21829. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  21830. #include <sys/mman.h>
  21831. #endif
  21832. #if SQLITE_ENABLE_LOCKING_STYLE
  21833. # include <sys/ioctl.h>
  21834. # if OS_VXWORKS
  21835. # include <semaphore.h>
  21836. # include <limits.h>
  21837. # else
  21838. # include <sys/file.h>
  21839. # include <sys/param.h>
  21840. # endif
  21841. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  21842. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  21843. # include <sys/mount.h>
  21844. #endif
  21845. #ifdef HAVE_UTIME
  21846. # include <utime.h>
  21847. #endif
  21848. /*
  21849. ** Allowed values of unixFile.fsFlags
  21850. */
  21851. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  21852. /*
  21853. ** If we are to be thread-safe, include the pthreads header and define
  21854. ** the SQLITE_UNIX_THREADS macro.
  21855. */
  21856. #if SQLITE_THREADSAFE
  21857. /* # include <pthread.h> */
  21858. # define SQLITE_UNIX_THREADS 1
  21859. #endif
  21860. /*
  21861. ** Default permissions when creating a new file
  21862. */
  21863. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  21864. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  21865. #endif
  21866. /*
  21867. ** Default permissions when creating auto proxy dir
  21868. */
  21869. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  21870. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  21871. #endif
  21872. /*
  21873. ** Maximum supported path-length.
  21874. */
  21875. #define MAX_PATHNAME 512
  21876. /*
  21877. ** Only set the lastErrno if the error code is a real error and not
  21878. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  21879. */
  21880. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  21881. /* Forward references */
  21882. typedef struct unixShm unixShm; /* Connection shared memory */
  21883. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  21884. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  21885. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  21886. /*
  21887. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  21888. ** cannot be closed immediately. In these cases, instances of the following
  21889. ** structure are used to store the file descriptor while waiting for an
  21890. ** opportunity to either close or reuse it.
  21891. */
  21892. struct UnixUnusedFd {
  21893. int fd; /* File descriptor to close */
  21894. int flags; /* Flags this file descriptor was opened with */
  21895. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  21896. };
  21897. /*
  21898. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  21899. ** VFS implementations.
  21900. */
  21901. typedef struct unixFile unixFile;
  21902. struct unixFile {
  21903. sqlite3_io_methods const *pMethod; /* Always the first entry */
  21904. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  21905. unixInodeInfo *pInode; /* Info about locks on this inode */
  21906. int h; /* The file descriptor */
  21907. unsigned char eFileLock; /* The type of lock held on this fd */
  21908. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  21909. int lastErrno; /* The unix errno from last I/O error */
  21910. void *lockingContext; /* Locking style specific state */
  21911. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  21912. const char *zPath; /* Name of the file */
  21913. unixShm *pShm; /* Shared memory segment information */
  21914. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  21915. int nFetchOut; /* Number of outstanding xFetch refs */
  21916. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  21917. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  21918. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  21919. void *pMapRegion; /* Memory mapped region */
  21920. #ifdef __QNXNTO__
  21921. int sectorSize; /* Device sector size */
  21922. int deviceCharacteristics; /* Precomputed device characteristics */
  21923. #endif
  21924. #if SQLITE_ENABLE_LOCKING_STYLE
  21925. int openFlags; /* The flags specified at open() */
  21926. #endif
  21927. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  21928. unsigned fsFlags; /* cached details from statfs() */
  21929. #endif
  21930. #if OS_VXWORKS
  21931. struct vxworksFileId *pId; /* Unique file ID */
  21932. #endif
  21933. #ifdef SQLITE_DEBUG
  21934. /* The next group of variables are used to track whether or not the
  21935. ** transaction counter in bytes 24-27 of database files are updated
  21936. ** whenever any part of the database changes. An assertion fault will
  21937. ** occur if a file is updated without also updating the transaction
  21938. ** counter. This test is made to avoid new problems similar to the
  21939. ** one described by ticket #3584.
  21940. */
  21941. unsigned char transCntrChng; /* True if the transaction counter changed */
  21942. unsigned char dbUpdate; /* True if any part of database file changed */
  21943. unsigned char inNormalWrite; /* True if in a normal write operation */
  21944. #endif
  21945. #ifdef SQLITE_TEST
  21946. /* In test mode, increase the size of this structure a bit so that
  21947. ** it is larger than the struct CrashFile defined in test6.c.
  21948. */
  21949. char aPadding[32];
  21950. #endif
  21951. };
  21952. /*
  21953. ** Allowed values for the unixFile.ctrlFlags bitmask:
  21954. */
  21955. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  21956. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  21957. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  21958. #ifndef SQLITE_DISABLE_DIRSYNC
  21959. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  21960. #else
  21961. # define UNIXFILE_DIRSYNC 0x00
  21962. #endif
  21963. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  21964. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  21965. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  21966. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  21967. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  21968. /*
  21969. ** Include code that is common to all os_*.c files
  21970. */
  21971. /************** Include os_common.h in the middle of os_unix.c ***************/
  21972. /************** Begin file os_common.h ***************************************/
  21973. /*
  21974. ** 2004 May 22
  21975. **
  21976. ** The author disclaims copyright to this source code. In place of
  21977. ** a legal notice, here is a blessing:
  21978. **
  21979. ** May you do good and not evil.
  21980. ** May you find forgiveness for yourself and forgive others.
  21981. ** May you share freely, never taking more than you give.
  21982. **
  21983. ******************************************************************************
  21984. **
  21985. ** This file contains macros and a little bit of code that is common to
  21986. ** all of the platform-specific files (os_*.c) and is #included into those
  21987. ** files.
  21988. **
  21989. ** This file should be #included by the os_*.c files only. It is not a
  21990. ** general purpose header file.
  21991. */
  21992. #ifndef _OS_COMMON_H_
  21993. #define _OS_COMMON_H_
  21994. /*
  21995. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  21996. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  21997. ** switch. The following code should catch this problem at compile-time.
  21998. */
  21999. #ifdef MEMORY_DEBUG
  22000. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22001. #endif
  22002. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22003. # ifndef SQLITE_DEBUG_OS_TRACE
  22004. # define SQLITE_DEBUG_OS_TRACE 0
  22005. # endif
  22006. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  22007. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  22008. #else
  22009. # define OSTRACE(X)
  22010. #endif
  22011. /*
  22012. ** Macros for performance tracing. Normally turned off. Only works
  22013. ** on i486 hardware.
  22014. */
  22015. #ifdef SQLITE_PERFORMANCE_TRACE
  22016. /*
  22017. ** hwtime.h contains inline assembler code for implementing
  22018. ** high-performance timing routines.
  22019. */
  22020. /************** Include hwtime.h in the middle of os_common.h ****************/
  22021. /************** Begin file hwtime.h ******************************************/
  22022. /*
  22023. ** 2008 May 27
  22024. **
  22025. ** The author disclaims copyright to this source code. In place of
  22026. ** a legal notice, here is a blessing:
  22027. **
  22028. ** May you do good and not evil.
  22029. ** May you find forgiveness for yourself and forgive others.
  22030. ** May you share freely, never taking more than you give.
  22031. **
  22032. ******************************************************************************
  22033. **
  22034. ** This file contains inline asm code for retrieving "high-performance"
  22035. ** counters for x86 class CPUs.
  22036. */
  22037. #ifndef _HWTIME_H_
  22038. #define _HWTIME_H_
  22039. /*
  22040. ** The following routine only works on pentium-class (or newer) processors.
  22041. ** It uses the RDTSC opcode to read the cycle count value out of the
  22042. ** processor and returns that value. This can be used for high-res
  22043. ** profiling.
  22044. */
  22045. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22046. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22047. #if defined(__GNUC__)
  22048. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22049. unsigned int lo, hi;
  22050. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22051. return (sqlite_uint64)hi << 32 | lo;
  22052. }
  22053. #elif defined(_MSC_VER)
  22054. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22055. __asm {
  22056. rdtsc
  22057. ret ; return value at EDX:EAX
  22058. }
  22059. }
  22060. #endif
  22061. #elif (defined(__GNUC__) && defined(__x86_64__))
  22062. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22063. unsigned long val;
  22064. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22065. return val;
  22066. }
  22067. #elif (defined(__GNUC__) && defined(__ppc__))
  22068. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22069. unsigned long long retval;
  22070. unsigned long junk;
  22071. __asm__ __volatile__ ("\n\
  22072. 1: mftbu %1\n\
  22073. mftb %L0\n\
  22074. mftbu %0\n\
  22075. cmpw %0,%1\n\
  22076. bne 1b"
  22077. : "=r" (retval), "=r" (junk));
  22078. return retval;
  22079. }
  22080. #else
  22081. #error Need implementation of sqlite3Hwtime() for your platform.
  22082. /*
  22083. ** To compile without implementing sqlite3Hwtime() for your platform,
  22084. ** you can remove the above #error and use the following
  22085. ** stub function. You will lose timing support for many
  22086. ** of the debugging and testing utilities, but it should at
  22087. ** least compile and run.
  22088. */
  22089. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22090. #endif
  22091. #endif /* !defined(_HWTIME_H_) */
  22092. /************** End of hwtime.h **********************************************/
  22093. /************** Continuing where we left off in os_common.h ******************/
  22094. static sqlite_uint64 g_start;
  22095. static sqlite_uint64 g_elapsed;
  22096. #define TIMER_START g_start=sqlite3Hwtime()
  22097. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22098. #define TIMER_ELAPSED g_elapsed
  22099. #else
  22100. #define TIMER_START
  22101. #define TIMER_END
  22102. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22103. #endif
  22104. /*
  22105. ** If we compile with the SQLITE_TEST macro set, then the following block
  22106. ** of code will give us the ability to simulate a disk I/O error. This
  22107. ** is used for testing the I/O recovery logic.
  22108. */
  22109. #ifdef SQLITE_TEST
  22110. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  22111. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  22112. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  22113. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  22114. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  22115. SQLITE_API int sqlite3_diskfull_pending = 0;
  22116. SQLITE_API int sqlite3_diskfull = 0;
  22117. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22118. #define SimulateIOError(CODE) \
  22119. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22120. || sqlite3_io_error_pending-- == 1 ) \
  22121. { local_ioerr(); CODE; }
  22122. static void local_ioerr(){
  22123. IOTRACE(("IOERR\n"));
  22124. sqlite3_io_error_hit++;
  22125. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22126. }
  22127. #define SimulateDiskfullError(CODE) \
  22128. if( sqlite3_diskfull_pending ){ \
  22129. if( sqlite3_diskfull_pending == 1 ){ \
  22130. local_ioerr(); \
  22131. sqlite3_diskfull = 1; \
  22132. sqlite3_io_error_hit = 1; \
  22133. CODE; \
  22134. }else{ \
  22135. sqlite3_diskfull_pending--; \
  22136. } \
  22137. }
  22138. #else
  22139. #define SimulateIOErrorBenign(X)
  22140. #define SimulateIOError(A)
  22141. #define SimulateDiskfullError(A)
  22142. #endif
  22143. /*
  22144. ** When testing, keep a count of the number of open files.
  22145. */
  22146. #ifdef SQLITE_TEST
  22147. SQLITE_API int sqlite3_open_file_count = 0;
  22148. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22149. #else
  22150. #define OpenCounter(X)
  22151. #endif
  22152. #endif /* !defined(_OS_COMMON_H_) */
  22153. /************** End of os_common.h *******************************************/
  22154. /************** Continuing where we left off in os_unix.c ********************/
  22155. /*
  22156. ** Define various macros that are missing from some systems.
  22157. */
  22158. #ifndef O_LARGEFILE
  22159. # define O_LARGEFILE 0
  22160. #endif
  22161. #ifdef SQLITE_DISABLE_LFS
  22162. # undef O_LARGEFILE
  22163. # define O_LARGEFILE 0
  22164. #endif
  22165. #ifndef O_NOFOLLOW
  22166. # define O_NOFOLLOW 0
  22167. #endif
  22168. #ifndef O_BINARY
  22169. # define O_BINARY 0
  22170. #endif
  22171. /*
  22172. ** The threadid macro resolves to the thread-id or to 0. Used for
  22173. ** testing and debugging only.
  22174. */
  22175. #if SQLITE_THREADSAFE
  22176. #define threadid pthread_self()
  22177. #else
  22178. #define threadid 0
  22179. #endif
  22180. /*
  22181. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  22182. */
  22183. #if !defined(HAVE_MREMAP)
  22184. # if defined(__linux__) && defined(_GNU_SOURCE)
  22185. # define HAVE_MREMAP 1
  22186. # else
  22187. # define HAVE_MREMAP 0
  22188. # endif
  22189. #endif
  22190. /*
  22191. ** Different Unix systems declare open() in different ways. Same use
  22192. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  22193. ** The difference is important when using a pointer to the function.
  22194. **
  22195. ** The safest way to deal with the problem is to always use this wrapper
  22196. ** which always has the same well-defined interface.
  22197. */
  22198. static int posixOpen(const char *zFile, int flags, int mode){
  22199. return open(zFile, flags, mode);
  22200. }
  22201. /*
  22202. ** On some systems, calls to fchown() will trigger a message in a security
  22203. ** log if they come from non-root processes. So avoid calling fchown() if
  22204. ** we are not running as root.
  22205. */
  22206. static int posixFchown(int fd, uid_t uid, gid_t gid){
  22207. return geteuid() ? 0 : fchown(fd,uid,gid);
  22208. }
  22209. /* Forward reference */
  22210. static int openDirectory(const char*, int*);
  22211. /*
  22212. ** Many system calls are accessed through pointer-to-functions so that
  22213. ** they may be overridden at runtime to facilitate fault injection during
  22214. ** testing and sandboxing. The following array holds the names and pointers
  22215. ** to all overrideable system calls.
  22216. */
  22217. static struct unix_syscall {
  22218. const char *zName; /* Name of the system call */
  22219. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  22220. sqlite3_syscall_ptr pDefault; /* Default value */
  22221. } aSyscall[] = {
  22222. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  22223. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  22224. { "close", (sqlite3_syscall_ptr)close, 0 },
  22225. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22226. { "access", (sqlite3_syscall_ptr)access, 0 },
  22227. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22228. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22229. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22230. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22231. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22232. /*
  22233. ** The DJGPP compiler environment looks mostly like Unix, but it
  22234. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22235. ** that always succeeds. This means that locking does not occur under
  22236. ** DJGPP. But it is DOS - what did you expect?
  22237. */
  22238. #ifdef __DJGPP__
  22239. { "fstat", 0, 0 },
  22240. #define osFstat(a,b,c) 0
  22241. #else
  22242. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22243. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  22244. #endif
  22245. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  22246. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  22247. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  22248. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  22249. { "read", (sqlite3_syscall_ptr)read, 0 },
  22250. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  22251. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22252. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  22253. #else
  22254. { "pread", (sqlite3_syscall_ptr)0, 0 },
  22255. #endif
  22256. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  22257. #if defined(USE_PREAD64)
  22258. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  22259. #else
  22260. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  22261. #endif
  22262. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  22263. { "write", (sqlite3_syscall_ptr)write, 0 },
  22264. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  22265. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22266. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  22267. #else
  22268. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  22269. #endif
  22270. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  22271. aSyscall[12].pCurrent)
  22272. #if defined(USE_PREAD64)
  22273. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  22274. #else
  22275. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  22276. #endif
  22277. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  22278. aSyscall[13].pCurrent)
  22279. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  22280. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  22281. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  22282. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  22283. #else
  22284. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  22285. #endif
  22286. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  22287. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  22288. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  22289. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  22290. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  22291. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  22292. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  22293. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  22294. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  22295. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  22296. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  22297. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  22298. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  22299. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  22300. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  22301. #if HAVE_MREMAP
  22302. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  22303. #else
  22304. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  22305. #endif
  22306. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  22307. }; /* End of the overrideable system calls */
  22308. /*
  22309. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22310. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  22311. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22312. ** system call named zName.
  22313. */
  22314. static int unixSetSystemCall(
  22315. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22316. const char *zName, /* Name of system call to override */
  22317. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22318. ){
  22319. unsigned int i;
  22320. int rc = SQLITE_NOTFOUND;
  22321. UNUSED_PARAMETER(pNotUsed);
  22322. if( zName==0 ){
  22323. /* If no zName is given, restore all system calls to their default
  22324. ** settings and return NULL
  22325. */
  22326. rc = SQLITE_OK;
  22327. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22328. if( aSyscall[i].pDefault ){
  22329. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22330. }
  22331. }
  22332. }else{
  22333. /* If zName is specified, operate on only the one system call
  22334. ** specified.
  22335. */
  22336. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22337. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22338. if( aSyscall[i].pDefault==0 ){
  22339. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22340. }
  22341. rc = SQLITE_OK;
  22342. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22343. aSyscall[i].pCurrent = pNewFunc;
  22344. break;
  22345. }
  22346. }
  22347. }
  22348. return rc;
  22349. }
  22350. /*
  22351. ** Return the value of a system call. Return NULL if zName is not a
  22352. ** recognized system call name. NULL is also returned if the system call
  22353. ** is currently undefined.
  22354. */
  22355. static sqlite3_syscall_ptr unixGetSystemCall(
  22356. sqlite3_vfs *pNotUsed,
  22357. const char *zName
  22358. ){
  22359. unsigned int i;
  22360. UNUSED_PARAMETER(pNotUsed);
  22361. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22362. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22363. }
  22364. return 0;
  22365. }
  22366. /*
  22367. ** Return the name of the first system call after zName. If zName==NULL
  22368. ** then return the name of the first system call. Return NULL if zName
  22369. ** is the last system call or if zName is not the name of a valid
  22370. ** system call.
  22371. */
  22372. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  22373. int i = -1;
  22374. UNUSED_PARAMETER(p);
  22375. if( zName ){
  22376. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22377. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22378. }
  22379. }
  22380. for(i++; i<ArraySize(aSyscall); i++){
  22381. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22382. }
  22383. return 0;
  22384. }
  22385. /*
  22386. ** Invoke open(). Do so multiple times, until it either succeeds or
  22387. ** fails for some reason other than EINTR.
  22388. **
  22389. ** If the file creation mode "m" is 0 then set it to the default for
  22390. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22391. ** 0644) as modified by the system umask. If m is not 0, then
  22392. ** make the file creation mode be exactly m ignoring the umask.
  22393. **
  22394. ** The m parameter will be non-zero only when creating -wal, -journal,
  22395. ** and -shm files. We want those files to have *exactly* the same
  22396. ** permissions as their original database, unadulterated by the umask.
  22397. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22398. ** transaction crashes and leaves behind hot journals, then any
  22399. ** process that is able to write to the database will also be able to
  22400. ** recover the hot journals.
  22401. */
  22402. static int robust_open(const char *z, int f, mode_t m){
  22403. int fd;
  22404. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  22405. do{
  22406. #if defined(O_CLOEXEC)
  22407. fd = osOpen(z,f|O_CLOEXEC,m2);
  22408. #else
  22409. fd = osOpen(z,f,m2);
  22410. #endif
  22411. }while( fd<0 && errno==EINTR );
  22412. if( fd>=0 ){
  22413. if( m!=0 ){
  22414. struct stat statbuf;
  22415. if( osFstat(fd, &statbuf)==0
  22416. && statbuf.st_size==0
  22417. && (statbuf.st_mode&0777)!=m
  22418. ){
  22419. osFchmod(fd, m);
  22420. }
  22421. }
  22422. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  22423. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22424. #endif
  22425. }
  22426. return fd;
  22427. }
  22428. /*
  22429. ** Helper functions to obtain and relinquish the global mutex. The
  22430. ** global mutex is used to protect the unixInodeInfo and
  22431. ** vxworksFileId objects used by this file, all of which may be
  22432. ** shared by multiple threads.
  22433. **
  22434. ** Function unixMutexHeld() is used to assert() that the global mutex
  22435. ** is held when required. This function is only used as part of assert()
  22436. ** statements. e.g.
  22437. **
  22438. ** unixEnterMutex()
  22439. ** assert( unixMutexHeld() );
  22440. ** unixEnterLeave()
  22441. */
  22442. static void unixEnterMutex(void){
  22443. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22444. }
  22445. static void unixLeaveMutex(void){
  22446. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22447. }
  22448. #ifdef SQLITE_DEBUG
  22449. static int unixMutexHeld(void) {
  22450. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22451. }
  22452. #endif
  22453. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22454. /*
  22455. ** Helper function for printing out trace information from debugging
  22456. ** binaries. This returns the string represetation of the supplied
  22457. ** integer lock-type.
  22458. */
  22459. static const char *azFileLock(int eFileLock){
  22460. switch( eFileLock ){
  22461. case NO_LOCK: return "NONE";
  22462. case SHARED_LOCK: return "SHARED";
  22463. case RESERVED_LOCK: return "RESERVED";
  22464. case PENDING_LOCK: return "PENDING";
  22465. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22466. }
  22467. return "ERROR";
  22468. }
  22469. #endif
  22470. #ifdef SQLITE_LOCK_TRACE
  22471. /*
  22472. ** Print out information about all locking operations.
  22473. **
  22474. ** This routine is used for troubleshooting locks on multithreaded
  22475. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  22476. ** command-line option on the compiler. This code is normally
  22477. ** turned off.
  22478. */
  22479. static int lockTrace(int fd, int op, struct flock *p){
  22480. char *zOpName, *zType;
  22481. int s;
  22482. int savedErrno;
  22483. if( op==F_GETLK ){
  22484. zOpName = "GETLK";
  22485. }else if( op==F_SETLK ){
  22486. zOpName = "SETLK";
  22487. }else{
  22488. s = osFcntl(fd, op, p);
  22489. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  22490. return s;
  22491. }
  22492. if( p->l_type==F_RDLCK ){
  22493. zType = "RDLCK";
  22494. }else if( p->l_type==F_WRLCK ){
  22495. zType = "WRLCK";
  22496. }else if( p->l_type==F_UNLCK ){
  22497. zType = "UNLCK";
  22498. }else{
  22499. assert( 0 );
  22500. }
  22501. assert( p->l_whence==SEEK_SET );
  22502. s = osFcntl(fd, op, p);
  22503. savedErrno = errno;
  22504. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  22505. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  22506. (int)p->l_pid, s);
  22507. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  22508. struct flock l2;
  22509. l2 = *p;
  22510. osFcntl(fd, F_GETLK, &l2);
  22511. if( l2.l_type==F_RDLCK ){
  22512. zType = "RDLCK";
  22513. }else if( l2.l_type==F_WRLCK ){
  22514. zType = "WRLCK";
  22515. }else if( l2.l_type==F_UNLCK ){
  22516. zType = "UNLCK";
  22517. }else{
  22518. assert( 0 );
  22519. }
  22520. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  22521. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  22522. }
  22523. errno = savedErrno;
  22524. return s;
  22525. }
  22526. #undef osFcntl
  22527. #define osFcntl lockTrace
  22528. #endif /* SQLITE_LOCK_TRACE */
  22529. /*
  22530. ** Retry ftruncate() calls that fail due to EINTR
  22531. */
  22532. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22533. int rc;
  22534. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  22535. return rc;
  22536. }
  22537. /*
  22538. ** This routine translates a standard POSIX errno code into something
  22539. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22540. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22541. ** and a variety of "please close the file descriptor NOW" errors into
  22542. ** SQLITE_IOERR
  22543. **
  22544. ** Errors during initialization of locks, or file system support for locks,
  22545. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22546. */
  22547. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22548. switch (posixError) {
  22549. #if 0
  22550. /* At one point this code was not commented out. In theory, this branch
  22551. ** should never be hit, as this function should only be called after
  22552. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22553. ** the value of errno as the first argument. Since a system call has failed,
  22554. ** errno should be non-zero.
  22555. **
  22556. ** Despite this, if errno really is zero, we still don't want to return
  22557. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22558. ** propagated back to the caller. Commenting this branch out means errno==0
  22559. ** will be handled by the "default:" case below.
  22560. */
  22561. case 0:
  22562. return SQLITE_OK;
  22563. #endif
  22564. case EAGAIN:
  22565. case ETIMEDOUT:
  22566. case EBUSY:
  22567. case EINTR:
  22568. case ENOLCK:
  22569. /* random NFS retry error, unless during file system support
  22570. * introspection, in which it actually means what it says */
  22571. return SQLITE_BUSY;
  22572. case EACCES:
  22573. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  22574. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  22575. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  22576. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  22577. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  22578. return SQLITE_BUSY;
  22579. }
  22580. /* else fall through */
  22581. case EPERM:
  22582. return SQLITE_PERM;
  22583. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  22584. ** this module never makes such a call. And the code in SQLite itself
  22585. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  22586. ** this case is also commented out. If the system does set errno to EDEADLK,
  22587. ** the default SQLITE_IOERR_XXX code will be returned. */
  22588. #if 0
  22589. case EDEADLK:
  22590. return SQLITE_IOERR_BLOCKED;
  22591. #endif
  22592. #if EOPNOTSUPP!=ENOTSUP
  22593. case EOPNOTSUPP:
  22594. /* something went terribly awry, unless during file system support
  22595. * introspection, in which it actually means what it says */
  22596. #endif
  22597. #ifdef ENOTSUP
  22598. case ENOTSUP:
  22599. /* invalid fd, unless during file system support introspection, in which
  22600. * it actually means what it says */
  22601. #endif
  22602. case EIO:
  22603. case EBADF:
  22604. case EINVAL:
  22605. case ENOTCONN:
  22606. case ENODEV:
  22607. case ENXIO:
  22608. case ENOENT:
  22609. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  22610. case ESTALE:
  22611. #endif
  22612. case ENOSYS:
  22613. /* these should force the client to close the file and reconnect */
  22614. default:
  22615. return sqliteIOErr;
  22616. }
  22617. }
  22618. /******************************************************************************
  22619. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  22620. **
  22621. ** On most versions of unix, we can get a unique ID for a file by concatenating
  22622. ** the device number and the inode number. But this does not work on VxWorks.
  22623. ** On VxWorks, a unique file id must be based on the canonical filename.
  22624. **
  22625. ** A pointer to an instance of the following structure can be used as a
  22626. ** unique file ID in VxWorks. Each instance of this structure contains
  22627. ** a copy of the canonical filename. There is also a reference count.
  22628. ** The structure is reclaimed when the number of pointers to it drops to
  22629. ** zero.
  22630. **
  22631. ** There are never very many files open at one time and lookups are not
  22632. ** a performance-critical path, so it is sufficient to put these
  22633. ** structures on a linked list.
  22634. */
  22635. struct vxworksFileId {
  22636. struct vxworksFileId *pNext; /* Next in a list of them all */
  22637. int nRef; /* Number of references to this one */
  22638. int nName; /* Length of the zCanonicalName[] string */
  22639. char *zCanonicalName; /* Canonical filename */
  22640. };
  22641. #if OS_VXWORKS
  22642. /*
  22643. ** All unique filenames are held on a linked list headed by this
  22644. ** variable:
  22645. */
  22646. static struct vxworksFileId *vxworksFileList = 0;
  22647. /*
  22648. ** Simplify a filename into its canonical form
  22649. ** by making the following changes:
  22650. **
  22651. ** * removing any trailing and duplicate /
  22652. ** * convert /./ into just /
  22653. ** * convert /A/../ where A is any simple name into just /
  22654. **
  22655. ** Changes are made in-place. Return the new name length.
  22656. **
  22657. ** The original filename is in z[0..n-1]. Return the number of
  22658. ** characters in the simplified name.
  22659. */
  22660. static int vxworksSimplifyName(char *z, int n){
  22661. int i, j;
  22662. while( n>1 && z[n-1]=='/' ){ n--; }
  22663. for(i=j=0; i<n; i++){
  22664. if( z[i]=='/' ){
  22665. if( z[i+1]=='/' ) continue;
  22666. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  22667. i += 1;
  22668. continue;
  22669. }
  22670. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  22671. while( j>0 && z[j-1]!='/' ){ j--; }
  22672. if( j>0 ){ j--; }
  22673. i += 2;
  22674. continue;
  22675. }
  22676. }
  22677. z[j++] = z[i];
  22678. }
  22679. z[j] = 0;
  22680. return j;
  22681. }
  22682. /*
  22683. ** Find a unique file ID for the given absolute pathname. Return
  22684. ** a pointer to the vxworksFileId object. This pointer is the unique
  22685. ** file ID.
  22686. **
  22687. ** The nRef field of the vxworksFileId object is incremented before
  22688. ** the object is returned. A new vxworksFileId object is created
  22689. ** and added to the global list if necessary.
  22690. **
  22691. ** If a memory allocation error occurs, return NULL.
  22692. */
  22693. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  22694. struct vxworksFileId *pNew; /* search key and new file ID */
  22695. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  22696. int n; /* Length of zAbsoluteName string */
  22697. assert( zAbsoluteName[0]=='/' );
  22698. n = (int)strlen(zAbsoluteName);
  22699. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  22700. if( pNew==0 ) return 0;
  22701. pNew->zCanonicalName = (char*)&pNew[1];
  22702. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  22703. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  22704. /* Search for an existing entry that matching the canonical name.
  22705. ** If found, increment the reference count and return a pointer to
  22706. ** the existing file ID.
  22707. */
  22708. unixEnterMutex();
  22709. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  22710. if( pCandidate->nName==n
  22711. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  22712. ){
  22713. sqlite3_free(pNew);
  22714. pCandidate->nRef++;
  22715. unixLeaveMutex();
  22716. return pCandidate;
  22717. }
  22718. }
  22719. /* No match was found. We will make a new file ID */
  22720. pNew->nRef = 1;
  22721. pNew->nName = n;
  22722. pNew->pNext = vxworksFileList;
  22723. vxworksFileList = pNew;
  22724. unixLeaveMutex();
  22725. return pNew;
  22726. }
  22727. /*
  22728. ** Decrement the reference count on a vxworksFileId object. Free
  22729. ** the object when the reference count reaches zero.
  22730. */
  22731. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  22732. unixEnterMutex();
  22733. assert( pId->nRef>0 );
  22734. pId->nRef--;
  22735. if( pId->nRef==0 ){
  22736. struct vxworksFileId **pp;
  22737. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  22738. assert( *pp==pId );
  22739. *pp = pId->pNext;
  22740. sqlite3_free(pId);
  22741. }
  22742. unixLeaveMutex();
  22743. }
  22744. #endif /* OS_VXWORKS */
  22745. /*************** End of Unique File ID Utility Used By VxWorks ****************
  22746. ******************************************************************************/
  22747. /******************************************************************************
  22748. *************************** Posix Advisory Locking ****************************
  22749. **
  22750. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  22751. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  22752. ** sets or clears a lock, that operation overrides any prior locks set
  22753. ** by the same process. It does not explicitly say so, but this implies
  22754. ** that it overrides locks set by the same process using a different
  22755. ** file descriptor. Consider this test case:
  22756. **
  22757. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  22758. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  22759. **
  22760. ** Suppose ./file1 and ./file2 are really the same file (because
  22761. ** one is a hard or symbolic link to the other) then if you set
  22762. ** an exclusive lock on fd1, then try to get an exclusive lock
  22763. ** on fd2, it works. I would have expected the second lock to
  22764. ** fail since there was already a lock on the file due to fd1.
  22765. ** But not so. Since both locks came from the same process, the
  22766. ** second overrides the first, even though they were on different
  22767. ** file descriptors opened on different file names.
  22768. **
  22769. ** This means that we cannot use POSIX locks to synchronize file access
  22770. ** among competing threads of the same process. POSIX locks will work fine
  22771. ** to synchronize access for threads in separate processes, but not
  22772. ** threads within the same process.
  22773. **
  22774. ** To work around the problem, SQLite has to manage file locks internally
  22775. ** on its own. Whenever a new database is opened, we have to find the
  22776. ** specific inode of the database file (the inode is determined by the
  22777. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  22778. ** and check for locks already existing on that inode. When locks are
  22779. ** created or removed, we have to look at our own internal record of the
  22780. ** locks to see if another thread has previously set a lock on that same
  22781. ** inode.
  22782. **
  22783. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  22784. ** For VxWorks, we have to use the alternative unique ID system based on
  22785. ** canonical filename and implemented in the previous division.)
  22786. **
  22787. ** The sqlite3_file structure for POSIX is no longer just an integer file
  22788. ** descriptor. It is now a structure that holds the integer file
  22789. ** descriptor and a pointer to a structure that describes the internal
  22790. ** locks on the corresponding inode. There is one locking structure
  22791. ** per inode, so if the same inode is opened twice, both unixFile structures
  22792. ** point to the same locking structure. The locking structure keeps
  22793. ** a reference count (so we will know when to delete it) and a "cnt"
  22794. ** field that tells us its internal lock status. cnt==0 means the
  22795. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  22796. ** cnt>0 means there are cnt shared locks on the file.
  22797. **
  22798. ** Any attempt to lock or unlock a file first checks the locking
  22799. ** structure. The fcntl() system call is only invoked to set a
  22800. ** POSIX lock if the internal lock structure transitions between
  22801. ** a locked and an unlocked state.
  22802. **
  22803. ** But wait: there are yet more problems with POSIX advisory locks.
  22804. **
  22805. ** If you close a file descriptor that points to a file that has locks,
  22806. ** all locks on that file that are owned by the current process are
  22807. ** released. To work around this problem, each unixInodeInfo object
  22808. ** maintains a count of the number of pending locks on tha inode.
  22809. ** When an attempt is made to close an unixFile, if there are
  22810. ** other unixFile open on the same inode that are holding locks, the call
  22811. ** to close() the file descriptor is deferred until all of the locks clear.
  22812. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  22813. ** be closed and that list is walked (and cleared) when the last lock
  22814. ** clears.
  22815. **
  22816. ** Yet another problem: LinuxThreads do not play well with posix locks.
  22817. **
  22818. ** Many older versions of linux use the LinuxThreads library which is
  22819. ** not posix compliant. Under LinuxThreads, a lock created by thread
  22820. ** A cannot be modified or overridden by a different thread B.
  22821. ** Only thread A can modify the lock. Locking behavior is correct
  22822. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  22823. ** on linux - with NPTL a lock created by thread A can override locks
  22824. ** in thread B. But there is no way to know at compile-time which
  22825. ** threading library is being used. So there is no way to know at
  22826. ** compile-time whether or not thread A can override locks on thread B.
  22827. ** One has to do a run-time check to discover the behavior of the
  22828. ** current process.
  22829. **
  22830. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  22831. ** was dropped beginning with version 3.7.0. SQLite will still work with
  22832. ** LinuxThreads provided that (1) there is no more than one connection
  22833. ** per database file in the same process and (2) database connections
  22834. ** do not move across threads.
  22835. */
  22836. /*
  22837. ** An instance of the following structure serves as the key used
  22838. ** to locate a particular unixInodeInfo object.
  22839. */
  22840. struct unixFileId {
  22841. dev_t dev; /* Device number */
  22842. #if OS_VXWORKS
  22843. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  22844. #else
  22845. ino_t ino; /* Inode number */
  22846. #endif
  22847. };
  22848. /*
  22849. ** An instance of the following structure is allocated for each open
  22850. ** inode. Or, on LinuxThreads, there is one of these structures for
  22851. ** each inode opened by each thread.
  22852. **
  22853. ** A single inode can have multiple file descriptors, so each unixFile
  22854. ** structure contains a pointer to an instance of this object and this
  22855. ** object keeps a count of the number of unixFile pointing to it.
  22856. */
  22857. struct unixInodeInfo {
  22858. struct unixFileId fileId; /* The lookup key */
  22859. int nShared; /* Number of SHARED locks held */
  22860. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  22861. unsigned char bProcessLock; /* An exclusive process lock is held */
  22862. int nRef; /* Number of pointers to this structure */
  22863. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  22864. int nLock; /* Number of outstanding file locks */
  22865. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  22866. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  22867. unixInodeInfo *pPrev; /* .... doubly linked */
  22868. #if SQLITE_ENABLE_LOCKING_STYLE
  22869. unsigned long long sharedByte; /* for AFP simulated shared lock */
  22870. #endif
  22871. #if OS_VXWORKS
  22872. sem_t *pSem; /* Named POSIX semaphore */
  22873. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  22874. #endif
  22875. };
  22876. /*
  22877. ** A lists of all unixInodeInfo objects.
  22878. */
  22879. static unixInodeInfo *inodeList = 0;
  22880. /*
  22881. **
  22882. ** This function - unixLogError_x(), is only ever called via the macro
  22883. ** unixLogError().
  22884. **
  22885. ** It is invoked after an error occurs in an OS function and errno has been
  22886. ** set. It logs a message using sqlite3_log() containing the current value of
  22887. ** errno and, if possible, the human-readable equivalent from strerror() or
  22888. ** strerror_r().
  22889. **
  22890. ** The first argument passed to the macro should be the error code that
  22891. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  22892. ** The two subsequent arguments should be the name of the OS function that
  22893. ** failed (e.g. "unlink", "open") and the associated file-system path,
  22894. ** if any.
  22895. */
  22896. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  22897. static int unixLogErrorAtLine(
  22898. int errcode, /* SQLite error code */
  22899. const char *zFunc, /* Name of OS function that failed */
  22900. const char *zPath, /* File path associated with error */
  22901. int iLine /* Source line number where error occurred */
  22902. ){
  22903. char *zErr; /* Message from strerror() or equivalent */
  22904. int iErrno = errno; /* Saved syscall error number */
  22905. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  22906. ** the strerror() function to obtain the human-readable error message
  22907. ** equivalent to errno. Otherwise, use strerror_r().
  22908. */
  22909. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  22910. char aErr[80];
  22911. memset(aErr, 0, sizeof(aErr));
  22912. zErr = aErr;
  22913. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  22914. ** assume that the system provides the GNU version of strerror_r() that
  22915. ** returns a pointer to a buffer containing the error message. That pointer
  22916. ** may point to aErr[], or it may point to some static storage somewhere.
  22917. ** Otherwise, assume that the system provides the POSIX version of
  22918. ** strerror_r(), which always writes an error message into aErr[].
  22919. **
  22920. ** If the code incorrectly assumes that it is the POSIX version that is
  22921. ** available, the error message will often be an empty string. Not a
  22922. ** huge problem. Incorrectly concluding that the GNU version is available
  22923. ** could lead to a segfault though.
  22924. */
  22925. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  22926. zErr =
  22927. # endif
  22928. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  22929. #elif SQLITE_THREADSAFE
  22930. /* This is a threadsafe build, but strerror_r() is not available. */
  22931. zErr = "";
  22932. #else
  22933. /* Non-threadsafe build, use strerror(). */
  22934. zErr = strerror(iErrno);
  22935. #endif
  22936. if( zPath==0 ) zPath = "";
  22937. sqlite3_log(errcode,
  22938. "os_unix.c:%d: (%d) %s(%s) - %s",
  22939. iLine, iErrno, zFunc, zPath, zErr
  22940. );
  22941. return errcode;
  22942. }
  22943. /*
  22944. ** Close a file descriptor.
  22945. **
  22946. ** We assume that close() almost always works, since it is only in a
  22947. ** very sick application or on a very sick platform that it might fail.
  22948. ** If it does fail, simply leak the file descriptor, but do log the
  22949. ** error.
  22950. **
  22951. ** Note that it is not safe to retry close() after EINTR since the
  22952. ** file descriptor might have already been reused by another thread.
  22953. ** So we don't even try to recover from an EINTR. Just log the error
  22954. ** and move on.
  22955. */
  22956. static void robust_close(unixFile *pFile, int h, int lineno){
  22957. if( osClose(h) ){
  22958. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  22959. pFile ? pFile->zPath : 0, lineno);
  22960. }
  22961. }
  22962. /*
  22963. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  22964. */
  22965. static void closePendingFds(unixFile *pFile){
  22966. unixInodeInfo *pInode = pFile->pInode;
  22967. UnixUnusedFd *p;
  22968. UnixUnusedFd *pNext;
  22969. for(p=pInode->pUnused; p; p=pNext){
  22970. pNext = p->pNext;
  22971. robust_close(pFile, p->fd, __LINE__);
  22972. sqlite3_free(p);
  22973. }
  22974. pInode->pUnused = 0;
  22975. }
  22976. /*
  22977. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  22978. **
  22979. ** The mutex entered using the unixEnterMutex() function must be held
  22980. ** when this function is called.
  22981. */
  22982. static void releaseInodeInfo(unixFile *pFile){
  22983. unixInodeInfo *pInode = pFile->pInode;
  22984. assert( unixMutexHeld() );
  22985. if( ALWAYS(pInode) ){
  22986. pInode->nRef--;
  22987. if( pInode->nRef==0 ){
  22988. assert( pInode->pShmNode==0 );
  22989. closePendingFds(pFile);
  22990. if( pInode->pPrev ){
  22991. assert( pInode->pPrev->pNext==pInode );
  22992. pInode->pPrev->pNext = pInode->pNext;
  22993. }else{
  22994. assert( inodeList==pInode );
  22995. inodeList = pInode->pNext;
  22996. }
  22997. if( pInode->pNext ){
  22998. assert( pInode->pNext->pPrev==pInode );
  22999. pInode->pNext->pPrev = pInode->pPrev;
  23000. }
  23001. sqlite3_free(pInode);
  23002. }
  23003. }
  23004. }
  23005. /*
  23006. ** Given a file descriptor, locate the unixInodeInfo object that
  23007. ** describes that file descriptor. Create a new one if necessary. The
  23008. ** return value might be uninitialized if an error occurs.
  23009. **
  23010. ** The mutex entered using the unixEnterMutex() function must be held
  23011. ** when this function is called.
  23012. **
  23013. ** Return an appropriate error code.
  23014. */
  23015. static int findInodeInfo(
  23016. unixFile *pFile, /* Unix file with file desc used in the key */
  23017. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  23018. ){
  23019. int rc; /* System call return code */
  23020. int fd; /* The file descriptor for pFile */
  23021. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  23022. struct stat statbuf; /* Low-level file information */
  23023. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  23024. assert( unixMutexHeld() );
  23025. /* Get low-level information about the file that we can used to
  23026. ** create a unique name for the file.
  23027. */
  23028. fd = pFile->h;
  23029. rc = osFstat(fd, &statbuf);
  23030. if( rc!=0 ){
  23031. pFile->lastErrno = errno;
  23032. #ifdef EOVERFLOW
  23033. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  23034. #endif
  23035. return SQLITE_IOERR;
  23036. }
  23037. #ifdef __APPLE__
  23038. /* On OS X on an msdos filesystem, the inode number is reported
  23039. ** incorrectly for zero-size files. See ticket #3260. To work
  23040. ** around this problem (we consider it a bug in OS X, not SQLite)
  23041. ** we always increase the file size to 1 by writing a single byte
  23042. ** prior to accessing the inode number. The one byte written is
  23043. ** an ASCII 'S' character which also happens to be the first byte
  23044. ** in the header of every SQLite database. In this way, if there
  23045. ** is a race condition such that another thread has already populated
  23046. ** the first page of the database, no damage is done.
  23047. */
  23048. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  23049. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  23050. if( rc!=1 ){
  23051. pFile->lastErrno = errno;
  23052. return SQLITE_IOERR;
  23053. }
  23054. rc = osFstat(fd, &statbuf);
  23055. if( rc!=0 ){
  23056. pFile->lastErrno = errno;
  23057. return SQLITE_IOERR;
  23058. }
  23059. }
  23060. #endif
  23061. memset(&fileId, 0, sizeof(fileId));
  23062. fileId.dev = statbuf.st_dev;
  23063. #if OS_VXWORKS
  23064. fileId.pId = pFile->pId;
  23065. #else
  23066. fileId.ino = statbuf.st_ino;
  23067. #endif
  23068. pInode = inodeList;
  23069. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  23070. pInode = pInode->pNext;
  23071. }
  23072. if( pInode==0 ){
  23073. pInode = sqlite3_malloc( sizeof(*pInode) );
  23074. if( pInode==0 ){
  23075. return SQLITE_NOMEM;
  23076. }
  23077. memset(pInode, 0, sizeof(*pInode));
  23078. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  23079. pInode->nRef = 1;
  23080. pInode->pNext = inodeList;
  23081. pInode->pPrev = 0;
  23082. if( inodeList ) inodeList->pPrev = pInode;
  23083. inodeList = pInode;
  23084. }else{
  23085. pInode->nRef++;
  23086. }
  23087. *ppInode = pInode;
  23088. return SQLITE_OK;
  23089. }
  23090. /*
  23091. ** Check a unixFile that is a database. Verify the following:
  23092. **
  23093. ** (1) There is exactly one hard link on the file
  23094. ** (2) The file is not a symbolic link
  23095. ** (3) The file has not been renamed or unlinked
  23096. **
  23097. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  23098. */
  23099. static void verifyDbFile(unixFile *pFile){
  23100. struct stat buf;
  23101. int rc;
  23102. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  23103. /* One or more of the following warnings have already been issued. Do not
  23104. ** repeat them so as not to clutter the error log */
  23105. return;
  23106. }
  23107. rc = osFstat(pFile->h, &buf);
  23108. if( rc!=0 ){
  23109. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  23110. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23111. return;
  23112. }
  23113. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  23114. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  23115. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23116. return;
  23117. }
  23118. if( buf.st_nlink>1 ){
  23119. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  23120. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23121. return;
  23122. }
  23123. if( pFile->pInode!=0
  23124. && ((rc = osStat(pFile->zPath, &buf))!=0
  23125. || buf.st_ino!=pFile->pInode->fileId.ino)
  23126. ){
  23127. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  23128. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23129. return;
  23130. }
  23131. }
  23132. /*
  23133. ** This routine checks if there is a RESERVED lock held on the specified
  23134. ** file by this or any other process. If such a lock is held, set *pResOut
  23135. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23136. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23137. */
  23138. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  23139. int rc = SQLITE_OK;
  23140. int reserved = 0;
  23141. unixFile *pFile = (unixFile*)id;
  23142. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23143. assert( pFile );
  23144. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  23145. /* Check if a thread in this process holds such a lock */
  23146. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  23147. reserved = 1;
  23148. }
  23149. /* Otherwise see if some other process holds it.
  23150. */
  23151. #ifndef __DJGPP__
  23152. if( !reserved && !pFile->pInode->bProcessLock ){
  23153. struct flock lock;
  23154. lock.l_whence = SEEK_SET;
  23155. lock.l_start = RESERVED_BYTE;
  23156. lock.l_len = 1;
  23157. lock.l_type = F_WRLCK;
  23158. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  23159. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  23160. pFile->lastErrno = errno;
  23161. } else if( lock.l_type!=F_UNLCK ){
  23162. reserved = 1;
  23163. }
  23164. }
  23165. #endif
  23166. unixLeaveMutex();
  23167. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  23168. *pResOut = reserved;
  23169. return rc;
  23170. }
  23171. /*
  23172. ** Attempt to set a system-lock on the file pFile. The lock is
  23173. ** described by pLock.
  23174. **
  23175. ** If the pFile was opened read/write from unix-excl, then the only lock
  23176. ** ever obtained is an exclusive lock, and it is obtained exactly once
  23177. ** the first time any lock is attempted. All subsequent system locking
  23178. ** operations become no-ops. Locking operations still happen internally,
  23179. ** in order to coordinate access between separate database connections
  23180. ** within this process, but all of that is handled in memory and the
  23181. ** operating system does not participate.
  23182. **
  23183. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  23184. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  23185. ** and is read-only.
  23186. **
  23187. ** Zero is returned if the call completes successfully, or -1 if a call
  23188. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  23189. */
  23190. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  23191. int rc;
  23192. unixInodeInfo *pInode = pFile->pInode;
  23193. assert( unixMutexHeld() );
  23194. assert( pInode!=0 );
  23195. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  23196. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  23197. ){
  23198. if( pInode->bProcessLock==0 ){
  23199. struct flock lock;
  23200. assert( pInode->nLock==0 );
  23201. lock.l_whence = SEEK_SET;
  23202. lock.l_start = SHARED_FIRST;
  23203. lock.l_len = SHARED_SIZE;
  23204. lock.l_type = F_WRLCK;
  23205. rc = osFcntl(pFile->h, F_SETLK, &lock);
  23206. if( rc<0 ) return rc;
  23207. pInode->bProcessLock = 1;
  23208. pInode->nLock++;
  23209. }else{
  23210. rc = 0;
  23211. }
  23212. }else{
  23213. rc = osFcntl(pFile->h, F_SETLK, pLock);
  23214. }
  23215. return rc;
  23216. }
  23217. /*
  23218. ** Lock the file with the lock specified by parameter eFileLock - one
  23219. ** of the following:
  23220. **
  23221. ** (1) SHARED_LOCK
  23222. ** (2) RESERVED_LOCK
  23223. ** (3) PENDING_LOCK
  23224. ** (4) EXCLUSIVE_LOCK
  23225. **
  23226. ** Sometimes when requesting one lock state, additional lock states
  23227. ** are inserted in between. The locking might fail on one of the later
  23228. ** transitions leaving the lock state different from what it started but
  23229. ** still short of its goal. The following chart shows the allowed
  23230. ** transitions and the inserted intermediate states:
  23231. **
  23232. ** UNLOCKED -> SHARED
  23233. ** SHARED -> RESERVED
  23234. ** SHARED -> (PENDING) -> EXCLUSIVE
  23235. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23236. ** PENDING -> EXCLUSIVE
  23237. **
  23238. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23239. ** routine to lower a locking level.
  23240. */
  23241. static int unixLock(sqlite3_file *id, int eFileLock){
  23242. /* The following describes the implementation of the various locks and
  23243. ** lock transitions in terms of the POSIX advisory shared and exclusive
  23244. ** lock primitives (called read-locks and write-locks below, to avoid
  23245. ** confusion with SQLite lock names). The algorithms are complicated
  23246. ** slightly in order to be compatible with windows systems simultaneously
  23247. ** accessing the same database file, in case that is ever required.
  23248. **
  23249. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  23250. ** byte', each single bytes at well known offsets, and the 'shared byte
  23251. ** range', a range of 510 bytes at a well known offset.
  23252. **
  23253. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  23254. ** byte'. If this is successful, a random byte from the 'shared byte
  23255. ** range' is read-locked and the lock on the 'pending byte' released.
  23256. **
  23257. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  23258. ** A RESERVED lock is implemented by grabbing a write-lock on the
  23259. ** 'reserved byte'.
  23260. **
  23261. ** A process may only obtain a PENDING lock after it has obtained a
  23262. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  23263. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  23264. ** obtained, but existing SHARED locks are allowed to persist. A process
  23265. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  23266. ** This property is used by the algorithm for rolling back a journal file
  23267. ** after a crash.
  23268. **
  23269. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23270. ** implemented by obtaining a write-lock on the entire 'shared byte
  23271. ** range'. Since all other locks require a read-lock on one of the bytes
  23272. ** within this range, this ensures that no other locks are held on the
  23273. ** database.
  23274. **
  23275. ** The reason a single byte cannot be used instead of the 'shared byte
  23276. ** range' is that some versions of windows do not support read-locks. By
  23277. ** locking a random byte from a range, concurrent SHARED locks may exist
  23278. ** even if the locking primitive used is always a write-lock.
  23279. */
  23280. int rc = SQLITE_OK;
  23281. unixFile *pFile = (unixFile*)id;
  23282. unixInodeInfo *pInode;
  23283. struct flock lock;
  23284. int tErrno = 0;
  23285. assert( pFile );
  23286. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23287. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23288. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  23289. /* If there is already a lock of this type or more restrictive on the
  23290. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23291. ** unixEnterMutex() hasn't been called yet.
  23292. */
  23293. if( pFile->eFileLock>=eFileLock ){
  23294. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23295. azFileLock(eFileLock)));
  23296. return SQLITE_OK;
  23297. }
  23298. /* Make sure the locking sequence is correct.
  23299. ** (1) We never move from unlocked to anything higher than shared lock.
  23300. ** (2) SQLite never explicitly requests a pendig lock.
  23301. ** (3) A shared lock is always held when a reserve lock is requested.
  23302. */
  23303. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23304. assert( eFileLock!=PENDING_LOCK );
  23305. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23306. /* This mutex is needed because pFile->pInode is shared across threads
  23307. */
  23308. unixEnterMutex();
  23309. pInode = pFile->pInode;
  23310. /* If some thread using this PID has a lock via a different unixFile*
  23311. ** handle that precludes the requested lock, return BUSY.
  23312. */
  23313. if( (pFile->eFileLock!=pInode->eFileLock &&
  23314. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23315. ){
  23316. rc = SQLITE_BUSY;
  23317. goto end_lock;
  23318. }
  23319. /* If a SHARED lock is requested, and some thread using this PID already
  23320. ** has a SHARED or RESERVED lock, then increment reference counts and
  23321. ** return SQLITE_OK.
  23322. */
  23323. if( eFileLock==SHARED_LOCK &&
  23324. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23325. assert( eFileLock==SHARED_LOCK );
  23326. assert( pFile->eFileLock==0 );
  23327. assert( pInode->nShared>0 );
  23328. pFile->eFileLock = SHARED_LOCK;
  23329. pInode->nShared++;
  23330. pInode->nLock++;
  23331. goto end_lock;
  23332. }
  23333. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23334. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23335. ** be released.
  23336. */
  23337. lock.l_len = 1L;
  23338. lock.l_whence = SEEK_SET;
  23339. if( eFileLock==SHARED_LOCK
  23340. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  23341. ){
  23342. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  23343. lock.l_start = PENDING_BYTE;
  23344. if( unixFileLock(pFile, &lock) ){
  23345. tErrno = errno;
  23346. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23347. if( rc!=SQLITE_BUSY ){
  23348. pFile->lastErrno = tErrno;
  23349. }
  23350. goto end_lock;
  23351. }
  23352. }
  23353. /* If control gets to this point, then actually go ahead and make
  23354. ** operating system calls for the specified lock.
  23355. */
  23356. if( eFileLock==SHARED_LOCK ){
  23357. assert( pInode->nShared==0 );
  23358. assert( pInode->eFileLock==0 );
  23359. assert( rc==SQLITE_OK );
  23360. /* Now get the read-lock */
  23361. lock.l_start = SHARED_FIRST;
  23362. lock.l_len = SHARED_SIZE;
  23363. if( unixFileLock(pFile, &lock) ){
  23364. tErrno = errno;
  23365. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23366. }
  23367. /* Drop the temporary PENDING lock */
  23368. lock.l_start = PENDING_BYTE;
  23369. lock.l_len = 1L;
  23370. lock.l_type = F_UNLCK;
  23371. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  23372. /* This could happen with a network mount */
  23373. tErrno = errno;
  23374. rc = SQLITE_IOERR_UNLOCK;
  23375. }
  23376. if( rc ){
  23377. if( rc!=SQLITE_BUSY ){
  23378. pFile->lastErrno = tErrno;
  23379. }
  23380. goto end_lock;
  23381. }else{
  23382. pFile->eFileLock = SHARED_LOCK;
  23383. pInode->nLock++;
  23384. pInode->nShared = 1;
  23385. }
  23386. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  23387. /* We are trying for an exclusive lock but another thread in this
  23388. ** same process is still holding a shared lock. */
  23389. rc = SQLITE_BUSY;
  23390. }else{
  23391. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  23392. ** assumed that there is a SHARED or greater lock on the file
  23393. ** already.
  23394. */
  23395. assert( 0!=pFile->eFileLock );
  23396. lock.l_type = F_WRLCK;
  23397. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  23398. if( eFileLock==RESERVED_LOCK ){
  23399. lock.l_start = RESERVED_BYTE;
  23400. lock.l_len = 1L;
  23401. }else{
  23402. lock.l_start = SHARED_FIRST;
  23403. lock.l_len = SHARED_SIZE;
  23404. }
  23405. if( unixFileLock(pFile, &lock) ){
  23406. tErrno = errno;
  23407. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23408. if( rc!=SQLITE_BUSY ){
  23409. pFile->lastErrno = tErrno;
  23410. }
  23411. }
  23412. }
  23413. #ifdef SQLITE_DEBUG
  23414. /* Set up the transaction-counter change checking flags when
  23415. ** transitioning from a SHARED to a RESERVED lock. The change
  23416. ** from SHARED to RESERVED marks the beginning of a normal
  23417. ** write operation (not a hot journal rollback).
  23418. */
  23419. if( rc==SQLITE_OK
  23420. && pFile->eFileLock<=SHARED_LOCK
  23421. && eFileLock==RESERVED_LOCK
  23422. ){
  23423. pFile->transCntrChng = 0;
  23424. pFile->dbUpdate = 0;
  23425. pFile->inNormalWrite = 1;
  23426. }
  23427. #endif
  23428. if( rc==SQLITE_OK ){
  23429. pFile->eFileLock = eFileLock;
  23430. pInode->eFileLock = eFileLock;
  23431. }else if( eFileLock==EXCLUSIVE_LOCK ){
  23432. pFile->eFileLock = PENDING_LOCK;
  23433. pInode->eFileLock = PENDING_LOCK;
  23434. }
  23435. end_lock:
  23436. unixLeaveMutex();
  23437. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  23438. rc==SQLITE_OK ? "ok" : "failed"));
  23439. return rc;
  23440. }
  23441. /*
  23442. ** Add the file descriptor used by file handle pFile to the corresponding
  23443. ** pUnused list.
  23444. */
  23445. static void setPendingFd(unixFile *pFile){
  23446. unixInodeInfo *pInode = pFile->pInode;
  23447. UnixUnusedFd *p = pFile->pUnused;
  23448. p->pNext = pInode->pUnused;
  23449. pInode->pUnused = p;
  23450. pFile->h = -1;
  23451. pFile->pUnused = 0;
  23452. }
  23453. /*
  23454. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23455. ** must be either NO_LOCK or SHARED_LOCK.
  23456. **
  23457. ** If the locking level of the file descriptor is already at or below
  23458. ** the requested locking level, this routine is a no-op.
  23459. **
  23460. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  23461. ** the byte range is divided into 2 parts and the first part is unlocked then
  23462. ** set to a read lock, then the other part is simply unlocked. This works
  23463. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  23464. ** remove the write lock on a region when a read lock is set.
  23465. */
  23466. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  23467. unixFile *pFile = (unixFile*)id;
  23468. unixInodeInfo *pInode;
  23469. struct flock lock;
  23470. int rc = SQLITE_OK;
  23471. assert( pFile );
  23472. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  23473. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  23474. getpid()));
  23475. assert( eFileLock<=SHARED_LOCK );
  23476. if( pFile->eFileLock<=eFileLock ){
  23477. return SQLITE_OK;
  23478. }
  23479. unixEnterMutex();
  23480. pInode = pFile->pInode;
  23481. assert( pInode->nShared!=0 );
  23482. if( pFile->eFileLock>SHARED_LOCK ){
  23483. assert( pInode->eFileLock==pFile->eFileLock );
  23484. #ifdef SQLITE_DEBUG
  23485. /* When reducing a lock such that other processes can start
  23486. ** reading the database file again, make sure that the
  23487. ** transaction counter was updated if any part of the database
  23488. ** file changed. If the transaction counter is not updated,
  23489. ** other connections to the same file might not realize that
  23490. ** the file has changed and hence might not know to flush their
  23491. ** cache. The use of a stale cache can lead to database corruption.
  23492. */
  23493. pFile->inNormalWrite = 0;
  23494. #endif
  23495. /* downgrading to a shared lock on NFS involves clearing the write lock
  23496. ** before establishing the readlock - to avoid a race condition we downgrade
  23497. ** the lock in 2 blocks, so that part of the range will be covered by a
  23498. ** write lock until the rest is covered by a read lock:
  23499. ** 1: [WWWWW]
  23500. ** 2: [....W]
  23501. ** 3: [RRRRW]
  23502. ** 4: [RRRR.]
  23503. */
  23504. if( eFileLock==SHARED_LOCK ){
  23505. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  23506. (void)handleNFSUnlock;
  23507. assert( handleNFSUnlock==0 );
  23508. #endif
  23509. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23510. if( handleNFSUnlock ){
  23511. int tErrno; /* Error code from system call errors */
  23512. off_t divSize = SHARED_SIZE - 1;
  23513. lock.l_type = F_UNLCK;
  23514. lock.l_whence = SEEK_SET;
  23515. lock.l_start = SHARED_FIRST;
  23516. lock.l_len = divSize;
  23517. if( unixFileLock(pFile, &lock)==(-1) ){
  23518. tErrno = errno;
  23519. rc = SQLITE_IOERR_UNLOCK;
  23520. if( IS_LOCK_ERROR(rc) ){
  23521. pFile->lastErrno = tErrno;
  23522. }
  23523. goto end_unlock;
  23524. }
  23525. lock.l_type = F_RDLCK;
  23526. lock.l_whence = SEEK_SET;
  23527. lock.l_start = SHARED_FIRST;
  23528. lock.l_len = divSize;
  23529. if( unixFileLock(pFile, &lock)==(-1) ){
  23530. tErrno = errno;
  23531. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  23532. if( IS_LOCK_ERROR(rc) ){
  23533. pFile->lastErrno = tErrno;
  23534. }
  23535. goto end_unlock;
  23536. }
  23537. lock.l_type = F_UNLCK;
  23538. lock.l_whence = SEEK_SET;
  23539. lock.l_start = SHARED_FIRST+divSize;
  23540. lock.l_len = SHARED_SIZE-divSize;
  23541. if( unixFileLock(pFile, &lock)==(-1) ){
  23542. tErrno = errno;
  23543. rc = SQLITE_IOERR_UNLOCK;
  23544. if( IS_LOCK_ERROR(rc) ){
  23545. pFile->lastErrno = tErrno;
  23546. }
  23547. goto end_unlock;
  23548. }
  23549. }else
  23550. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23551. {
  23552. lock.l_type = F_RDLCK;
  23553. lock.l_whence = SEEK_SET;
  23554. lock.l_start = SHARED_FIRST;
  23555. lock.l_len = SHARED_SIZE;
  23556. if( unixFileLock(pFile, &lock) ){
  23557. /* In theory, the call to unixFileLock() cannot fail because another
  23558. ** process is holding an incompatible lock. If it does, this
  23559. ** indicates that the other process is not following the locking
  23560. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  23561. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  23562. ** an assert to fail). */
  23563. rc = SQLITE_IOERR_RDLOCK;
  23564. pFile->lastErrno = errno;
  23565. goto end_unlock;
  23566. }
  23567. }
  23568. }
  23569. lock.l_type = F_UNLCK;
  23570. lock.l_whence = SEEK_SET;
  23571. lock.l_start = PENDING_BYTE;
  23572. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  23573. if( unixFileLock(pFile, &lock)==0 ){
  23574. pInode->eFileLock = SHARED_LOCK;
  23575. }else{
  23576. rc = SQLITE_IOERR_UNLOCK;
  23577. pFile->lastErrno = errno;
  23578. goto end_unlock;
  23579. }
  23580. }
  23581. if( eFileLock==NO_LOCK ){
  23582. /* Decrement the shared lock counter. Release the lock using an
  23583. ** OS call only when all threads in this same process have released
  23584. ** the lock.
  23585. */
  23586. pInode->nShared--;
  23587. if( pInode->nShared==0 ){
  23588. lock.l_type = F_UNLCK;
  23589. lock.l_whence = SEEK_SET;
  23590. lock.l_start = lock.l_len = 0L;
  23591. if( unixFileLock(pFile, &lock)==0 ){
  23592. pInode->eFileLock = NO_LOCK;
  23593. }else{
  23594. rc = SQLITE_IOERR_UNLOCK;
  23595. pFile->lastErrno = errno;
  23596. pInode->eFileLock = NO_LOCK;
  23597. pFile->eFileLock = NO_LOCK;
  23598. }
  23599. }
  23600. /* Decrement the count of locks against this same file. When the
  23601. ** count reaches zero, close any other file descriptors whose close
  23602. ** was deferred because of outstanding locks.
  23603. */
  23604. pInode->nLock--;
  23605. assert( pInode->nLock>=0 );
  23606. if( pInode->nLock==0 ){
  23607. closePendingFds(pFile);
  23608. }
  23609. }
  23610. end_unlock:
  23611. unixLeaveMutex();
  23612. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  23613. return rc;
  23614. }
  23615. /*
  23616. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23617. ** must be either NO_LOCK or SHARED_LOCK.
  23618. **
  23619. ** If the locking level of the file descriptor is already at or below
  23620. ** the requested locking level, this routine is a no-op.
  23621. */
  23622. static int unixUnlock(sqlite3_file *id, int eFileLock){
  23623. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  23624. return posixUnlock(id, eFileLock, 0);
  23625. }
  23626. static int unixMapfile(unixFile *pFd, i64 nByte);
  23627. static void unixUnmapfile(unixFile *pFd);
  23628. /*
  23629. ** This function performs the parts of the "close file" operation
  23630. ** common to all locking schemes. It closes the directory and file
  23631. ** handles, if they are valid, and sets all fields of the unixFile
  23632. ** structure to 0.
  23633. **
  23634. ** It is *not* necessary to hold the mutex when this routine is called,
  23635. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  23636. ** vxworksReleaseFileId() routine.
  23637. */
  23638. static int closeUnixFile(sqlite3_file *id){
  23639. unixFile *pFile = (unixFile*)id;
  23640. unixUnmapfile(pFile);
  23641. if( pFile->h>=0 ){
  23642. robust_close(pFile, pFile->h, __LINE__);
  23643. pFile->h = -1;
  23644. }
  23645. #if OS_VXWORKS
  23646. if( pFile->pId ){
  23647. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  23648. osUnlink(pFile->pId->zCanonicalName);
  23649. }
  23650. vxworksReleaseFileId(pFile->pId);
  23651. pFile->pId = 0;
  23652. }
  23653. #endif
  23654. OSTRACE(("CLOSE %-3d\n", pFile->h));
  23655. OpenCounter(-1);
  23656. sqlite3_free(pFile->pUnused);
  23657. memset(pFile, 0, sizeof(unixFile));
  23658. return SQLITE_OK;
  23659. }
  23660. /*
  23661. ** Close a file.
  23662. */
  23663. static int unixClose(sqlite3_file *id){
  23664. int rc = SQLITE_OK;
  23665. unixFile *pFile = (unixFile *)id;
  23666. verifyDbFile(pFile);
  23667. unixUnlock(id, NO_LOCK);
  23668. unixEnterMutex();
  23669. /* unixFile.pInode is always valid here. Otherwise, a different close
  23670. ** routine (e.g. nolockClose()) would be called instead.
  23671. */
  23672. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  23673. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  23674. /* If there are outstanding locks, do not actually close the file just
  23675. ** yet because that would clear those locks. Instead, add the file
  23676. ** descriptor to pInode->pUnused list. It will be automatically closed
  23677. ** when the last lock is cleared.
  23678. */
  23679. setPendingFd(pFile);
  23680. }
  23681. releaseInodeInfo(pFile);
  23682. rc = closeUnixFile(id);
  23683. unixLeaveMutex();
  23684. return rc;
  23685. }
  23686. /************** End of the posix advisory lock implementation *****************
  23687. ******************************************************************************/
  23688. /******************************************************************************
  23689. ****************************** No-op Locking **********************************
  23690. **
  23691. ** Of the various locking implementations available, this is by far the
  23692. ** simplest: locking is ignored. No attempt is made to lock the database
  23693. ** file for reading or writing.
  23694. **
  23695. ** This locking mode is appropriate for use on read-only databases
  23696. ** (ex: databases that are burned into CD-ROM, for example.) It can
  23697. ** also be used if the application employs some external mechanism to
  23698. ** prevent simultaneous access of the same database by two or more
  23699. ** database connections. But there is a serious risk of database
  23700. ** corruption if this locking mode is used in situations where multiple
  23701. ** database connections are accessing the same database file at the same
  23702. ** time and one or more of those connections are writing.
  23703. */
  23704. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  23705. UNUSED_PARAMETER(NotUsed);
  23706. *pResOut = 0;
  23707. return SQLITE_OK;
  23708. }
  23709. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  23710. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23711. return SQLITE_OK;
  23712. }
  23713. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  23714. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23715. return SQLITE_OK;
  23716. }
  23717. /*
  23718. ** Close the file.
  23719. */
  23720. static int nolockClose(sqlite3_file *id) {
  23721. return closeUnixFile(id);
  23722. }
  23723. /******************* End of the no-op lock implementation *********************
  23724. ******************************************************************************/
  23725. /******************************************************************************
  23726. ************************* Begin dot-file Locking ******************************
  23727. **
  23728. ** The dotfile locking implementation uses the existence of separate lock
  23729. ** files (really a directory) to control access to the database. This works
  23730. ** on just about every filesystem imaginable. But there are serious downsides:
  23731. **
  23732. ** (1) There is zero concurrency. A single reader blocks all other
  23733. ** connections from reading or writing the database.
  23734. **
  23735. ** (2) An application crash or power loss can leave stale lock files
  23736. ** sitting around that need to be cleared manually.
  23737. **
  23738. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  23739. ** other locking strategy is available.
  23740. **
  23741. ** Dotfile locking works by creating a subdirectory in the same directory as
  23742. ** the database and with the same name but with a ".lock" extension added.
  23743. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  23744. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  23745. */
  23746. /*
  23747. ** The file suffix added to the data base filename in order to create the
  23748. ** lock directory.
  23749. */
  23750. #define DOTLOCK_SUFFIX ".lock"
  23751. /*
  23752. ** This routine checks if there is a RESERVED lock held on the specified
  23753. ** file by this or any other process. If such a lock is held, set *pResOut
  23754. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23755. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23756. **
  23757. ** In dotfile locking, either a lock exists or it does not. So in this
  23758. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  23759. ** is held on the file and false if the file is unlocked.
  23760. */
  23761. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  23762. int rc = SQLITE_OK;
  23763. int reserved = 0;
  23764. unixFile *pFile = (unixFile*)id;
  23765. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23766. assert( pFile );
  23767. /* Check if a thread in this process holds such a lock */
  23768. if( pFile->eFileLock>SHARED_LOCK ){
  23769. /* Either this connection or some other connection in the same process
  23770. ** holds a lock on the file. No need to check further. */
  23771. reserved = 1;
  23772. }else{
  23773. /* The lock is held if and only if the lockfile exists */
  23774. const char *zLockFile = (const char*)pFile->lockingContext;
  23775. reserved = osAccess(zLockFile, 0)==0;
  23776. }
  23777. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  23778. *pResOut = reserved;
  23779. return rc;
  23780. }
  23781. /*
  23782. ** Lock the file with the lock specified by parameter eFileLock - one
  23783. ** of the following:
  23784. **
  23785. ** (1) SHARED_LOCK
  23786. ** (2) RESERVED_LOCK
  23787. ** (3) PENDING_LOCK
  23788. ** (4) EXCLUSIVE_LOCK
  23789. **
  23790. ** Sometimes when requesting one lock state, additional lock states
  23791. ** are inserted in between. The locking might fail on one of the later
  23792. ** transitions leaving the lock state different from what it started but
  23793. ** still short of its goal. The following chart shows the allowed
  23794. ** transitions and the inserted intermediate states:
  23795. **
  23796. ** UNLOCKED -> SHARED
  23797. ** SHARED -> RESERVED
  23798. ** SHARED -> (PENDING) -> EXCLUSIVE
  23799. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23800. ** PENDING -> EXCLUSIVE
  23801. **
  23802. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23803. ** routine to lower a locking level.
  23804. **
  23805. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  23806. ** But we track the other locking levels internally.
  23807. */
  23808. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  23809. unixFile *pFile = (unixFile*)id;
  23810. char *zLockFile = (char *)pFile->lockingContext;
  23811. int rc = SQLITE_OK;
  23812. /* If we have any lock, then the lock file already exists. All we have
  23813. ** to do is adjust our internal record of the lock level.
  23814. */
  23815. if( pFile->eFileLock > NO_LOCK ){
  23816. pFile->eFileLock = eFileLock;
  23817. /* Always update the timestamp on the old file */
  23818. #ifdef HAVE_UTIME
  23819. utime(zLockFile, NULL);
  23820. #else
  23821. utimes(zLockFile, NULL);
  23822. #endif
  23823. return SQLITE_OK;
  23824. }
  23825. /* grab an exclusive lock */
  23826. rc = osMkdir(zLockFile, 0777);
  23827. if( rc<0 ){
  23828. /* failed to open/create the lock directory */
  23829. int tErrno = errno;
  23830. if( EEXIST == tErrno ){
  23831. rc = SQLITE_BUSY;
  23832. } else {
  23833. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23834. if( IS_LOCK_ERROR(rc) ){
  23835. pFile->lastErrno = tErrno;
  23836. }
  23837. }
  23838. return rc;
  23839. }
  23840. /* got it, set the type and return ok */
  23841. pFile->eFileLock = eFileLock;
  23842. return rc;
  23843. }
  23844. /*
  23845. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23846. ** must be either NO_LOCK or SHARED_LOCK.
  23847. **
  23848. ** If the locking level of the file descriptor is already at or below
  23849. ** the requested locking level, this routine is a no-op.
  23850. **
  23851. ** When the locking level reaches NO_LOCK, delete the lock file.
  23852. */
  23853. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  23854. unixFile *pFile = (unixFile*)id;
  23855. char *zLockFile = (char *)pFile->lockingContext;
  23856. int rc;
  23857. assert( pFile );
  23858. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  23859. pFile->eFileLock, getpid()));
  23860. assert( eFileLock<=SHARED_LOCK );
  23861. /* no-op if possible */
  23862. if( pFile->eFileLock==eFileLock ){
  23863. return SQLITE_OK;
  23864. }
  23865. /* To downgrade to shared, simply update our internal notion of the
  23866. ** lock state. No need to mess with the file on disk.
  23867. */
  23868. if( eFileLock==SHARED_LOCK ){
  23869. pFile->eFileLock = SHARED_LOCK;
  23870. return SQLITE_OK;
  23871. }
  23872. /* To fully unlock the database, delete the lock file */
  23873. assert( eFileLock==NO_LOCK );
  23874. rc = osRmdir(zLockFile);
  23875. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  23876. if( rc<0 ){
  23877. int tErrno = errno;
  23878. rc = 0;
  23879. if( ENOENT != tErrno ){
  23880. rc = SQLITE_IOERR_UNLOCK;
  23881. }
  23882. if( IS_LOCK_ERROR(rc) ){
  23883. pFile->lastErrno = tErrno;
  23884. }
  23885. return rc;
  23886. }
  23887. pFile->eFileLock = NO_LOCK;
  23888. return SQLITE_OK;
  23889. }
  23890. /*
  23891. ** Close a file. Make sure the lock has been released before closing.
  23892. */
  23893. static int dotlockClose(sqlite3_file *id) {
  23894. int rc = SQLITE_OK;
  23895. if( id ){
  23896. unixFile *pFile = (unixFile*)id;
  23897. dotlockUnlock(id, NO_LOCK);
  23898. sqlite3_free(pFile->lockingContext);
  23899. rc = closeUnixFile(id);
  23900. }
  23901. return rc;
  23902. }
  23903. /****************** End of the dot-file lock implementation *******************
  23904. ******************************************************************************/
  23905. /******************************************************************************
  23906. ************************** Begin flock Locking ********************************
  23907. **
  23908. ** Use the flock() system call to do file locking.
  23909. **
  23910. ** flock() locking is like dot-file locking in that the various
  23911. ** fine-grain locking levels supported by SQLite are collapsed into
  23912. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  23913. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  23914. ** still works when you do this, but concurrency is reduced since
  23915. ** only a single process can be reading the database at a time.
  23916. **
  23917. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  23918. ** compiling for VXWORKS.
  23919. */
  23920. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  23921. /*
  23922. ** Retry flock() calls that fail with EINTR
  23923. */
  23924. #ifdef EINTR
  23925. static int robust_flock(int fd, int op){
  23926. int rc;
  23927. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  23928. return rc;
  23929. }
  23930. #else
  23931. # define robust_flock(a,b) flock(a,b)
  23932. #endif
  23933. /*
  23934. ** This routine checks if there is a RESERVED lock held on the specified
  23935. ** file by this or any other process. If such a lock is held, set *pResOut
  23936. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23937. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23938. */
  23939. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  23940. int rc = SQLITE_OK;
  23941. int reserved = 0;
  23942. unixFile *pFile = (unixFile*)id;
  23943. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23944. assert( pFile );
  23945. /* Check if a thread in this process holds such a lock */
  23946. if( pFile->eFileLock>SHARED_LOCK ){
  23947. reserved = 1;
  23948. }
  23949. /* Otherwise see if some other process holds it. */
  23950. if( !reserved ){
  23951. /* attempt to get the lock */
  23952. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  23953. if( !lrc ){
  23954. /* got the lock, unlock it */
  23955. lrc = robust_flock(pFile->h, LOCK_UN);
  23956. if ( lrc ) {
  23957. int tErrno = errno;
  23958. /* unlock failed with an error */
  23959. lrc = SQLITE_IOERR_UNLOCK;
  23960. if( IS_LOCK_ERROR(lrc) ){
  23961. pFile->lastErrno = tErrno;
  23962. rc = lrc;
  23963. }
  23964. }
  23965. } else {
  23966. int tErrno = errno;
  23967. reserved = 1;
  23968. /* someone else might have it reserved */
  23969. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23970. if( IS_LOCK_ERROR(lrc) ){
  23971. pFile->lastErrno = tErrno;
  23972. rc = lrc;
  23973. }
  23974. }
  23975. }
  23976. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  23977. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  23978. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  23979. rc = SQLITE_OK;
  23980. reserved=1;
  23981. }
  23982. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  23983. *pResOut = reserved;
  23984. return rc;
  23985. }
  23986. /*
  23987. ** Lock the file with the lock specified by parameter eFileLock - one
  23988. ** of the following:
  23989. **
  23990. ** (1) SHARED_LOCK
  23991. ** (2) RESERVED_LOCK
  23992. ** (3) PENDING_LOCK
  23993. ** (4) EXCLUSIVE_LOCK
  23994. **
  23995. ** Sometimes when requesting one lock state, additional lock states
  23996. ** are inserted in between. The locking might fail on one of the later
  23997. ** transitions leaving the lock state different from what it started but
  23998. ** still short of its goal. The following chart shows the allowed
  23999. ** transitions and the inserted intermediate states:
  24000. **
  24001. ** UNLOCKED -> SHARED
  24002. ** SHARED -> RESERVED
  24003. ** SHARED -> (PENDING) -> EXCLUSIVE
  24004. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24005. ** PENDING -> EXCLUSIVE
  24006. **
  24007. ** flock() only really support EXCLUSIVE locks. We track intermediate
  24008. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24009. ** above are really EXCLUSIVE locks and exclude all other processes from
  24010. ** access the file.
  24011. **
  24012. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24013. ** routine to lower a locking level.
  24014. */
  24015. static int flockLock(sqlite3_file *id, int eFileLock) {
  24016. int rc = SQLITE_OK;
  24017. unixFile *pFile = (unixFile*)id;
  24018. assert( pFile );
  24019. /* if we already have a lock, it is exclusive.
  24020. ** Just adjust level and punt on outta here. */
  24021. if (pFile->eFileLock > NO_LOCK) {
  24022. pFile->eFileLock = eFileLock;
  24023. return SQLITE_OK;
  24024. }
  24025. /* grab an exclusive lock */
  24026. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  24027. int tErrno = errno;
  24028. /* didn't get, must be busy */
  24029. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24030. if( IS_LOCK_ERROR(rc) ){
  24031. pFile->lastErrno = tErrno;
  24032. }
  24033. } else {
  24034. /* got it, set the type and return ok */
  24035. pFile->eFileLock = eFileLock;
  24036. }
  24037. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  24038. rc==SQLITE_OK ? "ok" : "failed"));
  24039. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24040. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24041. rc = SQLITE_BUSY;
  24042. }
  24043. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24044. return rc;
  24045. }
  24046. /*
  24047. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24048. ** must be either NO_LOCK or SHARED_LOCK.
  24049. **
  24050. ** If the locking level of the file descriptor is already at or below
  24051. ** the requested locking level, this routine is a no-op.
  24052. */
  24053. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  24054. unixFile *pFile = (unixFile*)id;
  24055. assert( pFile );
  24056. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  24057. pFile->eFileLock, getpid()));
  24058. assert( eFileLock<=SHARED_LOCK );
  24059. /* no-op if possible */
  24060. if( pFile->eFileLock==eFileLock ){
  24061. return SQLITE_OK;
  24062. }
  24063. /* shared can just be set because we always have an exclusive */
  24064. if (eFileLock==SHARED_LOCK) {
  24065. pFile->eFileLock = eFileLock;
  24066. return SQLITE_OK;
  24067. }
  24068. /* no, really, unlock. */
  24069. if( robust_flock(pFile->h, LOCK_UN) ){
  24070. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24071. return SQLITE_OK;
  24072. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24073. return SQLITE_IOERR_UNLOCK;
  24074. }else{
  24075. pFile->eFileLock = NO_LOCK;
  24076. return SQLITE_OK;
  24077. }
  24078. }
  24079. /*
  24080. ** Close a file.
  24081. */
  24082. static int flockClose(sqlite3_file *id) {
  24083. int rc = SQLITE_OK;
  24084. if( id ){
  24085. flockUnlock(id, NO_LOCK);
  24086. rc = closeUnixFile(id);
  24087. }
  24088. return rc;
  24089. }
  24090. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  24091. /******************* End of the flock lock implementation *********************
  24092. ******************************************************************************/
  24093. /******************************************************************************
  24094. ************************ Begin Named Semaphore Locking ************************
  24095. **
  24096. ** Named semaphore locking is only supported on VxWorks.
  24097. **
  24098. ** Semaphore locking is like dot-lock and flock in that it really only
  24099. ** supports EXCLUSIVE locking. Only a single process can read or write
  24100. ** the database file at a time. This reduces potential concurrency, but
  24101. ** makes the lock implementation much easier.
  24102. */
  24103. #if OS_VXWORKS
  24104. /*
  24105. ** This routine checks if there is a RESERVED lock held on the specified
  24106. ** file by this or any other process. If such a lock is held, set *pResOut
  24107. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24108. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24109. */
  24110. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24111. int rc = SQLITE_OK;
  24112. int reserved = 0;
  24113. unixFile *pFile = (unixFile*)id;
  24114. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24115. assert( pFile );
  24116. /* Check if a thread in this process holds such a lock */
  24117. if( pFile->eFileLock>SHARED_LOCK ){
  24118. reserved = 1;
  24119. }
  24120. /* Otherwise see if some other process holds it. */
  24121. if( !reserved ){
  24122. sem_t *pSem = pFile->pInode->pSem;
  24123. struct stat statBuf;
  24124. if( sem_trywait(pSem)==-1 ){
  24125. int tErrno = errno;
  24126. if( EAGAIN != tErrno ){
  24127. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  24128. pFile->lastErrno = tErrno;
  24129. } else {
  24130. /* someone else has the lock when we are in NO_LOCK */
  24131. reserved = (pFile->eFileLock < SHARED_LOCK);
  24132. }
  24133. }else{
  24134. /* we could have it if we want it */
  24135. sem_post(pSem);
  24136. }
  24137. }
  24138. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  24139. *pResOut = reserved;
  24140. return rc;
  24141. }
  24142. /*
  24143. ** Lock the file with the lock specified by parameter eFileLock - one
  24144. ** of the following:
  24145. **
  24146. ** (1) SHARED_LOCK
  24147. ** (2) RESERVED_LOCK
  24148. ** (3) PENDING_LOCK
  24149. ** (4) EXCLUSIVE_LOCK
  24150. **
  24151. ** Sometimes when requesting one lock state, additional lock states
  24152. ** are inserted in between. The locking might fail on one of the later
  24153. ** transitions leaving the lock state different from what it started but
  24154. ** still short of its goal. The following chart shows the allowed
  24155. ** transitions and the inserted intermediate states:
  24156. **
  24157. ** UNLOCKED -> SHARED
  24158. ** SHARED -> RESERVED
  24159. ** SHARED -> (PENDING) -> EXCLUSIVE
  24160. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24161. ** PENDING -> EXCLUSIVE
  24162. **
  24163. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  24164. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24165. ** above are really EXCLUSIVE locks and exclude all other processes from
  24166. ** access the file.
  24167. **
  24168. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24169. ** routine to lower a locking level.
  24170. */
  24171. static int semLock(sqlite3_file *id, int eFileLock) {
  24172. unixFile *pFile = (unixFile*)id;
  24173. int fd;
  24174. sem_t *pSem = pFile->pInode->pSem;
  24175. int rc = SQLITE_OK;
  24176. /* if we already have a lock, it is exclusive.
  24177. ** Just adjust level and punt on outta here. */
  24178. if (pFile->eFileLock > NO_LOCK) {
  24179. pFile->eFileLock = eFileLock;
  24180. rc = SQLITE_OK;
  24181. goto sem_end_lock;
  24182. }
  24183. /* lock semaphore now but bail out when already locked. */
  24184. if( sem_trywait(pSem)==-1 ){
  24185. rc = SQLITE_BUSY;
  24186. goto sem_end_lock;
  24187. }
  24188. /* got it, set the type and return ok */
  24189. pFile->eFileLock = eFileLock;
  24190. sem_end_lock:
  24191. return rc;
  24192. }
  24193. /*
  24194. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24195. ** must be either NO_LOCK or SHARED_LOCK.
  24196. **
  24197. ** If the locking level of the file descriptor is already at or below
  24198. ** the requested locking level, this routine is a no-op.
  24199. */
  24200. static int semUnlock(sqlite3_file *id, int eFileLock) {
  24201. unixFile *pFile = (unixFile*)id;
  24202. sem_t *pSem = pFile->pInode->pSem;
  24203. assert( pFile );
  24204. assert( pSem );
  24205. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  24206. pFile->eFileLock, getpid()));
  24207. assert( eFileLock<=SHARED_LOCK );
  24208. /* no-op if possible */
  24209. if( pFile->eFileLock==eFileLock ){
  24210. return SQLITE_OK;
  24211. }
  24212. /* shared can just be set because we always have an exclusive */
  24213. if (eFileLock==SHARED_LOCK) {
  24214. pFile->eFileLock = eFileLock;
  24215. return SQLITE_OK;
  24216. }
  24217. /* no, really unlock. */
  24218. if ( sem_post(pSem)==-1 ) {
  24219. int rc, tErrno = errno;
  24220. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  24221. if( IS_LOCK_ERROR(rc) ){
  24222. pFile->lastErrno = tErrno;
  24223. }
  24224. return rc;
  24225. }
  24226. pFile->eFileLock = NO_LOCK;
  24227. return SQLITE_OK;
  24228. }
  24229. /*
  24230. ** Close a file.
  24231. */
  24232. static int semClose(sqlite3_file *id) {
  24233. if( id ){
  24234. unixFile *pFile = (unixFile*)id;
  24235. semUnlock(id, NO_LOCK);
  24236. assert( pFile );
  24237. unixEnterMutex();
  24238. releaseInodeInfo(pFile);
  24239. unixLeaveMutex();
  24240. closeUnixFile(id);
  24241. }
  24242. return SQLITE_OK;
  24243. }
  24244. #endif /* OS_VXWORKS */
  24245. /*
  24246. ** Named semaphore locking is only available on VxWorks.
  24247. **
  24248. *************** End of the named semaphore lock implementation ****************
  24249. ******************************************************************************/
  24250. /******************************************************************************
  24251. *************************** Begin AFP Locking *********************************
  24252. **
  24253. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  24254. ** on Apple Macintosh computers - both OS9 and OSX.
  24255. **
  24256. ** Third-party implementations of AFP are available. But this code here
  24257. ** only works on OSX.
  24258. */
  24259. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24260. /*
  24261. ** The afpLockingContext structure contains all afp lock specific state
  24262. */
  24263. typedef struct afpLockingContext afpLockingContext;
  24264. struct afpLockingContext {
  24265. int reserved;
  24266. const char *dbPath; /* Name of the open file */
  24267. };
  24268. struct ByteRangeLockPB2
  24269. {
  24270. unsigned long long offset; /* offset to first byte to lock */
  24271. unsigned long long length; /* nbr of bytes to lock */
  24272. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  24273. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24274. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24275. int fd; /* file desc to assoc this lock with */
  24276. };
  24277. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24278. /*
  24279. ** This is a utility for setting or clearing a bit-range lock on an
  24280. ** AFP filesystem.
  24281. **
  24282. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24283. */
  24284. static int afpSetLock(
  24285. const char *path, /* Name of the file to be locked or unlocked */
  24286. unixFile *pFile, /* Open file descriptor on path */
  24287. unsigned long long offset, /* First byte to be locked */
  24288. unsigned long long length, /* Number of bytes to lock */
  24289. int setLockFlag /* True to set lock. False to clear lock */
  24290. ){
  24291. struct ByteRangeLockPB2 pb;
  24292. int err;
  24293. pb.unLockFlag = setLockFlag ? 0 : 1;
  24294. pb.startEndFlag = 0;
  24295. pb.offset = offset;
  24296. pb.length = length;
  24297. pb.fd = pFile->h;
  24298. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24299. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24300. offset, length));
  24301. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24302. if ( err==-1 ) {
  24303. int rc;
  24304. int tErrno = errno;
  24305. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24306. path, tErrno, strerror(tErrno)));
  24307. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24308. rc = SQLITE_BUSY;
  24309. #else
  24310. rc = sqliteErrorFromPosixError(tErrno,
  24311. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24312. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24313. if( IS_LOCK_ERROR(rc) ){
  24314. pFile->lastErrno = tErrno;
  24315. }
  24316. return rc;
  24317. } else {
  24318. return SQLITE_OK;
  24319. }
  24320. }
  24321. /*
  24322. ** This routine checks if there is a RESERVED lock held on the specified
  24323. ** file by this or any other process. If such a lock is held, set *pResOut
  24324. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24325. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24326. */
  24327. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24328. int rc = SQLITE_OK;
  24329. int reserved = 0;
  24330. unixFile *pFile = (unixFile*)id;
  24331. afpLockingContext *context;
  24332. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24333. assert( pFile );
  24334. context = (afpLockingContext *) pFile->lockingContext;
  24335. if( context->reserved ){
  24336. *pResOut = 1;
  24337. return SQLITE_OK;
  24338. }
  24339. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24340. /* Check if a thread in this process holds such a lock */
  24341. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24342. reserved = 1;
  24343. }
  24344. /* Otherwise see if some other process holds it.
  24345. */
  24346. if( !reserved ){
  24347. /* lock the RESERVED byte */
  24348. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24349. if( SQLITE_OK==lrc ){
  24350. /* if we succeeded in taking the reserved lock, unlock it to restore
  24351. ** the original state */
  24352. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24353. } else {
  24354. /* if we failed to get the lock then someone else must have it */
  24355. reserved = 1;
  24356. }
  24357. if( IS_LOCK_ERROR(lrc) ){
  24358. rc=lrc;
  24359. }
  24360. }
  24361. unixLeaveMutex();
  24362. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  24363. *pResOut = reserved;
  24364. return rc;
  24365. }
  24366. /*
  24367. ** Lock the file with the lock specified by parameter eFileLock - one
  24368. ** of the following:
  24369. **
  24370. ** (1) SHARED_LOCK
  24371. ** (2) RESERVED_LOCK
  24372. ** (3) PENDING_LOCK
  24373. ** (4) EXCLUSIVE_LOCK
  24374. **
  24375. ** Sometimes when requesting one lock state, additional lock states
  24376. ** are inserted in between. The locking might fail on one of the later
  24377. ** transitions leaving the lock state different from what it started but
  24378. ** still short of its goal. The following chart shows the allowed
  24379. ** transitions and the inserted intermediate states:
  24380. **
  24381. ** UNLOCKED -> SHARED
  24382. ** SHARED -> RESERVED
  24383. ** SHARED -> (PENDING) -> EXCLUSIVE
  24384. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24385. ** PENDING -> EXCLUSIVE
  24386. **
  24387. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24388. ** routine to lower a locking level.
  24389. */
  24390. static int afpLock(sqlite3_file *id, int eFileLock){
  24391. int rc = SQLITE_OK;
  24392. unixFile *pFile = (unixFile*)id;
  24393. unixInodeInfo *pInode = pFile->pInode;
  24394. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24395. assert( pFile );
  24396. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  24397. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24398. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  24399. /* If there is already a lock of this type or more restrictive on the
  24400. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  24401. ** unixEnterMutex() hasn't been called yet.
  24402. */
  24403. if( pFile->eFileLock>=eFileLock ){
  24404. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  24405. azFileLock(eFileLock)));
  24406. return SQLITE_OK;
  24407. }
  24408. /* Make sure the locking sequence is correct
  24409. ** (1) We never move from unlocked to anything higher than shared lock.
  24410. ** (2) SQLite never explicitly requests a pendig lock.
  24411. ** (3) A shared lock is always held when a reserve lock is requested.
  24412. */
  24413. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24414. assert( eFileLock!=PENDING_LOCK );
  24415. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24416. /* This mutex is needed because pFile->pInode is shared across threads
  24417. */
  24418. unixEnterMutex();
  24419. pInode = pFile->pInode;
  24420. /* If some thread using this PID has a lock via a different unixFile*
  24421. ** handle that precludes the requested lock, return BUSY.
  24422. */
  24423. if( (pFile->eFileLock!=pInode->eFileLock &&
  24424. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24425. ){
  24426. rc = SQLITE_BUSY;
  24427. goto afp_end_lock;
  24428. }
  24429. /* If a SHARED lock is requested, and some thread using this PID already
  24430. ** has a SHARED or RESERVED lock, then increment reference counts and
  24431. ** return SQLITE_OK.
  24432. */
  24433. if( eFileLock==SHARED_LOCK &&
  24434. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24435. assert( eFileLock==SHARED_LOCK );
  24436. assert( pFile->eFileLock==0 );
  24437. assert( pInode->nShared>0 );
  24438. pFile->eFileLock = SHARED_LOCK;
  24439. pInode->nShared++;
  24440. pInode->nLock++;
  24441. goto afp_end_lock;
  24442. }
  24443. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24444. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24445. ** be released.
  24446. */
  24447. if( eFileLock==SHARED_LOCK
  24448. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24449. ){
  24450. int failed;
  24451. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  24452. if (failed) {
  24453. rc = failed;
  24454. goto afp_end_lock;
  24455. }
  24456. }
  24457. /* If control gets to this point, then actually go ahead and make
  24458. ** operating system calls for the specified lock.
  24459. */
  24460. if( eFileLock==SHARED_LOCK ){
  24461. int lrc1, lrc2, lrc1Errno = 0;
  24462. long lk, mask;
  24463. assert( pInode->nShared==0 );
  24464. assert( pInode->eFileLock==0 );
  24465. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  24466. /* Now get the read-lock SHARED_LOCK */
  24467. /* note that the quality of the randomness doesn't matter that much */
  24468. lk = random();
  24469. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  24470. lrc1 = afpSetLock(context->dbPath, pFile,
  24471. SHARED_FIRST+pInode->sharedByte, 1, 1);
  24472. if( IS_LOCK_ERROR(lrc1) ){
  24473. lrc1Errno = pFile->lastErrno;
  24474. }
  24475. /* Drop the temporary PENDING lock */
  24476. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24477. if( IS_LOCK_ERROR(lrc1) ) {
  24478. pFile->lastErrno = lrc1Errno;
  24479. rc = lrc1;
  24480. goto afp_end_lock;
  24481. } else if( IS_LOCK_ERROR(lrc2) ){
  24482. rc = lrc2;
  24483. goto afp_end_lock;
  24484. } else if( lrc1 != SQLITE_OK ) {
  24485. rc = lrc1;
  24486. } else {
  24487. pFile->eFileLock = SHARED_LOCK;
  24488. pInode->nLock++;
  24489. pInode->nShared = 1;
  24490. }
  24491. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24492. /* We are trying for an exclusive lock but another thread in this
  24493. ** same process is still holding a shared lock. */
  24494. rc = SQLITE_BUSY;
  24495. }else{
  24496. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24497. ** assumed that there is a SHARED or greater lock on the file
  24498. ** already.
  24499. */
  24500. int failed = 0;
  24501. assert( 0!=pFile->eFileLock );
  24502. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  24503. /* Acquire a RESERVED lock */
  24504. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24505. if( !failed ){
  24506. context->reserved = 1;
  24507. }
  24508. }
  24509. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  24510. /* Acquire an EXCLUSIVE lock */
  24511. /* Remove the shared lock before trying the range. we'll need to
  24512. ** reestablish the shared lock if we can't get the afpUnlock
  24513. */
  24514. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  24515. pInode->sharedByte, 1, 0)) ){
  24516. int failed2 = SQLITE_OK;
  24517. /* now attemmpt to get the exclusive lock range */
  24518. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  24519. SHARED_SIZE, 1);
  24520. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  24521. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  24522. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  24523. ** a critical I/O error
  24524. */
  24525. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  24526. SQLITE_IOERR_LOCK;
  24527. goto afp_end_lock;
  24528. }
  24529. }else{
  24530. rc = failed;
  24531. }
  24532. }
  24533. if( failed ){
  24534. rc = failed;
  24535. }
  24536. }
  24537. if( rc==SQLITE_OK ){
  24538. pFile->eFileLock = eFileLock;
  24539. pInode->eFileLock = eFileLock;
  24540. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24541. pFile->eFileLock = PENDING_LOCK;
  24542. pInode->eFileLock = PENDING_LOCK;
  24543. }
  24544. afp_end_lock:
  24545. unixLeaveMutex();
  24546. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  24547. rc==SQLITE_OK ? "ok" : "failed"));
  24548. return rc;
  24549. }
  24550. /*
  24551. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24552. ** must be either NO_LOCK or SHARED_LOCK.
  24553. **
  24554. ** If the locking level of the file descriptor is already at or below
  24555. ** the requested locking level, this routine is a no-op.
  24556. */
  24557. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  24558. int rc = SQLITE_OK;
  24559. unixFile *pFile = (unixFile*)id;
  24560. unixInodeInfo *pInode;
  24561. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24562. int skipShared = 0;
  24563. #ifdef SQLITE_TEST
  24564. int h = pFile->h;
  24565. #endif
  24566. assert( pFile );
  24567. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  24568. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  24569. getpid()));
  24570. assert( eFileLock<=SHARED_LOCK );
  24571. if( pFile->eFileLock<=eFileLock ){
  24572. return SQLITE_OK;
  24573. }
  24574. unixEnterMutex();
  24575. pInode = pFile->pInode;
  24576. assert( pInode->nShared!=0 );
  24577. if( pFile->eFileLock>SHARED_LOCK ){
  24578. assert( pInode->eFileLock==pFile->eFileLock );
  24579. SimulateIOErrorBenign(1);
  24580. SimulateIOError( h=(-1) )
  24581. SimulateIOErrorBenign(0);
  24582. #ifdef SQLITE_DEBUG
  24583. /* When reducing a lock such that other processes can start
  24584. ** reading the database file again, make sure that the
  24585. ** transaction counter was updated if any part of the database
  24586. ** file changed. If the transaction counter is not updated,
  24587. ** other connections to the same file might not realize that
  24588. ** the file has changed and hence might not know to flush their
  24589. ** cache. The use of a stale cache can lead to database corruption.
  24590. */
  24591. assert( pFile->inNormalWrite==0
  24592. || pFile->dbUpdate==0
  24593. || pFile->transCntrChng==1 );
  24594. pFile->inNormalWrite = 0;
  24595. #endif
  24596. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  24597. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  24598. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  24599. /* only re-establish the shared lock if necessary */
  24600. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24601. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  24602. } else {
  24603. skipShared = 1;
  24604. }
  24605. }
  24606. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  24607. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24608. }
  24609. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  24610. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24611. if( !rc ){
  24612. context->reserved = 0;
  24613. }
  24614. }
  24615. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  24616. pInode->eFileLock = SHARED_LOCK;
  24617. }
  24618. }
  24619. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  24620. /* Decrement the shared lock counter. Release the lock using an
  24621. ** OS call only when all threads in this same process have released
  24622. ** the lock.
  24623. */
  24624. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24625. pInode->nShared--;
  24626. if( pInode->nShared==0 ){
  24627. SimulateIOErrorBenign(1);
  24628. SimulateIOError( h=(-1) )
  24629. SimulateIOErrorBenign(0);
  24630. if( !skipShared ){
  24631. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  24632. }
  24633. if( !rc ){
  24634. pInode->eFileLock = NO_LOCK;
  24635. pFile->eFileLock = NO_LOCK;
  24636. }
  24637. }
  24638. if( rc==SQLITE_OK ){
  24639. pInode->nLock--;
  24640. assert( pInode->nLock>=0 );
  24641. if( pInode->nLock==0 ){
  24642. closePendingFds(pFile);
  24643. }
  24644. }
  24645. }
  24646. unixLeaveMutex();
  24647. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24648. return rc;
  24649. }
  24650. /*
  24651. ** Close a file & cleanup AFP specific locking context
  24652. */
  24653. static int afpClose(sqlite3_file *id) {
  24654. int rc = SQLITE_OK;
  24655. if( id ){
  24656. unixFile *pFile = (unixFile*)id;
  24657. afpUnlock(id, NO_LOCK);
  24658. unixEnterMutex();
  24659. if( pFile->pInode && pFile->pInode->nLock ){
  24660. /* If there are outstanding locks, do not actually close the file just
  24661. ** yet because that would clear those locks. Instead, add the file
  24662. ** descriptor to pInode->aPending. It will be automatically closed when
  24663. ** the last lock is cleared.
  24664. */
  24665. setPendingFd(pFile);
  24666. }
  24667. releaseInodeInfo(pFile);
  24668. sqlite3_free(pFile->lockingContext);
  24669. rc = closeUnixFile(id);
  24670. unixLeaveMutex();
  24671. }
  24672. return rc;
  24673. }
  24674. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24675. /*
  24676. ** The code above is the AFP lock implementation. The code is specific
  24677. ** to MacOSX and does not work on other unix platforms. No alternative
  24678. ** is available. If you don't compile for a mac, then the "unix-afp"
  24679. ** VFS is not available.
  24680. **
  24681. ********************* End of the AFP lock implementation **********************
  24682. ******************************************************************************/
  24683. /******************************************************************************
  24684. *************************** Begin NFS Locking ********************************/
  24685. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24686. /*
  24687. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24688. ** must be either NO_LOCK or SHARED_LOCK.
  24689. **
  24690. ** If the locking level of the file descriptor is already at or below
  24691. ** the requested locking level, this routine is a no-op.
  24692. */
  24693. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  24694. return posixUnlock(id, eFileLock, 1);
  24695. }
  24696. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24697. /*
  24698. ** The code above is the NFS lock implementation. The code is specific
  24699. ** to MacOSX and does not work on other unix platforms. No alternative
  24700. ** is available.
  24701. **
  24702. ********************* End of the NFS lock implementation **********************
  24703. ******************************************************************************/
  24704. /******************************************************************************
  24705. **************** Non-locking sqlite3_file methods *****************************
  24706. **
  24707. ** The next division contains implementations for all methods of the
  24708. ** sqlite3_file object other than the locking methods. The locking
  24709. ** methods were defined in divisions above (one locking method per
  24710. ** division). Those methods that are common to all locking modes
  24711. ** are gather together into this division.
  24712. */
  24713. /*
  24714. ** Seek to the offset passed as the second argument, then read cnt
  24715. ** bytes into pBuf. Return the number of bytes actually read.
  24716. **
  24717. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  24718. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  24719. ** one system to another. Since SQLite does not define USE_PREAD
  24720. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  24721. ** See tickets #2741 and #2681.
  24722. **
  24723. ** To avoid stomping the errno value on a failed read the lastErrno value
  24724. ** is set before returning.
  24725. */
  24726. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  24727. int got;
  24728. int prior = 0;
  24729. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  24730. i64 newOffset;
  24731. #endif
  24732. TIMER_START;
  24733. assert( cnt==(cnt&0x1ffff) );
  24734. cnt &= 0x1ffff;
  24735. do{
  24736. #if defined(USE_PREAD)
  24737. got = osPread(id->h, pBuf, cnt, offset);
  24738. SimulateIOError( got = -1 );
  24739. #elif defined(USE_PREAD64)
  24740. got = osPread64(id->h, pBuf, cnt, offset);
  24741. SimulateIOError( got = -1 );
  24742. #else
  24743. newOffset = lseek(id->h, offset, SEEK_SET);
  24744. SimulateIOError( newOffset-- );
  24745. if( newOffset!=offset ){
  24746. if( newOffset == -1 ){
  24747. ((unixFile*)id)->lastErrno = errno;
  24748. }else{
  24749. ((unixFile*)id)->lastErrno = 0;
  24750. }
  24751. return -1;
  24752. }
  24753. got = osRead(id->h, pBuf, cnt);
  24754. #endif
  24755. if( got==cnt ) break;
  24756. if( got<0 ){
  24757. if( errno==EINTR ){ got = 1; continue; }
  24758. prior = 0;
  24759. ((unixFile*)id)->lastErrno = errno;
  24760. break;
  24761. }else if( got>0 ){
  24762. cnt -= got;
  24763. offset += got;
  24764. prior += got;
  24765. pBuf = (void*)(got + (char*)pBuf);
  24766. }
  24767. }while( got>0 );
  24768. TIMER_END;
  24769. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  24770. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  24771. return got+prior;
  24772. }
  24773. /*
  24774. ** Read data from a file into a buffer. Return SQLITE_OK if all
  24775. ** bytes were read successfully and SQLITE_IOERR if anything goes
  24776. ** wrong.
  24777. */
  24778. static int unixRead(
  24779. sqlite3_file *id,
  24780. void *pBuf,
  24781. int amt,
  24782. sqlite3_int64 offset
  24783. ){
  24784. unixFile *pFile = (unixFile *)id;
  24785. int got;
  24786. assert( id );
  24787. assert( offset>=0 );
  24788. assert( amt>0 );
  24789. /* If this is a database file (not a journal, master-journal or temp
  24790. ** file), the bytes in the locking range should never be read or written. */
  24791. #if 0
  24792. assert( pFile->pUnused==0
  24793. || offset>=PENDING_BYTE+512
  24794. || offset+amt<=PENDING_BYTE
  24795. );
  24796. #endif
  24797. #if SQLITE_MAX_MMAP_SIZE>0
  24798. /* Deal with as much of this read request as possible by transfering
  24799. ** data from the memory mapping using memcpy(). */
  24800. if( offset<pFile->mmapSize ){
  24801. if( offset+amt <= pFile->mmapSize ){
  24802. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  24803. return SQLITE_OK;
  24804. }else{
  24805. int nCopy = pFile->mmapSize - offset;
  24806. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  24807. pBuf = &((u8 *)pBuf)[nCopy];
  24808. amt -= nCopy;
  24809. offset += nCopy;
  24810. }
  24811. }
  24812. #endif
  24813. got = seekAndRead(pFile, offset, pBuf, amt);
  24814. if( got==amt ){
  24815. return SQLITE_OK;
  24816. }else if( got<0 ){
  24817. /* lastErrno set by seekAndRead */
  24818. return SQLITE_IOERR_READ;
  24819. }else{
  24820. pFile->lastErrno = 0; /* not a system error */
  24821. /* Unread parts of the buffer must be zero-filled */
  24822. memset(&((char*)pBuf)[got], 0, amt-got);
  24823. return SQLITE_IOERR_SHORT_READ;
  24824. }
  24825. }
  24826. /*
  24827. ** Attempt to seek the file-descriptor passed as the first argument to
  24828. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  24829. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  24830. ** return the actual number of bytes written (which may be less than
  24831. ** nBuf).
  24832. */
  24833. static int seekAndWriteFd(
  24834. int fd, /* File descriptor to write to */
  24835. i64 iOff, /* File offset to begin writing at */
  24836. const void *pBuf, /* Copy data from this buffer to the file */
  24837. int nBuf, /* Size of buffer pBuf in bytes */
  24838. int *piErrno /* OUT: Error number if error occurs */
  24839. ){
  24840. int rc = 0; /* Value returned by system call */
  24841. assert( nBuf==(nBuf&0x1ffff) );
  24842. nBuf &= 0x1ffff;
  24843. TIMER_START;
  24844. #if defined(USE_PREAD)
  24845. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  24846. #elif defined(USE_PREAD64)
  24847. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  24848. #else
  24849. do{
  24850. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  24851. SimulateIOError( iSeek-- );
  24852. if( iSeek!=iOff ){
  24853. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  24854. return -1;
  24855. }
  24856. rc = osWrite(fd, pBuf, nBuf);
  24857. }while( rc<0 && errno==EINTR );
  24858. #endif
  24859. TIMER_END;
  24860. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  24861. if( rc<0 && piErrno ) *piErrno = errno;
  24862. return rc;
  24863. }
  24864. /*
  24865. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  24866. ** Return the number of bytes actually read. Update the offset.
  24867. **
  24868. ** To avoid stomping the errno value on a failed write the lastErrno value
  24869. ** is set before returning.
  24870. */
  24871. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  24872. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  24873. }
  24874. /*
  24875. ** Write data from a buffer into a file. Return SQLITE_OK on success
  24876. ** or some other error code on failure.
  24877. */
  24878. static int unixWrite(
  24879. sqlite3_file *id,
  24880. const void *pBuf,
  24881. int amt,
  24882. sqlite3_int64 offset
  24883. ){
  24884. unixFile *pFile = (unixFile*)id;
  24885. int wrote = 0;
  24886. assert( id );
  24887. assert( amt>0 );
  24888. /* If this is a database file (not a journal, master-journal or temp
  24889. ** file), the bytes in the locking range should never be read or written. */
  24890. #if 0
  24891. assert( pFile->pUnused==0
  24892. || offset>=PENDING_BYTE+512
  24893. || offset+amt<=PENDING_BYTE
  24894. );
  24895. #endif
  24896. #ifdef SQLITE_DEBUG
  24897. /* If we are doing a normal write to a database file (as opposed to
  24898. ** doing a hot-journal rollback or a write to some file other than a
  24899. ** normal database file) then record the fact that the database
  24900. ** has changed. If the transaction counter is modified, record that
  24901. ** fact too.
  24902. */
  24903. if( pFile->inNormalWrite ){
  24904. pFile->dbUpdate = 1; /* The database has been modified */
  24905. if( offset<=24 && offset+amt>=27 ){
  24906. int rc;
  24907. char oldCntr[4];
  24908. SimulateIOErrorBenign(1);
  24909. rc = seekAndRead(pFile, 24, oldCntr, 4);
  24910. SimulateIOErrorBenign(0);
  24911. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  24912. pFile->transCntrChng = 1; /* The transaction counter has changed */
  24913. }
  24914. }
  24915. }
  24916. #endif
  24917. #if SQLITE_MAX_MMAP_SIZE>0
  24918. /* Deal with as much of this write request as possible by transfering
  24919. ** data from the memory mapping using memcpy(). */
  24920. if( offset<pFile->mmapSize ){
  24921. if( offset+amt <= pFile->mmapSize ){
  24922. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  24923. return SQLITE_OK;
  24924. }else{
  24925. int nCopy = pFile->mmapSize - offset;
  24926. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  24927. pBuf = &((u8 *)pBuf)[nCopy];
  24928. amt -= nCopy;
  24929. offset += nCopy;
  24930. }
  24931. }
  24932. #endif
  24933. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  24934. amt -= wrote;
  24935. offset += wrote;
  24936. pBuf = &((char*)pBuf)[wrote];
  24937. }
  24938. SimulateIOError(( wrote=(-1), amt=1 ));
  24939. SimulateDiskfullError(( wrote=0, amt=1 ));
  24940. if( amt>0 ){
  24941. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  24942. /* lastErrno set by seekAndWrite */
  24943. return SQLITE_IOERR_WRITE;
  24944. }else{
  24945. pFile->lastErrno = 0; /* not a system error */
  24946. return SQLITE_FULL;
  24947. }
  24948. }
  24949. return SQLITE_OK;
  24950. }
  24951. #ifdef SQLITE_TEST
  24952. /*
  24953. ** Count the number of fullsyncs and normal syncs. This is used to test
  24954. ** that syncs and fullsyncs are occurring at the right times.
  24955. */
  24956. SQLITE_API int sqlite3_sync_count = 0;
  24957. SQLITE_API int sqlite3_fullsync_count = 0;
  24958. #endif
  24959. /*
  24960. ** We do not trust systems to provide a working fdatasync(). Some do.
  24961. ** Others do no. To be safe, we will stick with the (slightly slower)
  24962. ** fsync(). If you know that your system does support fdatasync() correctly,
  24963. ** then simply compile with -Dfdatasync=fdatasync
  24964. */
  24965. #if !defined(fdatasync)
  24966. # define fdatasync fsync
  24967. #endif
  24968. /*
  24969. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  24970. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  24971. ** only available on Mac OS X. But that could change.
  24972. */
  24973. #ifdef F_FULLFSYNC
  24974. # define HAVE_FULLFSYNC 1
  24975. #else
  24976. # define HAVE_FULLFSYNC 0
  24977. #endif
  24978. /*
  24979. ** The fsync() system call does not work as advertised on many
  24980. ** unix systems. The following procedure is an attempt to make
  24981. ** it work better.
  24982. **
  24983. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  24984. ** for testing when we want to run through the test suite quickly.
  24985. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  24986. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  24987. ** or power failure will likely corrupt the database file.
  24988. **
  24989. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  24990. ** The idea behind dataOnly is that it should only write the file content
  24991. ** to disk, not the inode. We only set dataOnly if the file size is
  24992. ** unchanged since the file size is part of the inode. However,
  24993. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  24994. ** file size has changed. The only real difference between fdatasync()
  24995. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  24996. ** inode if the mtime or owner or other inode attributes have changed.
  24997. ** We only care about the file size, not the other file attributes, so
  24998. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  24999. ** So, we always use fdatasync() if it is available, regardless of
  25000. ** the value of the dataOnly flag.
  25001. */
  25002. static int full_fsync(int fd, int fullSync, int dataOnly){
  25003. int rc;
  25004. /* The following "ifdef/elif/else/" block has the same structure as
  25005. ** the one below. It is replicated here solely to avoid cluttering
  25006. ** up the real code with the UNUSED_PARAMETER() macros.
  25007. */
  25008. #ifdef SQLITE_NO_SYNC
  25009. UNUSED_PARAMETER(fd);
  25010. UNUSED_PARAMETER(fullSync);
  25011. UNUSED_PARAMETER(dataOnly);
  25012. #elif HAVE_FULLFSYNC
  25013. UNUSED_PARAMETER(dataOnly);
  25014. #else
  25015. UNUSED_PARAMETER(fullSync);
  25016. UNUSED_PARAMETER(dataOnly);
  25017. #endif
  25018. /* Record the number of times that we do a normal fsync() and
  25019. ** FULLSYNC. This is used during testing to verify that this procedure
  25020. ** gets called with the correct arguments.
  25021. */
  25022. #ifdef SQLITE_TEST
  25023. if( fullSync ) sqlite3_fullsync_count++;
  25024. sqlite3_sync_count++;
  25025. #endif
  25026. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25027. ** no-op
  25028. */
  25029. #ifdef SQLITE_NO_SYNC
  25030. rc = SQLITE_OK;
  25031. #elif HAVE_FULLFSYNC
  25032. if( fullSync ){
  25033. rc = osFcntl(fd, F_FULLFSYNC, 0);
  25034. }else{
  25035. rc = 1;
  25036. }
  25037. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  25038. ** It shouldn't be possible for fullfsync to fail on the local
  25039. ** file system (on OSX), so failure indicates that FULLFSYNC
  25040. ** isn't supported for this file system. So, attempt an fsync
  25041. ** and (for now) ignore the overhead of a superfluous fcntl call.
  25042. ** It'd be better to detect fullfsync support once and avoid
  25043. ** the fcntl call every time sync is called.
  25044. */
  25045. if( rc ) rc = fsync(fd);
  25046. #elif defined(__APPLE__)
  25047. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  25048. ** so currently we default to the macro that redefines fdatasync to fsync
  25049. */
  25050. rc = fsync(fd);
  25051. #else
  25052. rc = fdatasync(fd);
  25053. #if OS_VXWORKS
  25054. if( rc==-1 && errno==ENOTSUP ){
  25055. rc = fsync(fd);
  25056. }
  25057. #endif /* OS_VXWORKS */
  25058. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  25059. if( OS_VXWORKS && rc!= -1 ){
  25060. rc = 0;
  25061. }
  25062. return rc;
  25063. }
  25064. /*
  25065. ** Open a file descriptor to the directory containing file zFilename.
  25066. ** If successful, *pFd is set to the opened file descriptor and
  25067. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  25068. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  25069. ** value.
  25070. **
  25071. ** The directory file descriptor is used for only one thing - to
  25072. ** fsync() a directory to make sure file creation and deletion events
  25073. ** are flushed to disk. Such fsyncs are not needed on newer
  25074. ** journaling filesystems, but are required on older filesystems.
  25075. **
  25076. ** This routine can be overridden using the xSetSysCall interface.
  25077. ** The ability to override this routine was added in support of the
  25078. ** chromium sandbox. Opening a directory is a security risk (we are
  25079. ** told) so making it overrideable allows the chromium sandbox to
  25080. ** replace this routine with a harmless no-op. To make this routine
  25081. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  25082. ** *pFd set to a negative number.
  25083. **
  25084. ** If SQLITE_OK is returned, the caller is responsible for closing
  25085. ** the file descriptor *pFd using close().
  25086. */
  25087. static int openDirectory(const char *zFilename, int *pFd){
  25088. int ii;
  25089. int fd = -1;
  25090. char zDirname[MAX_PATHNAME+1];
  25091. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  25092. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  25093. if( ii>0 ){
  25094. zDirname[ii] = '\0';
  25095. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  25096. if( fd>=0 ){
  25097. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  25098. }
  25099. }
  25100. *pFd = fd;
  25101. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  25102. }
  25103. /*
  25104. ** Make sure all writes to a particular file are committed to disk.
  25105. **
  25106. ** If dataOnly==0 then both the file itself and its metadata (file
  25107. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  25108. ** file data is synced.
  25109. **
  25110. ** Under Unix, also make sure that the directory entry for the file
  25111. ** has been created by fsync-ing the directory that contains the file.
  25112. ** If we do not do this and we encounter a power failure, the directory
  25113. ** entry for the journal might not exist after we reboot. The next
  25114. ** SQLite to access the file will not know that the journal exists (because
  25115. ** the directory entry for the journal was never created) and the transaction
  25116. ** will not roll back - possibly leading to database corruption.
  25117. */
  25118. static int unixSync(sqlite3_file *id, int flags){
  25119. int rc;
  25120. unixFile *pFile = (unixFile*)id;
  25121. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  25122. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  25123. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  25124. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  25125. || (flags&0x0F)==SQLITE_SYNC_FULL
  25126. );
  25127. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  25128. ** line is to test that doing so does not cause any problems.
  25129. */
  25130. SimulateDiskfullError( return SQLITE_FULL );
  25131. assert( pFile );
  25132. OSTRACE(("SYNC %-3d\n", pFile->h));
  25133. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  25134. SimulateIOError( rc=1 );
  25135. if( rc ){
  25136. pFile->lastErrno = errno;
  25137. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  25138. }
  25139. /* Also fsync the directory containing the file if the DIRSYNC flag
  25140. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  25141. ** are unable to fsync a directory, so ignore errors on the fsync.
  25142. */
  25143. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  25144. int dirfd;
  25145. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  25146. HAVE_FULLFSYNC, isFullsync));
  25147. rc = osOpenDirectory(pFile->zPath, &dirfd);
  25148. if( rc==SQLITE_OK && dirfd>=0 ){
  25149. full_fsync(dirfd, 0, 0);
  25150. robust_close(pFile, dirfd, __LINE__);
  25151. }else if( rc==SQLITE_CANTOPEN ){
  25152. rc = SQLITE_OK;
  25153. }
  25154. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  25155. }
  25156. return rc;
  25157. }
  25158. /*
  25159. ** Truncate an open file to a specified size
  25160. */
  25161. static int unixTruncate(sqlite3_file *id, i64 nByte){
  25162. unixFile *pFile = (unixFile *)id;
  25163. int rc;
  25164. assert( pFile );
  25165. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  25166. /* If the user has configured a chunk-size for this file, truncate the
  25167. ** file so that it consists of an integer number of chunks (i.e. the
  25168. ** actual file size after the operation may be larger than the requested
  25169. ** size).
  25170. */
  25171. if( pFile->szChunk>0 ){
  25172. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  25173. }
  25174. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  25175. if( rc ){
  25176. pFile->lastErrno = errno;
  25177. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25178. }else{
  25179. #ifdef SQLITE_DEBUG
  25180. /* If we are doing a normal write to a database file (as opposed to
  25181. ** doing a hot-journal rollback or a write to some file other than a
  25182. ** normal database file) and we truncate the file to zero length,
  25183. ** that effectively updates the change counter. This might happen
  25184. ** when restoring a database using the backup API from a zero-length
  25185. ** source.
  25186. */
  25187. if( pFile->inNormalWrite && nByte==0 ){
  25188. pFile->transCntrChng = 1;
  25189. }
  25190. #endif
  25191. /* If the file was just truncated to a size smaller than the currently
  25192. ** mapped region, reduce the effective mapping size as well. SQLite will
  25193. ** use read() and write() to access data beyond this point from now on.
  25194. */
  25195. if( nByte<pFile->mmapSize ){
  25196. pFile->mmapSize = nByte;
  25197. }
  25198. return SQLITE_OK;
  25199. }
  25200. }
  25201. /*
  25202. ** Determine the current size of a file in bytes
  25203. */
  25204. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  25205. int rc;
  25206. struct stat buf;
  25207. assert( id );
  25208. rc = osFstat(((unixFile*)id)->h, &buf);
  25209. SimulateIOError( rc=1 );
  25210. if( rc!=0 ){
  25211. ((unixFile*)id)->lastErrno = errno;
  25212. return SQLITE_IOERR_FSTAT;
  25213. }
  25214. *pSize = buf.st_size;
  25215. /* When opening a zero-size database, the findInodeInfo() procedure
  25216. ** writes a single byte into that file in order to work around a bug
  25217. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  25218. ** layers, we need to report this file size as zero even though it is
  25219. ** really 1. Ticket #3260.
  25220. */
  25221. if( *pSize==1 ) *pSize = 0;
  25222. return SQLITE_OK;
  25223. }
  25224. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25225. /*
  25226. ** Handler for proxy-locking file-control verbs. Defined below in the
  25227. ** proxying locking division.
  25228. */
  25229. static int proxyFileControl(sqlite3_file*,int,void*);
  25230. #endif
  25231. /*
  25232. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  25233. ** file-control operation. Enlarge the database to nBytes in size
  25234. ** (rounded up to the next chunk-size). If the database is already
  25235. ** nBytes or larger, this routine is a no-op.
  25236. */
  25237. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  25238. if( pFile->szChunk>0 ){
  25239. i64 nSize; /* Required file size */
  25240. struct stat buf; /* Used to hold return values of fstat() */
  25241. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  25242. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  25243. if( nSize>(i64)buf.st_size ){
  25244. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25245. /* The code below is handling the return value of osFallocate()
  25246. ** correctly. posix_fallocate() is defined to "returns zero on success,
  25247. ** or an error number on failure". See the manpage for details. */
  25248. int err;
  25249. do{
  25250. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  25251. }while( err==EINTR );
  25252. if( err ) return SQLITE_IOERR_WRITE;
  25253. #else
  25254. /* If the OS does not have posix_fallocate(), fake it. First use
  25255. ** ftruncate() to set the file size, then write a single byte to
  25256. ** the last byte in each block within the extended region. This
  25257. ** is the same technique used by glibc to implement posix_fallocate()
  25258. ** on systems that do not have a real fallocate() system call.
  25259. */
  25260. int nBlk = buf.st_blksize; /* File-system block size */
  25261. i64 iWrite; /* Next offset to write to */
  25262. if( robust_ftruncate(pFile->h, nSize) ){
  25263. pFile->lastErrno = errno;
  25264. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25265. }
  25266. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  25267. while( iWrite<nSize ){
  25268. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  25269. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  25270. iWrite += nBlk;
  25271. }
  25272. #endif
  25273. }
  25274. }
  25275. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  25276. int rc;
  25277. if( pFile->szChunk<=0 ){
  25278. if( robust_ftruncate(pFile->h, nByte) ){
  25279. pFile->lastErrno = errno;
  25280. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25281. }
  25282. }
  25283. rc = unixMapfile(pFile, nByte);
  25284. return rc;
  25285. }
  25286. return SQLITE_OK;
  25287. }
  25288. /*
  25289. ** If *pArg is inititially negative then this is a query. Set *pArg to
  25290. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  25291. **
  25292. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  25293. */
  25294. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  25295. if( *pArg<0 ){
  25296. *pArg = (pFile->ctrlFlags & mask)!=0;
  25297. }else if( (*pArg)==0 ){
  25298. pFile->ctrlFlags &= ~mask;
  25299. }else{
  25300. pFile->ctrlFlags |= mask;
  25301. }
  25302. }
  25303. /* Forward declaration */
  25304. static int unixGetTempname(int nBuf, char *zBuf);
  25305. /*
  25306. ** Information and control of an open file handle.
  25307. */
  25308. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  25309. unixFile *pFile = (unixFile*)id;
  25310. switch( op ){
  25311. case SQLITE_FCNTL_LOCKSTATE: {
  25312. *(int*)pArg = pFile->eFileLock;
  25313. return SQLITE_OK;
  25314. }
  25315. case SQLITE_LAST_ERRNO: {
  25316. *(int*)pArg = pFile->lastErrno;
  25317. return SQLITE_OK;
  25318. }
  25319. case SQLITE_FCNTL_CHUNK_SIZE: {
  25320. pFile->szChunk = *(int *)pArg;
  25321. return SQLITE_OK;
  25322. }
  25323. case SQLITE_FCNTL_SIZE_HINT: {
  25324. int rc;
  25325. SimulateIOErrorBenign(1);
  25326. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  25327. SimulateIOErrorBenign(0);
  25328. return rc;
  25329. }
  25330. case SQLITE_FCNTL_PERSIST_WAL: {
  25331. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  25332. return SQLITE_OK;
  25333. }
  25334. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  25335. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  25336. return SQLITE_OK;
  25337. }
  25338. case SQLITE_FCNTL_VFSNAME: {
  25339. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  25340. return SQLITE_OK;
  25341. }
  25342. case SQLITE_FCNTL_TEMPFILENAME: {
  25343. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  25344. if( zTFile ){
  25345. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  25346. *(char**)pArg = zTFile;
  25347. }
  25348. return SQLITE_OK;
  25349. }
  25350. case SQLITE_FCNTL_MMAP_SIZE: {
  25351. i64 newLimit = *(i64*)pArg;
  25352. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  25353. newLimit = sqlite3GlobalConfig.mxMmap;
  25354. }
  25355. *(i64*)pArg = pFile->mmapSizeMax;
  25356. if( newLimit>=0 ){
  25357. pFile->mmapSizeMax = newLimit;
  25358. if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
  25359. }
  25360. return SQLITE_OK;
  25361. }
  25362. #ifdef SQLITE_DEBUG
  25363. /* The pager calls this method to signal that it has done
  25364. ** a rollback and that the database is therefore unchanged and
  25365. ** it hence it is OK for the transaction change counter to be
  25366. ** unchanged.
  25367. */
  25368. case SQLITE_FCNTL_DB_UNCHANGED: {
  25369. ((unixFile*)id)->dbUpdate = 0;
  25370. return SQLITE_OK;
  25371. }
  25372. #endif
  25373. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25374. case SQLITE_SET_LOCKPROXYFILE:
  25375. case SQLITE_GET_LOCKPROXYFILE: {
  25376. return proxyFileControl(id,op,pArg);
  25377. }
  25378. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25379. }
  25380. return SQLITE_NOTFOUND;
  25381. }
  25382. /*
  25383. ** Return the sector size in bytes of the underlying block device for
  25384. ** the specified file. This is almost always 512 bytes, but may be
  25385. ** larger for some devices.
  25386. **
  25387. ** SQLite code assumes this function cannot fail. It also assumes that
  25388. ** if two files are created in the same file-system directory (i.e.
  25389. ** a database and its journal file) that the sector size will be the
  25390. ** same for both.
  25391. */
  25392. #ifndef __QNXNTO__
  25393. static int unixSectorSize(sqlite3_file *NotUsed){
  25394. UNUSED_PARAMETER(NotUsed);
  25395. return SQLITE_DEFAULT_SECTOR_SIZE;
  25396. }
  25397. #endif
  25398. /*
  25399. ** The following version of unixSectorSize() is optimized for QNX.
  25400. */
  25401. #ifdef __QNXNTO__
  25402. #include <sys/dcmd_blk.h>
  25403. #include <sys/statvfs.h>
  25404. static int unixSectorSize(sqlite3_file *id){
  25405. unixFile *pFile = (unixFile*)id;
  25406. if( pFile->sectorSize == 0 ){
  25407. struct statvfs fsInfo;
  25408. /* Set defaults for non-supported filesystems */
  25409. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25410. pFile->deviceCharacteristics = 0;
  25411. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  25412. return pFile->sectorSize;
  25413. }
  25414. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  25415. pFile->sectorSize = fsInfo.f_bsize;
  25416. pFile->deviceCharacteristics =
  25417. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  25418. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25419. ** the write succeeds */
  25420. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25421. ** so it is ordered */
  25422. 0;
  25423. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  25424. pFile->sectorSize = fsInfo.f_bsize;
  25425. pFile->deviceCharacteristics =
  25426. /* etfs cluster size writes are atomic */
  25427. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  25428. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25429. ** the write succeeds */
  25430. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25431. ** so it is ordered */
  25432. 0;
  25433. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  25434. pFile->sectorSize = fsInfo.f_bsize;
  25435. pFile->deviceCharacteristics =
  25436. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  25437. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25438. ** the write succeeds */
  25439. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25440. ** so it is ordered */
  25441. 0;
  25442. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  25443. pFile->sectorSize = fsInfo.f_bsize;
  25444. pFile->deviceCharacteristics =
  25445. /* full bitset of atomics from max sector size and smaller */
  25446. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25447. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25448. ** so it is ordered */
  25449. 0;
  25450. }else if( strstr(fsInfo.f_basetype, "dos") ){
  25451. pFile->sectorSize = fsInfo.f_bsize;
  25452. pFile->deviceCharacteristics =
  25453. /* full bitset of atomics from max sector size and smaller */
  25454. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25455. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25456. ** so it is ordered */
  25457. 0;
  25458. }else{
  25459. pFile->deviceCharacteristics =
  25460. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  25461. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25462. ** the write succeeds */
  25463. 0;
  25464. }
  25465. }
  25466. /* Last chance verification. If the sector size isn't a multiple of 512
  25467. ** then it isn't valid.*/
  25468. if( pFile->sectorSize % 512 != 0 ){
  25469. pFile->deviceCharacteristics = 0;
  25470. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25471. }
  25472. return pFile->sectorSize;
  25473. }
  25474. #endif /* __QNXNTO__ */
  25475. /*
  25476. ** Return the device characteristics for the file.
  25477. **
  25478. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  25479. ** However, that choice is contraversial since technically the underlying
  25480. ** file system does not always provide powersafe overwrites. (In other
  25481. ** words, after a power-loss event, parts of the file that were never
  25482. ** written might end up being altered.) However, non-PSOW behavior is very,
  25483. ** very rare. And asserting PSOW makes a large reduction in the amount
  25484. ** of required I/O for journaling, since a lot of padding is eliminated.
  25485. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  25486. ** available to turn it off and URI query parameter available to turn it off.
  25487. */
  25488. static int unixDeviceCharacteristics(sqlite3_file *id){
  25489. unixFile *p = (unixFile*)id;
  25490. int rc = 0;
  25491. #ifdef __QNXNTO__
  25492. if( p->sectorSize==0 ) unixSectorSize(id);
  25493. rc = p->deviceCharacteristics;
  25494. #endif
  25495. if( p->ctrlFlags & UNIXFILE_PSOW ){
  25496. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  25497. }
  25498. return rc;
  25499. }
  25500. #ifndef SQLITE_OMIT_WAL
  25501. /*
  25502. ** Object used to represent an shared memory buffer.
  25503. **
  25504. ** When multiple threads all reference the same wal-index, each thread
  25505. ** has its own unixShm object, but they all point to a single instance
  25506. ** of this unixShmNode object. In other words, each wal-index is opened
  25507. ** only once per process.
  25508. **
  25509. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25510. ** We could coalesce this object into unixInodeInfo, but that would mean
  25511. ** every open file that does not use shared memory (in other words, most
  25512. ** open files) would have to carry around this extra information. So
  25513. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25514. ** and the unixShmNode object is created only when needed.
  25515. **
  25516. ** unixMutexHeld() must be true when creating or destroying
  25517. ** this object or while reading or writing the following fields:
  25518. **
  25519. ** nRef
  25520. **
  25521. ** The following fields are read-only after the object is created:
  25522. **
  25523. ** fid
  25524. ** zFilename
  25525. **
  25526. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25527. ** unixMutexHeld() is true when reading or writing any other field
  25528. ** in this structure.
  25529. */
  25530. struct unixShmNode {
  25531. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25532. sqlite3_mutex *mutex; /* Mutex to access this object */
  25533. char *zFilename; /* Name of the mmapped file */
  25534. int h; /* Open file descriptor */
  25535. int szRegion; /* Size of shared-memory regions */
  25536. u16 nRegion; /* Size of array apRegion */
  25537. u8 isReadonly; /* True if read-only */
  25538. char **apRegion; /* Array of mapped shared-memory regions */
  25539. int nRef; /* Number of unixShm objects pointing to this */
  25540. unixShm *pFirst; /* All unixShm objects pointing to this */
  25541. #ifdef SQLITE_DEBUG
  25542. u8 exclMask; /* Mask of exclusive locks held */
  25543. u8 sharedMask; /* Mask of shared locks held */
  25544. u8 nextShmId; /* Next available unixShm.id value */
  25545. #endif
  25546. };
  25547. /*
  25548. ** Structure used internally by this VFS to record the state of an
  25549. ** open shared memory connection.
  25550. **
  25551. ** The following fields are initialized when this object is created and
  25552. ** are read-only thereafter:
  25553. **
  25554. ** unixShm.pFile
  25555. ** unixShm.id
  25556. **
  25557. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  25558. ** while accessing any read/write fields.
  25559. */
  25560. struct unixShm {
  25561. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  25562. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  25563. u8 hasMutex; /* True if holding the unixShmNode mutex */
  25564. u8 id; /* Id of this connection within its unixShmNode */
  25565. u16 sharedMask; /* Mask of shared locks held */
  25566. u16 exclMask; /* Mask of exclusive locks held */
  25567. };
  25568. /*
  25569. ** Constants used for locking
  25570. */
  25571. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  25572. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  25573. /*
  25574. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  25575. **
  25576. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  25577. ** otherwise.
  25578. */
  25579. static int unixShmSystemLock(
  25580. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  25581. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  25582. int ofst, /* First byte of the locking range */
  25583. int n /* Number of bytes to lock */
  25584. ){
  25585. struct flock f; /* The posix advisory locking structure */
  25586. int rc = SQLITE_OK; /* Result code form fcntl() */
  25587. /* Access to the unixShmNode object is serialized by the caller */
  25588. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  25589. /* Shared locks never span more than one byte */
  25590. assert( n==1 || lockType!=F_RDLCK );
  25591. /* Locks are within range */
  25592. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  25593. if( pShmNode->h>=0 ){
  25594. /* Initialize the locking parameters */
  25595. memset(&f, 0, sizeof(f));
  25596. f.l_type = lockType;
  25597. f.l_whence = SEEK_SET;
  25598. f.l_start = ofst;
  25599. f.l_len = n;
  25600. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  25601. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  25602. }
  25603. /* Update the global lock state and do debug tracing */
  25604. #ifdef SQLITE_DEBUG
  25605. { u16 mask;
  25606. OSTRACE(("SHM-LOCK "));
  25607. mask = (1<<(ofst+n)) - (1<<ofst);
  25608. if( rc==SQLITE_OK ){
  25609. if( lockType==F_UNLCK ){
  25610. OSTRACE(("unlock %d ok", ofst));
  25611. pShmNode->exclMask &= ~mask;
  25612. pShmNode->sharedMask &= ~mask;
  25613. }else if( lockType==F_RDLCK ){
  25614. OSTRACE(("read-lock %d ok", ofst));
  25615. pShmNode->exclMask &= ~mask;
  25616. pShmNode->sharedMask |= mask;
  25617. }else{
  25618. assert( lockType==F_WRLCK );
  25619. OSTRACE(("write-lock %d ok", ofst));
  25620. pShmNode->exclMask |= mask;
  25621. pShmNode->sharedMask &= ~mask;
  25622. }
  25623. }else{
  25624. if( lockType==F_UNLCK ){
  25625. OSTRACE(("unlock %d failed", ofst));
  25626. }else if( lockType==F_RDLCK ){
  25627. OSTRACE(("read-lock failed"));
  25628. }else{
  25629. assert( lockType==F_WRLCK );
  25630. OSTRACE(("write-lock %d failed", ofst));
  25631. }
  25632. }
  25633. OSTRACE((" - afterwards %03x,%03x\n",
  25634. pShmNode->sharedMask, pShmNode->exclMask));
  25635. }
  25636. #endif
  25637. return rc;
  25638. }
  25639. /*
  25640. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  25641. **
  25642. ** This is not a VFS shared-memory method; it is a utility function called
  25643. ** by VFS shared-memory methods.
  25644. */
  25645. static void unixShmPurge(unixFile *pFd){
  25646. unixShmNode *p = pFd->pInode->pShmNode;
  25647. assert( unixMutexHeld() );
  25648. if( p && p->nRef==0 ){
  25649. int i;
  25650. assert( p->pInode==pFd->pInode );
  25651. sqlite3_mutex_free(p->mutex);
  25652. for(i=0; i<p->nRegion; i++){
  25653. if( p->h>=0 ){
  25654. osMunmap(p->apRegion[i], p->szRegion);
  25655. }else{
  25656. sqlite3_free(p->apRegion[i]);
  25657. }
  25658. }
  25659. sqlite3_free(p->apRegion);
  25660. if( p->h>=0 ){
  25661. robust_close(pFd, p->h, __LINE__);
  25662. p->h = -1;
  25663. }
  25664. p->pInode->pShmNode = 0;
  25665. sqlite3_free(p);
  25666. }
  25667. }
  25668. /*
  25669. ** Open a shared-memory area associated with open database file pDbFd.
  25670. ** This particular implementation uses mmapped files.
  25671. **
  25672. ** The file used to implement shared-memory is in the same directory
  25673. ** as the open database file and has the same name as the open database
  25674. ** file with the "-shm" suffix added. For example, if the database file
  25675. ** is "/home/user1/config.db" then the file that is created and mmapped
  25676. ** for shared memory will be called "/home/user1/config.db-shm".
  25677. **
  25678. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  25679. ** some other tmpfs mount. But if a file in a different directory
  25680. ** from the database file is used, then differing access permissions
  25681. ** or a chroot() might cause two different processes on the same
  25682. ** database to end up using different files for shared memory -
  25683. ** meaning that their memory would not really be shared - resulting
  25684. ** in database corruption. Nevertheless, this tmpfs file usage
  25685. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  25686. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  25687. ** option results in an incompatible build of SQLite; builds of SQLite
  25688. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  25689. ** same database file at the same time, database corruption will likely
  25690. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  25691. ** "unsupported" and may go away in a future SQLite release.
  25692. **
  25693. ** When opening a new shared-memory file, if no other instances of that
  25694. ** file are currently open, in this process or in other processes, then
  25695. ** the file must be truncated to zero length or have its header cleared.
  25696. **
  25697. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  25698. ** that means that an exclusive lock is held on the database file and
  25699. ** that no other processes are able to read or write the database. In
  25700. ** that case, we do not really need shared memory. No shared memory
  25701. ** file is created. The shared memory will be simulated with heap memory.
  25702. */
  25703. static int unixOpenSharedMemory(unixFile *pDbFd){
  25704. struct unixShm *p = 0; /* The connection to be opened */
  25705. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  25706. int rc; /* Result code */
  25707. unixInodeInfo *pInode; /* The inode of fd */
  25708. char *zShmFilename; /* Name of the file used for SHM */
  25709. int nShmFilename; /* Size of the SHM filename in bytes */
  25710. /* Allocate space for the new unixShm object. */
  25711. p = sqlite3_malloc( sizeof(*p) );
  25712. if( p==0 ) return SQLITE_NOMEM;
  25713. memset(p, 0, sizeof(*p));
  25714. assert( pDbFd->pShm==0 );
  25715. /* Check to see if a unixShmNode object already exists. Reuse an existing
  25716. ** one if present. Create a new one if necessary.
  25717. */
  25718. unixEnterMutex();
  25719. pInode = pDbFd->pInode;
  25720. pShmNode = pInode->pShmNode;
  25721. if( pShmNode==0 ){
  25722. struct stat sStat; /* fstat() info for database file */
  25723. /* Call fstat() to figure out the permissions on the database file. If
  25724. ** a new *-shm file is created, an attempt will be made to create it
  25725. ** with the same permissions.
  25726. */
  25727. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  25728. rc = SQLITE_IOERR_FSTAT;
  25729. goto shm_open_err;
  25730. }
  25731. #ifdef SQLITE_SHM_DIRECTORY
  25732. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  25733. #else
  25734. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  25735. #endif
  25736. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  25737. if( pShmNode==0 ){
  25738. rc = SQLITE_NOMEM;
  25739. goto shm_open_err;
  25740. }
  25741. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  25742. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  25743. #ifdef SQLITE_SHM_DIRECTORY
  25744. sqlite3_snprintf(nShmFilename, zShmFilename,
  25745. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  25746. (u32)sStat.st_ino, (u32)sStat.st_dev);
  25747. #else
  25748. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  25749. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  25750. #endif
  25751. pShmNode->h = -1;
  25752. pDbFd->pInode->pShmNode = pShmNode;
  25753. pShmNode->pInode = pDbFd->pInode;
  25754. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  25755. if( pShmNode->mutex==0 ){
  25756. rc = SQLITE_NOMEM;
  25757. goto shm_open_err;
  25758. }
  25759. if( pInode->bProcessLock==0 ){
  25760. int openFlags = O_RDWR | O_CREAT;
  25761. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  25762. openFlags = O_RDONLY;
  25763. pShmNode->isReadonly = 1;
  25764. }
  25765. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  25766. if( pShmNode->h<0 ){
  25767. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  25768. goto shm_open_err;
  25769. }
  25770. /* If this process is running as root, make sure that the SHM file
  25771. ** is owned by the same user that owns the original database. Otherwise,
  25772. ** the original owner will not be able to connect.
  25773. */
  25774. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  25775. /* Check to see if another process is holding the dead-man switch.
  25776. ** If not, truncate the file to zero length.
  25777. */
  25778. rc = SQLITE_OK;
  25779. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  25780. if( robust_ftruncate(pShmNode->h, 0) ){
  25781. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  25782. }
  25783. }
  25784. if( rc==SQLITE_OK ){
  25785. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  25786. }
  25787. if( rc ) goto shm_open_err;
  25788. }
  25789. }
  25790. /* Make the new connection a child of the unixShmNode */
  25791. p->pShmNode = pShmNode;
  25792. #ifdef SQLITE_DEBUG
  25793. p->id = pShmNode->nextShmId++;
  25794. #endif
  25795. pShmNode->nRef++;
  25796. pDbFd->pShm = p;
  25797. unixLeaveMutex();
  25798. /* The reference count on pShmNode has already been incremented under
  25799. ** the cover of the unixEnterMutex() mutex and the pointer from the
  25800. ** new (struct unixShm) object to the pShmNode has been set. All that is
  25801. ** left to do is to link the new object into the linked list starting
  25802. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  25803. ** mutex.
  25804. */
  25805. sqlite3_mutex_enter(pShmNode->mutex);
  25806. p->pNext = pShmNode->pFirst;
  25807. pShmNode->pFirst = p;
  25808. sqlite3_mutex_leave(pShmNode->mutex);
  25809. return SQLITE_OK;
  25810. /* Jump here on any error */
  25811. shm_open_err:
  25812. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  25813. sqlite3_free(p);
  25814. unixLeaveMutex();
  25815. return rc;
  25816. }
  25817. /*
  25818. ** This function is called to obtain a pointer to region iRegion of the
  25819. ** shared-memory associated with the database file fd. Shared-memory regions
  25820. ** are numbered starting from zero. Each shared-memory region is szRegion
  25821. ** bytes in size.
  25822. **
  25823. ** If an error occurs, an error code is returned and *pp is set to NULL.
  25824. **
  25825. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  25826. ** region has not been allocated (by any client, including one running in a
  25827. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  25828. ** bExtend is non-zero and the requested shared-memory region has not yet
  25829. ** been allocated, it is allocated by this function.
  25830. **
  25831. ** If the shared-memory region has already been allocated or is allocated by
  25832. ** this call as described above, then it is mapped into this processes
  25833. ** address space (if it is not already), *pp is set to point to the mapped
  25834. ** memory and SQLITE_OK returned.
  25835. */
  25836. static int unixShmMap(
  25837. sqlite3_file *fd, /* Handle open on database file */
  25838. int iRegion, /* Region to retrieve */
  25839. int szRegion, /* Size of regions */
  25840. int bExtend, /* True to extend file if necessary */
  25841. void volatile **pp /* OUT: Mapped memory */
  25842. ){
  25843. unixFile *pDbFd = (unixFile*)fd;
  25844. unixShm *p;
  25845. unixShmNode *pShmNode;
  25846. int rc = SQLITE_OK;
  25847. /* If the shared-memory file has not yet been opened, open it now. */
  25848. if( pDbFd->pShm==0 ){
  25849. rc = unixOpenSharedMemory(pDbFd);
  25850. if( rc!=SQLITE_OK ) return rc;
  25851. }
  25852. p = pDbFd->pShm;
  25853. pShmNode = p->pShmNode;
  25854. sqlite3_mutex_enter(pShmNode->mutex);
  25855. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  25856. assert( pShmNode->pInode==pDbFd->pInode );
  25857. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  25858. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  25859. if( pShmNode->nRegion<=iRegion ){
  25860. char **apNew; /* New apRegion[] array */
  25861. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  25862. struct stat sStat; /* Used by fstat() */
  25863. pShmNode->szRegion = szRegion;
  25864. if( pShmNode->h>=0 ){
  25865. /* The requested region is not mapped into this processes address space.
  25866. ** Check to see if it has been allocated (i.e. if the wal-index file is
  25867. ** large enough to contain the requested region).
  25868. */
  25869. if( osFstat(pShmNode->h, &sStat) ){
  25870. rc = SQLITE_IOERR_SHMSIZE;
  25871. goto shmpage_out;
  25872. }
  25873. if( sStat.st_size<nByte ){
  25874. /* The requested memory region does not exist. If bExtend is set to
  25875. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  25876. */
  25877. if( !bExtend ){
  25878. goto shmpage_out;
  25879. }
  25880. /* Alternatively, if bExtend is true, extend the file. Do this by
  25881. ** writing a single byte to the end of each (OS) page being
  25882. ** allocated or extended. Technically, we need only write to the
  25883. ** last page in order to extend the file. But writing to all new
  25884. ** pages forces the OS to allocate them immediately, which reduces
  25885. ** the chances of SIGBUS while accessing the mapped region later on.
  25886. */
  25887. else{
  25888. static const int pgsz = 4096;
  25889. int iPg;
  25890. /* Write to the last byte of each newly allocated or extended page */
  25891. assert( (nByte % pgsz)==0 );
  25892. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  25893. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  25894. const char *zFile = pShmNode->zFilename;
  25895. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  25896. goto shmpage_out;
  25897. }
  25898. }
  25899. }
  25900. }
  25901. }
  25902. /* Map the requested memory region into this processes address space. */
  25903. apNew = (char **)sqlite3_realloc(
  25904. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  25905. );
  25906. if( !apNew ){
  25907. rc = SQLITE_IOERR_NOMEM;
  25908. goto shmpage_out;
  25909. }
  25910. pShmNode->apRegion = apNew;
  25911. while(pShmNode->nRegion<=iRegion){
  25912. void *pMem;
  25913. if( pShmNode->h>=0 ){
  25914. pMem = osMmap(0, szRegion,
  25915. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  25916. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  25917. );
  25918. if( pMem==MAP_FAILED ){
  25919. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  25920. goto shmpage_out;
  25921. }
  25922. }else{
  25923. pMem = sqlite3_malloc(szRegion);
  25924. if( pMem==0 ){
  25925. rc = SQLITE_NOMEM;
  25926. goto shmpage_out;
  25927. }
  25928. memset(pMem, 0, szRegion);
  25929. }
  25930. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  25931. pShmNode->nRegion++;
  25932. }
  25933. }
  25934. shmpage_out:
  25935. if( pShmNode->nRegion>iRegion ){
  25936. *pp = pShmNode->apRegion[iRegion];
  25937. }else{
  25938. *pp = 0;
  25939. }
  25940. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  25941. sqlite3_mutex_leave(pShmNode->mutex);
  25942. return rc;
  25943. }
  25944. /*
  25945. ** Change the lock state for a shared-memory segment.
  25946. **
  25947. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  25948. ** different here than in posix. In xShmLock(), one can go from unlocked
  25949. ** to shared and back or from unlocked to exclusive and back. But one may
  25950. ** not go from shared to exclusive or from exclusive to shared.
  25951. */
  25952. static int unixShmLock(
  25953. sqlite3_file *fd, /* Database file holding the shared memory */
  25954. int ofst, /* First lock to acquire or release */
  25955. int n, /* Number of locks to acquire or release */
  25956. int flags /* What to do with the lock */
  25957. ){
  25958. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  25959. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  25960. unixShm *pX; /* For looping over all siblings */
  25961. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  25962. int rc = SQLITE_OK; /* Result code */
  25963. u16 mask; /* Mask of locks to take or release */
  25964. assert( pShmNode==pDbFd->pInode->pShmNode );
  25965. assert( pShmNode->pInode==pDbFd->pInode );
  25966. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  25967. assert( n>=1 );
  25968. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  25969. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  25970. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  25971. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  25972. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  25973. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  25974. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  25975. mask = (1<<(ofst+n)) - (1<<ofst);
  25976. assert( n>1 || mask==(1<<ofst) );
  25977. sqlite3_mutex_enter(pShmNode->mutex);
  25978. if( flags & SQLITE_SHM_UNLOCK ){
  25979. u16 allMask = 0; /* Mask of locks held by siblings */
  25980. /* See if any siblings hold this same lock */
  25981. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  25982. if( pX==p ) continue;
  25983. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  25984. allMask |= pX->sharedMask;
  25985. }
  25986. /* Unlock the system-level locks */
  25987. if( (mask & allMask)==0 ){
  25988. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  25989. }else{
  25990. rc = SQLITE_OK;
  25991. }
  25992. /* Undo the local locks */
  25993. if( rc==SQLITE_OK ){
  25994. p->exclMask &= ~mask;
  25995. p->sharedMask &= ~mask;
  25996. }
  25997. }else if( flags & SQLITE_SHM_SHARED ){
  25998. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  25999. /* Find out which shared locks are already held by sibling connections.
  26000. ** If any sibling already holds an exclusive lock, go ahead and return
  26001. ** SQLITE_BUSY.
  26002. */
  26003. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26004. if( (pX->exclMask & mask)!=0 ){
  26005. rc = SQLITE_BUSY;
  26006. break;
  26007. }
  26008. allShared |= pX->sharedMask;
  26009. }
  26010. /* Get shared locks at the system level, if necessary */
  26011. if( rc==SQLITE_OK ){
  26012. if( (allShared & mask)==0 ){
  26013. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  26014. }else{
  26015. rc = SQLITE_OK;
  26016. }
  26017. }
  26018. /* Get the local shared locks */
  26019. if( rc==SQLITE_OK ){
  26020. p->sharedMask |= mask;
  26021. }
  26022. }else{
  26023. /* Make sure no sibling connections hold locks that will block this
  26024. ** lock. If any do, return SQLITE_BUSY right away.
  26025. */
  26026. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26027. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  26028. rc = SQLITE_BUSY;
  26029. break;
  26030. }
  26031. }
  26032. /* Get the exclusive locks at the system level. Then if successful
  26033. ** also mark the local connection as being locked.
  26034. */
  26035. if( rc==SQLITE_OK ){
  26036. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  26037. if( rc==SQLITE_OK ){
  26038. assert( (p->sharedMask & mask)==0 );
  26039. p->exclMask |= mask;
  26040. }
  26041. }
  26042. }
  26043. sqlite3_mutex_leave(pShmNode->mutex);
  26044. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  26045. p->id, getpid(), p->sharedMask, p->exclMask));
  26046. return rc;
  26047. }
  26048. /*
  26049. ** Implement a memory barrier or memory fence on shared memory.
  26050. **
  26051. ** All loads and stores begun before the barrier must complete before
  26052. ** any load or store begun after the barrier.
  26053. */
  26054. static void unixShmBarrier(
  26055. sqlite3_file *fd /* Database file holding the shared memory */
  26056. ){
  26057. UNUSED_PARAMETER(fd);
  26058. unixEnterMutex();
  26059. unixLeaveMutex();
  26060. }
  26061. /*
  26062. ** Close a connection to shared-memory. Delete the underlying
  26063. ** storage if deleteFlag is true.
  26064. **
  26065. ** If there is no shared memory associated with the connection then this
  26066. ** routine is a harmless no-op.
  26067. */
  26068. static int unixShmUnmap(
  26069. sqlite3_file *fd, /* The underlying database file */
  26070. int deleteFlag /* Delete shared-memory if true */
  26071. ){
  26072. unixShm *p; /* The connection to be closed */
  26073. unixShmNode *pShmNode; /* The underlying shared-memory file */
  26074. unixShm **pp; /* For looping over sibling connections */
  26075. unixFile *pDbFd; /* The underlying database file */
  26076. pDbFd = (unixFile*)fd;
  26077. p = pDbFd->pShm;
  26078. if( p==0 ) return SQLITE_OK;
  26079. pShmNode = p->pShmNode;
  26080. assert( pShmNode==pDbFd->pInode->pShmNode );
  26081. assert( pShmNode->pInode==pDbFd->pInode );
  26082. /* Remove connection p from the set of connections associated
  26083. ** with pShmNode */
  26084. sqlite3_mutex_enter(pShmNode->mutex);
  26085. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  26086. *pp = p->pNext;
  26087. /* Free the connection p */
  26088. sqlite3_free(p);
  26089. pDbFd->pShm = 0;
  26090. sqlite3_mutex_leave(pShmNode->mutex);
  26091. /* If pShmNode->nRef has reached 0, then close the underlying
  26092. ** shared-memory file, too */
  26093. unixEnterMutex();
  26094. assert( pShmNode->nRef>0 );
  26095. pShmNode->nRef--;
  26096. if( pShmNode->nRef==0 ){
  26097. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  26098. unixShmPurge(pDbFd);
  26099. }
  26100. unixLeaveMutex();
  26101. return SQLITE_OK;
  26102. }
  26103. #else
  26104. # define unixShmMap 0
  26105. # define unixShmLock 0
  26106. # define unixShmBarrier 0
  26107. # define unixShmUnmap 0
  26108. #endif /* #ifndef SQLITE_OMIT_WAL */
  26109. /*
  26110. ** If it is currently memory mapped, unmap file pFd.
  26111. */
  26112. static void unixUnmapfile(unixFile *pFd){
  26113. assert( pFd->nFetchOut==0 );
  26114. #if SQLITE_MAX_MMAP_SIZE>0
  26115. if( pFd->pMapRegion ){
  26116. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  26117. pFd->pMapRegion = 0;
  26118. pFd->mmapSize = 0;
  26119. pFd->mmapSizeActual = 0;
  26120. }
  26121. #endif
  26122. }
  26123. #if SQLITE_MAX_MMAP_SIZE>0
  26124. /*
  26125. ** Return the system page size.
  26126. */
  26127. static int unixGetPagesize(void){
  26128. #if HAVE_MREMAP
  26129. return 512;
  26130. #elif defined(_BSD_SOURCE)
  26131. return getpagesize();
  26132. #else
  26133. return (int)sysconf(_SC_PAGESIZE);
  26134. #endif
  26135. }
  26136. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  26137. #if SQLITE_MAX_MMAP_SIZE>0
  26138. /*
  26139. ** Attempt to set the size of the memory mapping maintained by file
  26140. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  26141. **
  26142. ** If successful, this function sets the following variables:
  26143. **
  26144. ** unixFile.pMapRegion
  26145. ** unixFile.mmapSize
  26146. ** unixFile.mmapSizeActual
  26147. **
  26148. ** If unsuccessful, an error message is logged via sqlite3_log() and
  26149. ** the three variables above are zeroed. In this case SQLite should
  26150. ** continue accessing the database using the xRead() and xWrite()
  26151. ** methods.
  26152. */
  26153. static void unixRemapfile(
  26154. unixFile *pFd, /* File descriptor object */
  26155. i64 nNew /* Required mapping size */
  26156. ){
  26157. const char *zErr = "mmap";
  26158. int h = pFd->h; /* File descriptor open on db file */
  26159. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  26160. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  26161. u8 *pNew = 0; /* Location of new mapping */
  26162. int flags = PROT_READ; /* Flags to pass to mmap() */
  26163. assert( pFd->nFetchOut==0 );
  26164. assert( nNew>pFd->mmapSize );
  26165. assert( nNew<=pFd->mmapSizeMax );
  26166. assert( nNew>0 );
  26167. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  26168. assert( MAP_FAILED!=0 );
  26169. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  26170. if( pOrig ){
  26171. const int szSyspage = unixGetPagesize();
  26172. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  26173. u8 *pReq = &pOrig[nReuse];
  26174. /* Unmap any pages of the existing mapping that cannot be reused. */
  26175. if( nReuse!=nOrig ){
  26176. osMunmap(pReq, nOrig-nReuse);
  26177. }
  26178. #if HAVE_MREMAP
  26179. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  26180. zErr = "mremap";
  26181. #else
  26182. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  26183. if( pNew!=MAP_FAILED ){
  26184. if( pNew!=pReq ){
  26185. osMunmap(pNew, nNew - nReuse);
  26186. pNew = 0;
  26187. }else{
  26188. pNew = pOrig;
  26189. }
  26190. }
  26191. #endif
  26192. /* The attempt to extend the existing mapping failed. Free it. */
  26193. if( pNew==MAP_FAILED || pNew==0 ){
  26194. osMunmap(pOrig, nReuse);
  26195. }
  26196. }
  26197. /* If pNew is still NULL, try to create an entirely new mapping. */
  26198. if( pNew==0 ){
  26199. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  26200. }
  26201. if( pNew==MAP_FAILED ){
  26202. pNew = 0;
  26203. nNew = 0;
  26204. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  26205. /* If the mmap() above failed, assume that all subsequent mmap() calls
  26206. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  26207. ** in this case. */
  26208. pFd->mmapSizeMax = 0;
  26209. }
  26210. pFd->pMapRegion = (void *)pNew;
  26211. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  26212. }
  26213. #endif
  26214. /*
  26215. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  26216. ** is already mapped, the existing mapping is replaced by the new). Or, if
  26217. ** there already exists a mapping for this file, and there are still
  26218. ** outstanding xFetch() references to it, this function is a no-op.
  26219. **
  26220. ** If parameter nByte is non-negative, then it is the requested size of
  26221. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  26222. ** requested size is the size of the file on disk. The actual size of the
  26223. ** created mapping is either the requested size or the value configured
  26224. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  26225. **
  26226. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  26227. ** recreated as a result of outstanding references) or an SQLite error
  26228. ** code otherwise.
  26229. */
  26230. static int unixMapfile(unixFile *pFd, i64 nByte){
  26231. #if SQLITE_MAX_MMAP_SIZE>0
  26232. i64 nMap = nByte;
  26233. int rc;
  26234. assert( nMap>=0 || pFd->nFetchOut==0 );
  26235. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  26236. if( nMap<0 ){
  26237. struct stat statbuf; /* Low-level file information */
  26238. rc = osFstat(pFd->h, &statbuf);
  26239. if( rc!=SQLITE_OK ){
  26240. return SQLITE_IOERR_FSTAT;
  26241. }
  26242. nMap = statbuf.st_size;
  26243. }
  26244. if( nMap>pFd->mmapSizeMax ){
  26245. nMap = pFd->mmapSizeMax;
  26246. }
  26247. if( nMap!=pFd->mmapSize ){
  26248. if( nMap>0 ){
  26249. unixRemapfile(pFd, nMap);
  26250. }else{
  26251. unixUnmapfile(pFd);
  26252. }
  26253. }
  26254. #endif
  26255. return SQLITE_OK;
  26256. }
  26257. /*
  26258. ** If possible, return a pointer to a mapping of file fd starting at offset
  26259. ** iOff. The mapping must be valid for at least nAmt bytes.
  26260. **
  26261. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  26262. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  26263. ** Finally, if an error does occur, return an SQLite error code. The final
  26264. ** value of *pp is undefined in this case.
  26265. **
  26266. ** If this function does return a pointer, the caller must eventually
  26267. ** release the reference by calling unixUnfetch().
  26268. */
  26269. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  26270. #if SQLITE_MAX_MMAP_SIZE>0
  26271. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26272. #endif
  26273. *pp = 0;
  26274. #if SQLITE_MAX_MMAP_SIZE>0
  26275. if( pFd->mmapSizeMax>0 ){
  26276. if( pFd->pMapRegion==0 ){
  26277. int rc = unixMapfile(pFd, -1);
  26278. if( rc!=SQLITE_OK ) return rc;
  26279. }
  26280. if( pFd->mmapSize >= iOff+nAmt ){
  26281. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  26282. pFd->nFetchOut++;
  26283. }
  26284. }
  26285. #endif
  26286. return SQLITE_OK;
  26287. }
  26288. /*
  26289. ** If the third argument is non-NULL, then this function releases a
  26290. ** reference obtained by an earlier call to unixFetch(). The second
  26291. ** argument passed to this function must be the same as the corresponding
  26292. ** argument that was passed to the unixFetch() invocation.
  26293. **
  26294. ** Or, if the third argument is NULL, then this function is being called
  26295. ** to inform the VFS layer that, according to POSIX, any existing mapping
  26296. ** may now be invalid and should be unmapped.
  26297. */
  26298. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  26299. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26300. UNUSED_PARAMETER(iOff);
  26301. /* If p==0 (unmap the entire file) then there must be no outstanding
  26302. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  26303. ** then there must be at least one outstanding. */
  26304. assert( (p==0)==(pFd->nFetchOut==0) );
  26305. /* If p!=0, it must match the iOff value. */
  26306. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  26307. if( p ){
  26308. pFd->nFetchOut--;
  26309. }else{
  26310. unixUnmapfile(pFd);
  26311. }
  26312. assert( pFd->nFetchOut>=0 );
  26313. return SQLITE_OK;
  26314. }
  26315. /*
  26316. ** Here ends the implementation of all sqlite3_file methods.
  26317. **
  26318. ********************** End sqlite3_file Methods *******************************
  26319. ******************************************************************************/
  26320. /*
  26321. ** This division contains definitions of sqlite3_io_methods objects that
  26322. ** implement various file locking strategies. It also contains definitions
  26323. ** of "finder" functions. A finder-function is used to locate the appropriate
  26324. ** sqlite3_io_methods object for a particular database file. The pAppData
  26325. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  26326. ** the correct finder-function for that VFS.
  26327. **
  26328. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  26329. ** object. The only interesting finder-function is autolockIoFinder, which
  26330. ** looks at the filesystem type and tries to guess the best locking
  26331. ** strategy from that.
  26332. **
  26333. ** For finder-funtion F, two objects are created:
  26334. **
  26335. ** (1) The real finder-function named "FImpt()".
  26336. **
  26337. ** (2) A constant pointer to this function named just "F".
  26338. **
  26339. **
  26340. ** A pointer to the F pointer is used as the pAppData value for VFS
  26341. ** objects. We have to do this instead of letting pAppData point
  26342. ** directly at the finder-function since C90 rules prevent a void*
  26343. ** from be cast into a function pointer.
  26344. **
  26345. **
  26346. ** Each instance of this macro generates two objects:
  26347. **
  26348. ** * A constant sqlite3_io_methods object call METHOD that has locking
  26349. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  26350. **
  26351. ** * An I/O method finder function called FINDER that returns a pointer
  26352. ** to the METHOD object in the previous bullet.
  26353. */
  26354. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  26355. static const sqlite3_io_methods METHOD = { \
  26356. VERSION, /* iVersion */ \
  26357. CLOSE, /* xClose */ \
  26358. unixRead, /* xRead */ \
  26359. unixWrite, /* xWrite */ \
  26360. unixTruncate, /* xTruncate */ \
  26361. unixSync, /* xSync */ \
  26362. unixFileSize, /* xFileSize */ \
  26363. LOCK, /* xLock */ \
  26364. UNLOCK, /* xUnlock */ \
  26365. CKLOCK, /* xCheckReservedLock */ \
  26366. unixFileControl, /* xFileControl */ \
  26367. unixSectorSize, /* xSectorSize */ \
  26368. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  26369. unixShmMap, /* xShmMap */ \
  26370. unixShmLock, /* xShmLock */ \
  26371. unixShmBarrier, /* xShmBarrier */ \
  26372. unixShmUnmap, /* xShmUnmap */ \
  26373. unixFetch, /* xFetch */ \
  26374. unixUnfetch, /* xUnfetch */ \
  26375. }; \
  26376. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  26377. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  26378. return &METHOD; \
  26379. } \
  26380. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  26381. = FINDER##Impl;
  26382. /*
  26383. ** Here are all of the sqlite3_io_methods objects for each of the
  26384. ** locking strategies. Functions that return pointers to these methods
  26385. ** are also created.
  26386. */
  26387. IOMETHODS(
  26388. posixIoFinder, /* Finder function name */
  26389. posixIoMethods, /* sqlite3_io_methods object name */
  26390. 3, /* shared memory and mmap are enabled */
  26391. unixClose, /* xClose method */
  26392. unixLock, /* xLock method */
  26393. unixUnlock, /* xUnlock method */
  26394. unixCheckReservedLock /* xCheckReservedLock method */
  26395. )
  26396. IOMETHODS(
  26397. nolockIoFinder, /* Finder function name */
  26398. nolockIoMethods, /* sqlite3_io_methods object name */
  26399. 1, /* shared memory is disabled */
  26400. nolockClose, /* xClose method */
  26401. nolockLock, /* xLock method */
  26402. nolockUnlock, /* xUnlock method */
  26403. nolockCheckReservedLock /* xCheckReservedLock method */
  26404. )
  26405. IOMETHODS(
  26406. dotlockIoFinder, /* Finder function name */
  26407. dotlockIoMethods, /* sqlite3_io_methods object name */
  26408. 1, /* shared memory is disabled */
  26409. dotlockClose, /* xClose method */
  26410. dotlockLock, /* xLock method */
  26411. dotlockUnlock, /* xUnlock method */
  26412. dotlockCheckReservedLock /* xCheckReservedLock method */
  26413. )
  26414. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  26415. IOMETHODS(
  26416. flockIoFinder, /* Finder function name */
  26417. flockIoMethods, /* sqlite3_io_methods object name */
  26418. 1, /* shared memory is disabled */
  26419. flockClose, /* xClose method */
  26420. flockLock, /* xLock method */
  26421. flockUnlock, /* xUnlock method */
  26422. flockCheckReservedLock /* xCheckReservedLock method */
  26423. )
  26424. #endif
  26425. #if OS_VXWORKS
  26426. IOMETHODS(
  26427. semIoFinder, /* Finder function name */
  26428. semIoMethods, /* sqlite3_io_methods object name */
  26429. 1, /* shared memory is disabled */
  26430. semClose, /* xClose method */
  26431. semLock, /* xLock method */
  26432. semUnlock, /* xUnlock method */
  26433. semCheckReservedLock /* xCheckReservedLock method */
  26434. )
  26435. #endif
  26436. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26437. IOMETHODS(
  26438. afpIoFinder, /* Finder function name */
  26439. afpIoMethods, /* sqlite3_io_methods object name */
  26440. 1, /* shared memory is disabled */
  26441. afpClose, /* xClose method */
  26442. afpLock, /* xLock method */
  26443. afpUnlock, /* xUnlock method */
  26444. afpCheckReservedLock /* xCheckReservedLock method */
  26445. )
  26446. #endif
  26447. /*
  26448. ** The proxy locking method is a "super-method" in the sense that it
  26449. ** opens secondary file descriptors for the conch and lock files and
  26450. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  26451. ** secondary files. For this reason, the division that implements
  26452. ** proxy locking is located much further down in the file. But we need
  26453. ** to go ahead and define the sqlite3_io_methods and finder function
  26454. ** for proxy locking here. So we forward declare the I/O methods.
  26455. */
  26456. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26457. static int proxyClose(sqlite3_file*);
  26458. static int proxyLock(sqlite3_file*, int);
  26459. static int proxyUnlock(sqlite3_file*, int);
  26460. static int proxyCheckReservedLock(sqlite3_file*, int*);
  26461. IOMETHODS(
  26462. proxyIoFinder, /* Finder function name */
  26463. proxyIoMethods, /* sqlite3_io_methods object name */
  26464. 1, /* shared memory is disabled */
  26465. proxyClose, /* xClose method */
  26466. proxyLock, /* xLock method */
  26467. proxyUnlock, /* xUnlock method */
  26468. proxyCheckReservedLock /* xCheckReservedLock method */
  26469. )
  26470. #endif
  26471. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  26472. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26473. IOMETHODS(
  26474. nfsIoFinder, /* Finder function name */
  26475. nfsIoMethods, /* sqlite3_io_methods object name */
  26476. 1, /* shared memory is disabled */
  26477. unixClose, /* xClose method */
  26478. unixLock, /* xLock method */
  26479. nfsUnlock, /* xUnlock method */
  26480. unixCheckReservedLock /* xCheckReservedLock method */
  26481. )
  26482. #endif
  26483. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26484. /*
  26485. ** This "finder" function attempts to determine the best locking strategy
  26486. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26487. ** object that implements that strategy.
  26488. **
  26489. ** This is for MacOSX only.
  26490. */
  26491. static const sqlite3_io_methods *autolockIoFinderImpl(
  26492. const char *filePath, /* name of the database file */
  26493. unixFile *pNew /* open file object for the database file */
  26494. ){
  26495. static const struct Mapping {
  26496. const char *zFilesystem; /* Filesystem type name */
  26497. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  26498. } aMap[] = {
  26499. { "hfs", &posixIoMethods },
  26500. { "ufs", &posixIoMethods },
  26501. { "afpfs", &afpIoMethods },
  26502. { "smbfs", &afpIoMethods },
  26503. { "webdav", &nolockIoMethods },
  26504. { 0, 0 }
  26505. };
  26506. int i;
  26507. struct statfs fsInfo;
  26508. struct flock lockInfo;
  26509. if( !filePath ){
  26510. /* If filePath==NULL that means we are dealing with a transient file
  26511. ** that does not need to be locked. */
  26512. return &nolockIoMethods;
  26513. }
  26514. if( statfs(filePath, &fsInfo) != -1 ){
  26515. if( fsInfo.f_flags & MNT_RDONLY ){
  26516. return &nolockIoMethods;
  26517. }
  26518. for(i=0; aMap[i].zFilesystem; i++){
  26519. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  26520. return aMap[i].pMethods;
  26521. }
  26522. }
  26523. }
  26524. /* Default case. Handles, amongst others, "nfs".
  26525. ** Test byte-range lock using fcntl(). If the call succeeds,
  26526. ** assume that the file-system supports POSIX style locks.
  26527. */
  26528. lockInfo.l_len = 1;
  26529. lockInfo.l_start = 0;
  26530. lockInfo.l_whence = SEEK_SET;
  26531. lockInfo.l_type = F_RDLCK;
  26532. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26533. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  26534. return &nfsIoMethods;
  26535. } else {
  26536. return &posixIoMethods;
  26537. }
  26538. }else{
  26539. return &dotlockIoMethods;
  26540. }
  26541. }
  26542. static const sqlite3_io_methods
  26543. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26544. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26545. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  26546. /*
  26547. ** This "finder" function attempts to determine the best locking strategy
  26548. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26549. ** object that implements that strategy.
  26550. **
  26551. ** This is for VXWorks only.
  26552. */
  26553. static const sqlite3_io_methods *autolockIoFinderImpl(
  26554. const char *filePath, /* name of the database file */
  26555. unixFile *pNew /* the open file object */
  26556. ){
  26557. struct flock lockInfo;
  26558. if( !filePath ){
  26559. /* If filePath==NULL that means we are dealing with a transient file
  26560. ** that does not need to be locked. */
  26561. return &nolockIoMethods;
  26562. }
  26563. /* Test if fcntl() is supported and use POSIX style locks.
  26564. ** Otherwise fall back to the named semaphore method.
  26565. */
  26566. lockInfo.l_len = 1;
  26567. lockInfo.l_start = 0;
  26568. lockInfo.l_whence = SEEK_SET;
  26569. lockInfo.l_type = F_RDLCK;
  26570. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26571. return &posixIoMethods;
  26572. }else{
  26573. return &semIoMethods;
  26574. }
  26575. }
  26576. static const sqlite3_io_methods
  26577. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26578. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  26579. /*
  26580. ** An abstract type for a pointer to a IO method finder function:
  26581. */
  26582. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  26583. /****************************************************************************
  26584. **************************** sqlite3_vfs methods ****************************
  26585. **
  26586. ** This division contains the implementation of methods on the
  26587. ** sqlite3_vfs object.
  26588. */
  26589. /*
  26590. ** Initialize the contents of the unixFile structure pointed to by pId.
  26591. */
  26592. static int fillInUnixFile(
  26593. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26594. int h, /* Open file descriptor of file being opened */
  26595. sqlite3_file *pId, /* Write to the unixFile structure here */
  26596. const char *zFilename, /* Name of the file being opened */
  26597. int ctrlFlags /* Zero or more UNIXFILE_* values */
  26598. ){
  26599. const sqlite3_io_methods *pLockingStyle;
  26600. unixFile *pNew = (unixFile *)pId;
  26601. int rc = SQLITE_OK;
  26602. assert( pNew->pInode==NULL );
  26603. /* Usually the path zFilename should not be a relative pathname. The
  26604. ** exception is when opening the proxy "conch" file in builds that
  26605. ** include the special Apple locking styles.
  26606. */
  26607. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26608. assert( zFilename==0 || zFilename[0]=='/'
  26609. || pVfs->pAppData==(void*)&autolockIoFinder );
  26610. #else
  26611. assert( zFilename==0 || zFilename[0]=='/' );
  26612. #endif
  26613. /* No locking occurs in temporary files */
  26614. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  26615. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  26616. pNew->h = h;
  26617. pNew->pVfs = pVfs;
  26618. pNew->zPath = zFilename;
  26619. pNew->ctrlFlags = (u8)ctrlFlags;
  26620. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  26621. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  26622. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  26623. pNew->ctrlFlags |= UNIXFILE_PSOW;
  26624. }
  26625. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  26626. pNew->ctrlFlags |= UNIXFILE_EXCL;
  26627. }
  26628. #if OS_VXWORKS
  26629. pNew->pId = vxworksFindFileId(zFilename);
  26630. if( pNew->pId==0 ){
  26631. ctrlFlags |= UNIXFILE_NOLOCK;
  26632. rc = SQLITE_NOMEM;
  26633. }
  26634. #endif
  26635. if( ctrlFlags & UNIXFILE_NOLOCK ){
  26636. pLockingStyle = &nolockIoMethods;
  26637. }else{
  26638. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  26639. #if SQLITE_ENABLE_LOCKING_STYLE
  26640. /* Cache zFilename in the locking context (AFP and dotlock override) for
  26641. ** proxyLock activation is possible (remote proxy is based on db name)
  26642. ** zFilename remains valid until file is closed, to support */
  26643. pNew->lockingContext = (void*)zFilename;
  26644. #endif
  26645. }
  26646. if( pLockingStyle == &posixIoMethods
  26647. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26648. || pLockingStyle == &nfsIoMethods
  26649. #endif
  26650. ){
  26651. unixEnterMutex();
  26652. rc = findInodeInfo(pNew, &pNew->pInode);
  26653. if( rc!=SQLITE_OK ){
  26654. /* If an error occurred in findInodeInfo(), close the file descriptor
  26655. ** immediately, before releasing the mutex. findInodeInfo() may fail
  26656. ** in two scenarios:
  26657. **
  26658. ** (a) A call to fstat() failed.
  26659. ** (b) A malloc failed.
  26660. **
  26661. ** Scenario (b) may only occur if the process is holding no other
  26662. ** file descriptors open on the same file. If there were other file
  26663. ** descriptors on this file, then no malloc would be required by
  26664. ** findInodeInfo(). If this is the case, it is quite safe to close
  26665. ** handle h - as it is guaranteed that no posix locks will be released
  26666. ** by doing so.
  26667. **
  26668. ** If scenario (a) caused the error then things are not so safe. The
  26669. ** implicit assumption here is that if fstat() fails, things are in
  26670. ** such bad shape that dropping a lock or two doesn't matter much.
  26671. */
  26672. robust_close(pNew, h, __LINE__);
  26673. h = -1;
  26674. }
  26675. unixLeaveMutex();
  26676. }
  26677. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26678. else if( pLockingStyle == &afpIoMethods ){
  26679. /* AFP locking uses the file path so it needs to be included in
  26680. ** the afpLockingContext.
  26681. */
  26682. afpLockingContext *pCtx;
  26683. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  26684. if( pCtx==0 ){
  26685. rc = SQLITE_NOMEM;
  26686. }else{
  26687. /* NB: zFilename exists and remains valid until the file is closed
  26688. ** according to requirement F11141. So we do not need to make a
  26689. ** copy of the filename. */
  26690. pCtx->dbPath = zFilename;
  26691. pCtx->reserved = 0;
  26692. srandomdev();
  26693. unixEnterMutex();
  26694. rc = findInodeInfo(pNew, &pNew->pInode);
  26695. if( rc!=SQLITE_OK ){
  26696. sqlite3_free(pNew->lockingContext);
  26697. robust_close(pNew, h, __LINE__);
  26698. h = -1;
  26699. }
  26700. unixLeaveMutex();
  26701. }
  26702. }
  26703. #endif
  26704. else if( pLockingStyle == &dotlockIoMethods ){
  26705. /* Dotfile locking uses the file path so it needs to be included in
  26706. ** the dotlockLockingContext
  26707. */
  26708. char *zLockFile;
  26709. int nFilename;
  26710. assert( zFilename!=0 );
  26711. nFilename = (int)strlen(zFilename) + 6;
  26712. zLockFile = (char *)sqlite3_malloc(nFilename);
  26713. if( zLockFile==0 ){
  26714. rc = SQLITE_NOMEM;
  26715. }else{
  26716. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  26717. }
  26718. pNew->lockingContext = zLockFile;
  26719. }
  26720. #if OS_VXWORKS
  26721. else if( pLockingStyle == &semIoMethods ){
  26722. /* Named semaphore locking uses the file path so it needs to be
  26723. ** included in the semLockingContext
  26724. */
  26725. unixEnterMutex();
  26726. rc = findInodeInfo(pNew, &pNew->pInode);
  26727. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  26728. char *zSemName = pNew->pInode->aSemName;
  26729. int n;
  26730. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  26731. pNew->pId->zCanonicalName);
  26732. for( n=1; zSemName[n]; n++ )
  26733. if( zSemName[n]=='/' ) zSemName[n] = '_';
  26734. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  26735. if( pNew->pInode->pSem == SEM_FAILED ){
  26736. rc = SQLITE_NOMEM;
  26737. pNew->pInode->aSemName[0] = '\0';
  26738. }
  26739. }
  26740. unixLeaveMutex();
  26741. }
  26742. #endif
  26743. pNew->lastErrno = 0;
  26744. #if OS_VXWORKS
  26745. if( rc!=SQLITE_OK ){
  26746. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26747. h = -1;
  26748. osUnlink(zFilename);
  26749. pNew->ctrlFlags |= UNIXFILE_DELETE;
  26750. }
  26751. #endif
  26752. if( rc!=SQLITE_OK ){
  26753. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26754. }else{
  26755. pNew->pMethod = pLockingStyle;
  26756. OpenCounter(+1);
  26757. verifyDbFile(pNew);
  26758. }
  26759. return rc;
  26760. }
  26761. /*
  26762. ** Return the name of a directory in which to put temporary files.
  26763. ** If no suitable temporary file directory can be found, return NULL.
  26764. */
  26765. static const char *unixTempFileDir(void){
  26766. static const char *azDirs[] = {
  26767. 0,
  26768. 0,
  26769. "/var/tmp",
  26770. "/usr/tmp",
  26771. "/tmp",
  26772. 0 /* List terminator */
  26773. };
  26774. unsigned int i;
  26775. struct stat buf;
  26776. const char *zDir = 0;
  26777. azDirs[0] = sqlite3_temp_directory;
  26778. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  26779. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  26780. if( zDir==0 ) continue;
  26781. if( osStat(zDir, &buf) ) continue;
  26782. if( !S_ISDIR(buf.st_mode) ) continue;
  26783. if( osAccess(zDir, 07) ) continue;
  26784. break;
  26785. }
  26786. return zDir;
  26787. }
  26788. /*
  26789. ** Create a temporary file name in zBuf. zBuf must be allocated
  26790. ** by the calling process and must be big enough to hold at least
  26791. ** pVfs->mxPathname bytes.
  26792. */
  26793. static int unixGetTempname(int nBuf, char *zBuf){
  26794. static const unsigned char zChars[] =
  26795. "abcdefghijklmnopqrstuvwxyz"
  26796. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  26797. "0123456789";
  26798. unsigned int i, j;
  26799. const char *zDir;
  26800. /* It's odd to simulate an io-error here, but really this is just
  26801. ** using the io-error infrastructure to test that SQLite handles this
  26802. ** function failing.
  26803. */
  26804. SimulateIOError( return SQLITE_IOERR );
  26805. zDir = unixTempFileDir();
  26806. if( zDir==0 ) zDir = ".";
  26807. /* Check that the output buffer is large enough for the temporary file
  26808. ** name. If it is not, return SQLITE_ERROR.
  26809. */
  26810. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  26811. return SQLITE_ERROR;
  26812. }
  26813. do{
  26814. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  26815. j = (int)strlen(zBuf);
  26816. sqlite3_randomness(15, &zBuf[j]);
  26817. for(i=0; i<15; i++, j++){
  26818. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  26819. }
  26820. zBuf[j] = 0;
  26821. zBuf[j+1] = 0;
  26822. }while( osAccess(zBuf,0)==0 );
  26823. return SQLITE_OK;
  26824. }
  26825. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26826. /*
  26827. ** Routine to transform a unixFile into a proxy-locking unixFile.
  26828. ** Implementation in the proxy-lock division, but used by unixOpen()
  26829. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  26830. */
  26831. static int proxyTransformUnixFile(unixFile*, const char*);
  26832. #endif
  26833. /*
  26834. ** Search for an unused file descriptor that was opened on the database
  26835. ** file (not a journal or master-journal file) identified by pathname
  26836. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  26837. ** argument to this function.
  26838. **
  26839. ** Such a file descriptor may exist if a database connection was closed
  26840. ** but the associated file descriptor could not be closed because some
  26841. ** other file descriptor open on the same file is holding a file-lock.
  26842. ** Refer to comments in the unixClose() function and the lengthy comment
  26843. ** describing "Posix Advisory Locking" at the start of this file for
  26844. ** further details. Also, ticket #4018.
  26845. **
  26846. ** If a suitable file descriptor is found, then it is returned. If no
  26847. ** such file descriptor is located, -1 is returned.
  26848. */
  26849. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  26850. UnixUnusedFd *pUnused = 0;
  26851. /* Do not search for an unused file descriptor on vxworks. Not because
  26852. ** vxworks would not benefit from the change (it might, we're not sure),
  26853. ** but because no way to test it is currently available. It is better
  26854. ** not to risk breaking vxworks support for the sake of such an obscure
  26855. ** feature. */
  26856. #if !OS_VXWORKS
  26857. struct stat sStat; /* Results of stat() call */
  26858. /* A stat() call may fail for various reasons. If this happens, it is
  26859. ** almost certain that an open() call on the same path will also fail.
  26860. ** For this reason, if an error occurs in the stat() call here, it is
  26861. ** ignored and -1 is returned. The caller will try to open a new file
  26862. ** descriptor on the same path, fail, and return an error to SQLite.
  26863. **
  26864. ** Even if a subsequent open() call does succeed, the consequences of
  26865. ** not searching for a resusable file descriptor are not dire. */
  26866. if( 0==osStat(zPath, &sStat) ){
  26867. unixInodeInfo *pInode;
  26868. unixEnterMutex();
  26869. pInode = inodeList;
  26870. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  26871. || pInode->fileId.ino!=sStat.st_ino) ){
  26872. pInode = pInode->pNext;
  26873. }
  26874. if( pInode ){
  26875. UnixUnusedFd **pp;
  26876. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  26877. pUnused = *pp;
  26878. if( pUnused ){
  26879. *pp = pUnused->pNext;
  26880. }
  26881. }
  26882. unixLeaveMutex();
  26883. }
  26884. #endif /* if !OS_VXWORKS */
  26885. return pUnused;
  26886. }
  26887. /*
  26888. ** This function is called by unixOpen() to determine the unix permissions
  26889. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  26890. ** and a value suitable for passing as the third argument to open(2) is
  26891. ** written to *pMode. If an IO error occurs, an SQLite error code is
  26892. ** returned and the value of *pMode is not modified.
  26893. **
  26894. ** In most cases cases, this routine sets *pMode to 0, which will become
  26895. ** an indication to robust_open() to create the file using
  26896. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  26897. ** But if the file being opened is a WAL or regular journal file, then
  26898. ** this function queries the file-system for the permissions on the
  26899. ** corresponding database file and sets *pMode to this value. Whenever
  26900. ** possible, WAL and journal files are created using the same permissions
  26901. ** as the associated database file.
  26902. **
  26903. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  26904. ** original filename is unavailable. But 8_3_NAMES is only used for
  26905. ** FAT filesystems and permissions do not matter there, so just use
  26906. ** the default permissions.
  26907. */
  26908. static int findCreateFileMode(
  26909. const char *zPath, /* Path of file (possibly) being created */
  26910. int flags, /* Flags passed as 4th argument to xOpen() */
  26911. mode_t *pMode, /* OUT: Permissions to open file with */
  26912. uid_t *pUid, /* OUT: uid to set on the file */
  26913. gid_t *pGid /* OUT: gid to set on the file */
  26914. ){
  26915. int rc = SQLITE_OK; /* Return Code */
  26916. *pMode = 0;
  26917. *pUid = 0;
  26918. *pGid = 0;
  26919. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  26920. char zDb[MAX_PATHNAME+1]; /* Database file path */
  26921. int nDb; /* Number of valid bytes in zDb */
  26922. struct stat sStat; /* Output of stat() on database file */
  26923. /* zPath is a path to a WAL or journal file. The following block derives
  26924. ** the path to the associated database file from zPath. This block handles
  26925. ** the following naming conventions:
  26926. **
  26927. ** "<path to db>-journal"
  26928. ** "<path to db>-wal"
  26929. ** "<path to db>-journalNN"
  26930. ** "<path to db>-walNN"
  26931. **
  26932. ** where NN is a decimal number. The NN naming schemes are
  26933. ** used by the test_multiplex.c module.
  26934. */
  26935. nDb = sqlite3Strlen30(zPath) - 1;
  26936. #ifdef SQLITE_ENABLE_8_3_NAMES
  26937. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  26938. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  26939. #else
  26940. while( zPath[nDb]!='-' ){
  26941. assert( nDb>0 );
  26942. assert( zPath[nDb]!='\n' );
  26943. nDb--;
  26944. }
  26945. #endif
  26946. memcpy(zDb, zPath, nDb);
  26947. zDb[nDb] = '\0';
  26948. if( 0==osStat(zDb, &sStat) ){
  26949. *pMode = sStat.st_mode & 0777;
  26950. *pUid = sStat.st_uid;
  26951. *pGid = sStat.st_gid;
  26952. }else{
  26953. rc = SQLITE_IOERR_FSTAT;
  26954. }
  26955. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  26956. *pMode = 0600;
  26957. }
  26958. return rc;
  26959. }
  26960. /*
  26961. ** Open the file zPath.
  26962. **
  26963. ** Previously, the SQLite OS layer used three functions in place of this
  26964. ** one:
  26965. **
  26966. ** sqlite3OsOpenReadWrite();
  26967. ** sqlite3OsOpenReadOnly();
  26968. ** sqlite3OsOpenExclusive();
  26969. **
  26970. ** These calls correspond to the following combinations of flags:
  26971. **
  26972. ** ReadWrite() -> (READWRITE | CREATE)
  26973. ** ReadOnly() -> (READONLY)
  26974. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  26975. **
  26976. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  26977. ** true, the file was configured to be automatically deleted when the
  26978. ** file handle closed. To achieve the same effect using this new
  26979. ** interface, add the DELETEONCLOSE flag to those specified above for
  26980. ** OpenExclusive().
  26981. */
  26982. static int unixOpen(
  26983. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  26984. const char *zPath, /* Pathname of file to be opened */
  26985. sqlite3_file *pFile, /* The file descriptor to be filled in */
  26986. int flags, /* Input flags to control the opening */
  26987. int *pOutFlags /* Output flags returned to SQLite core */
  26988. ){
  26989. unixFile *p = (unixFile *)pFile;
  26990. int fd = -1; /* File descriptor returned by open() */
  26991. int openFlags = 0; /* Flags to pass to open() */
  26992. int eType = flags&0xFFFFFF00; /* Type of file to open */
  26993. int noLock; /* True to omit locking primitives */
  26994. int rc = SQLITE_OK; /* Function Return Code */
  26995. int ctrlFlags = 0; /* UNIXFILE_* flags */
  26996. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  26997. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  26998. int isCreate = (flags & SQLITE_OPEN_CREATE);
  26999. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  27000. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  27001. #if SQLITE_ENABLE_LOCKING_STYLE
  27002. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  27003. #endif
  27004. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27005. struct statfs fsInfo;
  27006. #endif
  27007. /* If creating a master or main-file journal, this function will open
  27008. ** a file-descriptor on the directory too. The first time unixSync()
  27009. ** is called the directory file descriptor will be fsync()ed and close()d.
  27010. */
  27011. int syncDir = (isCreate && (
  27012. eType==SQLITE_OPEN_MASTER_JOURNAL
  27013. || eType==SQLITE_OPEN_MAIN_JOURNAL
  27014. || eType==SQLITE_OPEN_WAL
  27015. ));
  27016. /* If argument zPath is a NULL pointer, this function is required to open
  27017. ** a temporary file. Use this buffer to store the file name in.
  27018. */
  27019. char zTmpname[MAX_PATHNAME+2];
  27020. const char *zName = zPath;
  27021. /* Check the following statements are true:
  27022. **
  27023. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  27024. ** (b) if CREATE is set, then READWRITE must also be set, and
  27025. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  27026. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  27027. */
  27028. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  27029. assert(isCreate==0 || isReadWrite);
  27030. assert(isExclusive==0 || isCreate);
  27031. assert(isDelete==0 || isCreate);
  27032. /* The main DB, main journal, WAL file and master journal are never
  27033. ** automatically deleted. Nor are they ever temporary files. */
  27034. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  27035. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  27036. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  27037. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  27038. /* Assert that the upper layer has set one of the "file-type" flags. */
  27039. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  27040. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  27041. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  27042. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  27043. );
  27044. memset(p, 0, sizeof(unixFile));
  27045. if( eType==SQLITE_OPEN_MAIN_DB ){
  27046. UnixUnusedFd *pUnused;
  27047. pUnused = findReusableFd(zName, flags);
  27048. if( pUnused ){
  27049. fd = pUnused->fd;
  27050. }else{
  27051. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27052. if( !pUnused ){
  27053. return SQLITE_NOMEM;
  27054. }
  27055. }
  27056. p->pUnused = pUnused;
  27057. /* Database filenames are double-zero terminated if they are not
  27058. ** URIs with parameters. Hence, they can always be passed into
  27059. ** sqlite3_uri_parameter(). */
  27060. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  27061. }else if( !zName ){
  27062. /* If zName is NULL, the upper layer is requesting a temp file. */
  27063. assert(isDelete && !syncDir);
  27064. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  27065. if( rc!=SQLITE_OK ){
  27066. return rc;
  27067. }
  27068. zName = zTmpname;
  27069. /* Generated temporary filenames are always double-zero terminated
  27070. ** for use by sqlite3_uri_parameter(). */
  27071. assert( zName[strlen(zName)+1]==0 );
  27072. }
  27073. /* Determine the value of the flags parameter passed to POSIX function
  27074. ** open(). These must be calculated even if open() is not called, as
  27075. ** they may be stored as part of the file handle and used by the
  27076. ** 'conch file' locking functions later on. */
  27077. if( isReadonly ) openFlags |= O_RDONLY;
  27078. if( isReadWrite ) openFlags |= O_RDWR;
  27079. if( isCreate ) openFlags |= O_CREAT;
  27080. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  27081. openFlags |= (O_LARGEFILE|O_BINARY);
  27082. if( fd<0 ){
  27083. mode_t openMode; /* Permissions to create file with */
  27084. uid_t uid; /* Userid for the file */
  27085. gid_t gid; /* Groupid for the file */
  27086. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  27087. if( rc!=SQLITE_OK ){
  27088. assert( !p->pUnused );
  27089. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  27090. return rc;
  27091. }
  27092. fd = robust_open(zName, openFlags, openMode);
  27093. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  27094. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  27095. /* Failed to open the file for read/write access. Try read-only. */
  27096. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  27097. openFlags &= ~(O_RDWR|O_CREAT);
  27098. flags |= SQLITE_OPEN_READONLY;
  27099. openFlags |= O_RDONLY;
  27100. isReadonly = 1;
  27101. fd = robust_open(zName, openFlags, openMode);
  27102. }
  27103. if( fd<0 ){
  27104. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  27105. goto open_finished;
  27106. }
  27107. /* If this process is running as root and if creating a new rollback
  27108. ** journal or WAL file, set the ownership of the journal or WAL to be
  27109. ** the same as the original database.
  27110. */
  27111. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27112. osFchown(fd, uid, gid);
  27113. }
  27114. }
  27115. assert( fd>=0 );
  27116. if( pOutFlags ){
  27117. *pOutFlags = flags;
  27118. }
  27119. if( p->pUnused ){
  27120. p->pUnused->fd = fd;
  27121. p->pUnused->flags = flags;
  27122. }
  27123. if( isDelete ){
  27124. #if OS_VXWORKS
  27125. zPath = zName;
  27126. #else
  27127. osUnlink(zName);
  27128. #endif
  27129. }
  27130. #if SQLITE_ENABLE_LOCKING_STYLE
  27131. else{
  27132. p->openFlags = openFlags;
  27133. }
  27134. #endif
  27135. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  27136. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27137. if( fstatfs(fd, &fsInfo) == -1 ){
  27138. ((unixFile*)pFile)->lastErrno = errno;
  27139. robust_close(p, fd, __LINE__);
  27140. return SQLITE_IOERR_ACCESS;
  27141. }
  27142. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  27143. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  27144. }
  27145. #endif
  27146. /* Set up appropriate ctrlFlags */
  27147. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  27148. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  27149. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  27150. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  27151. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  27152. #if SQLITE_ENABLE_LOCKING_STYLE
  27153. #if SQLITE_PREFER_PROXY_LOCKING
  27154. isAutoProxy = 1;
  27155. #endif
  27156. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  27157. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  27158. int useProxy = 0;
  27159. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  27160. ** never use proxy, NULL means use proxy for non-local files only. */
  27161. if( envforce!=NULL ){
  27162. useProxy = atoi(envforce)>0;
  27163. }else{
  27164. if( statfs(zPath, &fsInfo) == -1 ){
  27165. /* In theory, the close(fd) call is sub-optimal. If the file opened
  27166. ** with fd is a database file, and there are other connections open
  27167. ** on that file that are currently holding advisory locks on it,
  27168. ** then the call to close() will cancel those locks. In practice,
  27169. ** we're assuming that statfs() doesn't fail very often. At least
  27170. ** not while other file descriptors opened by the same process on
  27171. ** the same file are working. */
  27172. p->lastErrno = errno;
  27173. robust_close(p, fd, __LINE__);
  27174. rc = SQLITE_IOERR_ACCESS;
  27175. goto open_finished;
  27176. }
  27177. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  27178. }
  27179. if( useProxy ){
  27180. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27181. if( rc==SQLITE_OK ){
  27182. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  27183. if( rc!=SQLITE_OK ){
  27184. /* Use unixClose to clean up the resources added in fillInUnixFile
  27185. ** and clear all the structure's references. Specifically,
  27186. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  27187. */
  27188. unixClose(pFile);
  27189. return rc;
  27190. }
  27191. }
  27192. goto open_finished;
  27193. }
  27194. }
  27195. #endif
  27196. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27197. open_finished:
  27198. if( rc!=SQLITE_OK ){
  27199. sqlite3_free(p->pUnused);
  27200. }
  27201. return rc;
  27202. }
  27203. /*
  27204. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  27205. ** the directory after deleting the file.
  27206. */
  27207. static int unixDelete(
  27208. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  27209. const char *zPath, /* Name of file to be deleted */
  27210. int dirSync /* If true, fsync() directory after deleting file */
  27211. ){
  27212. int rc = SQLITE_OK;
  27213. UNUSED_PARAMETER(NotUsed);
  27214. SimulateIOError(return SQLITE_IOERR_DELETE);
  27215. if( osUnlink(zPath)==(-1) ){
  27216. if( errno==ENOENT ){
  27217. rc = SQLITE_IOERR_DELETE_NOENT;
  27218. }else{
  27219. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  27220. }
  27221. return rc;
  27222. }
  27223. #ifndef SQLITE_DISABLE_DIRSYNC
  27224. if( (dirSync & 1)!=0 ){
  27225. int fd;
  27226. rc = osOpenDirectory(zPath, &fd);
  27227. if( rc==SQLITE_OK ){
  27228. #if OS_VXWORKS
  27229. if( fsync(fd)==-1 )
  27230. #else
  27231. if( fsync(fd) )
  27232. #endif
  27233. {
  27234. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  27235. }
  27236. robust_close(0, fd, __LINE__);
  27237. }else if( rc==SQLITE_CANTOPEN ){
  27238. rc = SQLITE_OK;
  27239. }
  27240. }
  27241. #endif
  27242. return rc;
  27243. }
  27244. /*
  27245. ** Test the existence of or access permissions of file zPath. The
  27246. ** test performed depends on the value of flags:
  27247. **
  27248. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  27249. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  27250. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  27251. **
  27252. ** Otherwise return 0.
  27253. */
  27254. static int unixAccess(
  27255. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  27256. const char *zPath, /* Path of the file to examine */
  27257. int flags, /* What do we want to learn about the zPath file? */
  27258. int *pResOut /* Write result boolean here */
  27259. ){
  27260. int amode = 0;
  27261. UNUSED_PARAMETER(NotUsed);
  27262. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  27263. switch( flags ){
  27264. case SQLITE_ACCESS_EXISTS:
  27265. amode = F_OK;
  27266. break;
  27267. case SQLITE_ACCESS_READWRITE:
  27268. amode = W_OK|R_OK;
  27269. break;
  27270. case SQLITE_ACCESS_READ:
  27271. amode = R_OK;
  27272. break;
  27273. default:
  27274. assert(!"Invalid flags argument");
  27275. }
  27276. *pResOut = (osAccess(zPath, amode)==0);
  27277. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  27278. struct stat buf;
  27279. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  27280. *pResOut = 0;
  27281. }
  27282. }
  27283. return SQLITE_OK;
  27284. }
  27285. /*
  27286. ** Turn a relative pathname into a full pathname. The relative path
  27287. ** is stored as a nul-terminated string in the buffer pointed to by
  27288. ** zPath.
  27289. **
  27290. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  27291. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  27292. ** this buffer before returning.
  27293. */
  27294. static int unixFullPathname(
  27295. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27296. const char *zPath, /* Possibly relative input path */
  27297. int nOut, /* Size of output buffer in bytes */
  27298. char *zOut /* Output buffer */
  27299. ){
  27300. /* It's odd to simulate an io-error here, but really this is just
  27301. ** using the io-error infrastructure to test that SQLite handles this
  27302. ** function failing. This function could fail if, for example, the
  27303. ** current working directory has been unlinked.
  27304. */
  27305. SimulateIOError( return SQLITE_ERROR );
  27306. assert( pVfs->mxPathname==MAX_PATHNAME );
  27307. UNUSED_PARAMETER(pVfs);
  27308. zOut[nOut-1] = '\0';
  27309. if( zPath[0]=='/' ){
  27310. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  27311. }else{
  27312. int nCwd;
  27313. if( osGetcwd(zOut, nOut-1)==0 ){
  27314. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  27315. }
  27316. nCwd = (int)strlen(zOut);
  27317. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  27318. }
  27319. return SQLITE_OK;
  27320. }
  27321. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  27322. /*
  27323. ** Interfaces for opening a shared library, finding entry points
  27324. ** within the shared library, and closing the shared library.
  27325. */
  27326. #include <dlfcn.h>
  27327. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  27328. UNUSED_PARAMETER(NotUsed);
  27329. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  27330. }
  27331. /*
  27332. ** SQLite calls this function immediately after a call to unixDlSym() or
  27333. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  27334. ** message is available, it is written to zBufOut. If no error message
  27335. ** is available, zBufOut is left unmodified and SQLite uses a default
  27336. ** error message.
  27337. */
  27338. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  27339. const char *zErr;
  27340. UNUSED_PARAMETER(NotUsed);
  27341. unixEnterMutex();
  27342. zErr = dlerror();
  27343. if( zErr ){
  27344. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  27345. }
  27346. unixLeaveMutex();
  27347. }
  27348. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  27349. /*
  27350. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  27351. ** cast into a pointer to a function. And yet the library dlsym() routine
  27352. ** returns a void* which is really a pointer to a function. So how do we
  27353. ** use dlsym() with -pedantic-errors?
  27354. **
  27355. ** Variable x below is defined to be a pointer to a function taking
  27356. ** parameters void* and const char* and returning a pointer to a function.
  27357. ** We initialize x by assigning it a pointer to the dlsym() function.
  27358. ** (That assignment requires a cast.) Then we call the function that
  27359. ** x points to.
  27360. **
  27361. ** This work-around is unlikely to work correctly on any system where
  27362. ** you really cannot cast a function pointer into void*. But then, on the
  27363. ** other hand, dlsym() will not work on such a system either, so we have
  27364. ** not really lost anything.
  27365. */
  27366. void (*(*x)(void*,const char*))(void);
  27367. UNUSED_PARAMETER(NotUsed);
  27368. x = (void(*(*)(void*,const char*))(void))dlsym;
  27369. return (*x)(p, zSym);
  27370. }
  27371. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  27372. UNUSED_PARAMETER(NotUsed);
  27373. dlclose(pHandle);
  27374. }
  27375. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  27376. #define unixDlOpen 0
  27377. #define unixDlError 0
  27378. #define unixDlSym 0
  27379. #define unixDlClose 0
  27380. #endif
  27381. /*
  27382. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  27383. */
  27384. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  27385. UNUSED_PARAMETER(NotUsed);
  27386. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  27387. /* We have to initialize zBuf to prevent valgrind from reporting
  27388. ** errors. The reports issued by valgrind are incorrect - we would
  27389. ** prefer that the randomness be increased by making use of the
  27390. ** uninitialized space in zBuf - but valgrind errors tend to worry
  27391. ** some users. Rather than argue, it seems easier just to initialize
  27392. ** the whole array and silence valgrind, even if that means less randomness
  27393. ** in the random seed.
  27394. **
  27395. ** When testing, initializing zBuf[] to zero is all we do. That means
  27396. ** that we always use the same random number sequence. This makes the
  27397. ** tests repeatable.
  27398. */
  27399. memset(zBuf, 0, nBuf);
  27400. #if !defined(SQLITE_TEST)
  27401. {
  27402. int pid, fd, got;
  27403. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  27404. if( fd<0 ){
  27405. time_t t;
  27406. time(&t);
  27407. memcpy(zBuf, &t, sizeof(t));
  27408. pid = getpid();
  27409. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  27410. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  27411. nBuf = sizeof(t) + sizeof(pid);
  27412. }else{
  27413. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  27414. robust_close(0, fd, __LINE__);
  27415. }
  27416. }
  27417. #endif
  27418. return nBuf;
  27419. }
  27420. /*
  27421. ** Sleep for a little while. Return the amount of time slept.
  27422. ** The argument is the number of microseconds we want to sleep.
  27423. ** The return value is the number of microseconds of sleep actually
  27424. ** requested from the underlying operating system, a number which
  27425. ** might be greater than or equal to the argument, but not less
  27426. ** than the argument.
  27427. */
  27428. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  27429. #if OS_VXWORKS
  27430. struct timespec sp;
  27431. sp.tv_sec = microseconds / 1000000;
  27432. sp.tv_nsec = (microseconds % 1000000) * 1000;
  27433. nanosleep(&sp, NULL);
  27434. UNUSED_PARAMETER(NotUsed);
  27435. return microseconds;
  27436. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  27437. usleep(microseconds);
  27438. UNUSED_PARAMETER(NotUsed);
  27439. return microseconds;
  27440. #else
  27441. int seconds = (microseconds+999999)/1000000;
  27442. sleep(seconds);
  27443. UNUSED_PARAMETER(NotUsed);
  27444. return seconds*1000000;
  27445. #endif
  27446. }
  27447. /*
  27448. ** The following variable, if set to a non-zero value, is interpreted as
  27449. ** the number of seconds since 1970 and is used to set the result of
  27450. ** sqlite3OsCurrentTime() during testing.
  27451. */
  27452. #ifdef SQLITE_TEST
  27453. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  27454. #endif
  27455. /*
  27456. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  27457. ** the current time and date as a Julian Day number times 86_400_000. In
  27458. ** other words, write into *piNow the number of milliseconds since the Julian
  27459. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  27460. ** proleptic Gregorian calendar.
  27461. **
  27462. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  27463. ** cannot be found.
  27464. */
  27465. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  27466. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  27467. int rc = SQLITE_OK;
  27468. #if defined(NO_GETTOD)
  27469. time_t t;
  27470. time(&t);
  27471. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  27472. #elif OS_VXWORKS
  27473. struct timespec sNow;
  27474. clock_gettime(CLOCK_REALTIME, &sNow);
  27475. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  27476. #else
  27477. struct timeval sNow;
  27478. if( gettimeofday(&sNow, 0)==0 ){
  27479. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  27480. }else{
  27481. rc = SQLITE_ERROR;
  27482. }
  27483. #endif
  27484. #ifdef SQLITE_TEST
  27485. if( sqlite3_current_time ){
  27486. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  27487. }
  27488. #endif
  27489. UNUSED_PARAMETER(NotUsed);
  27490. return rc;
  27491. }
  27492. /*
  27493. ** Find the current time (in Universal Coordinated Time). Write the
  27494. ** current time and date as a Julian Day number into *prNow and
  27495. ** return 0. Return 1 if the time and date cannot be found.
  27496. */
  27497. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  27498. sqlite3_int64 i = 0;
  27499. int rc;
  27500. UNUSED_PARAMETER(NotUsed);
  27501. rc = unixCurrentTimeInt64(0, &i);
  27502. *prNow = i/86400000.0;
  27503. return rc;
  27504. }
  27505. /*
  27506. ** We added the xGetLastError() method with the intention of providing
  27507. ** better low-level error messages when operating-system problems come up
  27508. ** during SQLite operation. But so far, none of that has been implemented
  27509. ** in the core. So this routine is never called. For now, it is merely
  27510. ** a place-holder.
  27511. */
  27512. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  27513. UNUSED_PARAMETER(NotUsed);
  27514. UNUSED_PARAMETER(NotUsed2);
  27515. UNUSED_PARAMETER(NotUsed3);
  27516. return 0;
  27517. }
  27518. /*
  27519. ************************ End of sqlite3_vfs methods ***************************
  27520. ******************************************************************************/
  27521. /******************************************************************************
  27522. ************************** Begin Proxy Locking ********************************
  27523. **
  27524. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  27525. ** other locking methods on secondary lock files. Proxy locking is a
  27526. ** meta-layer over top of the primitive locking implemented above. For
  27527. ** this reason, the division that implements of proxy locking is deferred
  27528. ** until late in the file (here) after all of the other I/O methods have
  27529. ** been defined - so that the primitive locking methods are available
  27530. ** as services to help with the implementation of proxy locking.
  27531. **
  27532. ****
  27533. **
  27534. ** The default locking schemes in SQLite use byte-range locks on the
  27535. ** database file to coordinate safe, concurrent access by multiple readers
  27536. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  27537. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  27538. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  27539. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  27540. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  27541. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  27542. ** address in the shared range is taken for a SHARED lock, the entire
  27543. ** shared range is taken for an EXCLUSIVE lock):
  27544. **
  27545. ** PENDING_BYTE 0x40000000
  27546. ** RESERVED_BYTE 0x40000001
  27547. ** SHARED_RANGE 0x40000002 -> 0x40000200
  27548. **
  27549. ** This works well on the local file system, but shows a nearly 100x
  27550. ** slowdown in read performance on AFP because the AFP client disables
  27551. ** the read cache when byte-range locks are present. Enabling the read
  27552. ** cache exposes a cache coherency problem that is present on all OS X
  27553. ** supported network file systems. NFS and AFP both observe the
  27554. ** close-to-open semantics for ensuring cache coherency
  27555. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  27556. ** address the requirements for concurrent database access by multiple
  27557. ** readers and writers
  27558. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  27559. **
  27560. ** To address the performance and cache coherency issues, proxy file locking
  27561. ** changes the way database access is controlled by limiting access to a
  27562. ** single host at a time and moving file locks off of the database file
  27563. ** and onto a proxy file on the local file system.
  27564. **
  27565. **
  27566. ** Using proxy locks
  27567. ** -----------------
  27568. **
  27569. ** C APIs
  27570. **
  27571. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  27572. ** <proxy_path> | ":auto:");
  27573. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  27574. **
  27575. **
  27576. ** SQL pragmas
  27577. **
  27578. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  27579. ** PRAGMA [database.]lock_proxy_file
  27580. **
  27581. ** Specifying ":auto:" means that if there is a conch file with a matching
  27582. ** host ID in it, the proxy path in the conch file will be used, otherwise
  27583. ** a proxy path based on the user's temp dir
  27584. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  27585. ** actual proxy file name is generated from the name and path of the
  27586. ** database file. For example:
  27587. **
  27588. ** For database path "/Users/me/foo.db"
  27589. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  27590. **
  27591. ** Once a lock proxy is configured for a database connection, it can not
  27592. ** be removed, however it may be switched to a different proxy path via
  27593. ** the above APIs (assuming the conch file is not being held by another
  27594. ** connection or process).
  27595. **
  27596. **
  27597. ** How proxy locking works
  27598. ** -----------------------
  27599. **
  27600. ** Proxy file locking relies primarily on two new supporting files:
  27601. **
  27602. ** * conch file to limit access to the database file to a single host
  27603. ** at a time
  27604. **
  27605. ** * proxy file to act as a proxy for the advisory locks normally
  27606. ** taken on the database
  27607. **
  27608. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  27609. ** by taking an sqlite-style shared lock on the conch file, reading the
  27610. ** contents and comparing the host's unique host ID (see below) and lock
  27611. ** proxy path against the values stored in the conch. The conch file is
  27612. ** stored in the same directory as the database file and the file name
  27613. ** is patterned after the database file name as ".<databasename>-conch".
  27614. ** If the conch file does not exist, or it's contents do not match the
  27615. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  27616. ** lock and the conch file contents is updated with the host ID and proxy
  27617. ** path and the lock is downgraded to a shared lock again. If the conch
  27618. ** is held by another process (with a shared lock), the exclusive lock
  27619. ** will fail and SQLITE_BUSY is returned.
  27620. **
  27621. ** The proxy file - a single-byte file used for all advisory file locks
  27622. ** normally taken on the database file. This allows for safe sharing
  27623. ** of the database file for multiple readers and writers on the same
  27624. ** host (the conch ensures that they all use the same local lock file).
  27625. **
  27626. ** Requesting the lock proxy does not immediately take the conch, it is
  27627. ** only taken when the first request to lock database file is made.
  27628. ** This matches the semantics of the traditional locking behavior, where
  27629. ** opening a connection to a database file does not take a lock on it.
  27630. ** The shared lock and an open file descriptor are maintained until
  27631. ** the connection to the database is closed.
  27632. **
  27633. ** The proxy file and the lock file are never deleted so they only need
  27634. ** to be created the first time they are used.
  27635. **
  27636. ** Configuration options
  27637. ** ---------------------
  27638. **
  27639. ** SQLITE_PREFER_PROXY_LOCKING
  27640. **
  27641. ** Database files accessed on non-local file systems are
  27642. ** automatically configured for proxy locking, lock files are
  27643. ** named automatically using the same logic as
  27644. ** PRAGMA lock_proxy_file=":auto:"
  27645. **
  27646. ** SQLITE_PROXY_DEBUG
  27647. **
  27648. ** Enables the logging of error messages during host id file
  27649. ** retrieval and creation
  27650. **
  27651. ** LOCKPROXYDIR
  27652. **
  27653. ** Overrides the default directory used for lock proxy files that
  27654. ** are named automatically via the ":auto:" setting
  27655. **
  27656. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  27657. **
  27658. ** Permissions to use when creating a directory for storing the
  27659. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  27660. **
  27661. **
  27662. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  27663. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  27664. ** force proxy locking to be used for every database file opened, and 0
  27665. ** will force automatic proxy locking to be disabled for all database
  27666. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  27667. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  27668. */
  27669. /*
  27670. ** Proxy locking is only available on MacOSX
  27671. */
  27672. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27673. /*
  27674. ** The proxyLockingContext has the path and file structures for the remote
  27675. ** and local proxy files in it
  27676. */
  27677. typedef struct proxyLockingContext proxyLockingContext;
  27678. struct proxyLockingContext {
  27679. unixFile *conchFile; /* Open conch file */
  27680. char *conchFilePath; /* Name of the conch file */
  27681. unixFile *lockProxy; /* Open proxy lock file */
  27682. char *lockProxyPath; /* Name of the proxy lock file */
  27683. char *dbPath; /* Name of the open file */
  27684. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  27685. void *oldLockingContext; /* Original lockingcontext to restore on close */
  27686. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  27687. };
  27688. /*
  27689. ** The proxy lock file path for the database at dbPath is written into lPath,
  27690. ** which must point to valid, writable memory large enough for a maxLen length
  27691. ** file path.
  27692. */
  27693. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  27694. int len;
  27695. int dbLen;
  27696. int i;
  27697. #ifdef LOCKPROXYDIR
  27698. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  27699. #else
  27700. # ifdef _CS_DARWIN_USER_TEMP_DIR
  27701. {
  27702. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  27703. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  27704. lPath, errno, getpid()));
  27705. return SQLITE_IOERR_LOCK;
  27706. }
  27707. len = strlcat(lPath, "sqliteplocks", maxLen);
  27708. }
  27709. # else
  27710. len = strlcpy(lPath, "/tmp/", maxLen);
  27711. # endif
  27712. #endif
  27713. if( lPath[len-1]!='/' ){
  27714. len = strlcat(lPath, "/", maxLen);
  27715. }
  27716. /* transform the db path to a unique cache name */
  27717. dbLen = (int)strlen(dbPath);
  27718. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  27719. char c = dbPath[i];
  27720. lPath[i+len] = (c=='/')?'_':c;
  27721. }
  27722. lPath[i+len]='\0';
  27723. strlcat(lPath, ":auto:", maxLen);
  27724. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  27725. return SQLITE_OK;
  27726. }
  27727. /*
  27728. ** Creates the lock file and any missing directories in lockPath
  27729. */
  27730. static int proxyCreateLockPath(const char *lockPath){
  27731. int i, len;
  27732. char buf[MAXPATHLEN];
  27733. int start = 0;
  27734. assert(lockPath!=NULL);
  27735. /* try to create all the intermediate directories */
  27736. len = (int)strlen(lockPath);
  27737. buf[0] = lockPath[0];
  27738. for( i=1; i<len; i++ ){
  27739. if( lockPath[i] == '/' && (i - start > 0) ){
  27740. /* only mkdir if leaf dir != "." or "/" or ".." */
  27741. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  27742. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  27743. buf[i]='\0';
  27744. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  27745. int err=errno;
  27746. if( err!=EEXIST ) {
  27747. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  27748. "'%s' proxy lock path=%s pid=%d\n",
  27749. buf, strerror(err), lockPath, getpid()));
  27750. return err;
  27751. }
  27752. }
  27753. }
  27754. start=i+1;
  27755. }
  27756. buf[i] = lockPath[i];
  27757. }
  27758. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  27759. return 0;
  27760. }
  27761. /*
  27762. ** Create a new VFS file descriptor (stored in memory obtained from
  27763. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  27764. **
  27765. ** The caller is responsible not only for closing the file descriptor
  27766. ** but also for freeing the memory associated with the file descriptor.
  27767. */
  27768. static int proxyCreateUnixFile(
  27769. const char *path, /* path for the new unixFile */
  27770. unixFile **ppFile, /* unixFile created and returned by ref */
  27771. int islockfile /* if non zero missing dirs will be created */
  27772. ) {
  27773. int fd = -1;
  27774. unixFile *pNew;
  27775. int rc = SQLITE_OK;
  27776. int openFlags = O_RDWR | O_CREAT;
  27777. sqlite3_vfs dummyVfs;
  27778. int terrno = 0;
  27779. UnixUnusedFd *pUnused = NULL;
  27780. /* 1. first try to open/create the file
  27781. ** 2. if that fails, and this is a lock file (not-conch), try creating
  27782. ** the parent directories and then try again.
  27783. ** 3. if that fails, try to open the file read-only
  27784. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  27785. */
  27786. pUnused = findReusableFd(path, openFlags);
  27787. if( pUnused ){
  27788. fd = pUnused->fd;
  27789. }else{
  27790. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27791. if( !pUnused ){
  27792. return SQLITE_NOMEM;
  27793. }
  27794. }
  27795. if( fd<0 ){
  27796. fd = robust_open(path, openFlags, 0);
  27797. terrno = errno;
  27798. if( fd<0 && errno==ENOENT && islockfile ){
  27799. if( proxyCreateLockPath(path) == SQLITE_OK ){
  27800. fd = robust_open(path, openFlags, 0);
  27801. }
  27802. }
  27803. }
  27804. if( fd<0 ){
  27805. openFlags = O_RDONLY;
  27806. fd = robust_open(path, openFlags, 0);
  27807. terrno = errno;
  27808. }
  27809. if( fd<0 ){
  27810. if( islockfile ){
  27811. return SQLITE_BUSY;
  27812. }
  27813. switch (terrno) {
  27814. case EACCES:
  27815. return SQLITE_PERM;
  27816. case EIO:
  27817. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  27818. default:
  27819. return SQLITE_CANTOPEN_BKPT;
  27820. }
  27821. }
  27822. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  27823. if( pNew==NULL ){
  27824. rc = SQLITE_NOMEM;
  27825. goto end_create_proxy;
  27826. }
  27827. memset(pNew, 0, sizeof(unixFile));
  27828. pNew->openFlags = openFlags;
  27829. memset(&dummyVfs, 0, sizeof(dummyVfs));
  27830. dummyVfs.pAppData = (void*)&autolockIoFinder;
  27831. dummyVfs.zName = "dummy";
  27832. pUnused->fd = fd;
  27833. pUnused->flags = openFlags;
  27834. pNew->pUnused = pUnused;
  27835. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  27836. if( rc==SQLITE_OK ){
  27837. *ppFile = pNew;
  27838. return SQLITE_OK;
  27839. }
  27840. end_create_proxy:
  27841. robust_close(pNew, fd, __LINE__);
  27842. sqlite3_free(pNew);
  27843. sqlite3_free(pUnused);
  27844. return rc;
  27845. }
  27846. #ifdef SQLITE_TEST
  27847. /* simulate multiple hosts by creating unique hostid file paths */
  27848. SQLITE_API int sqlite3_hostid_num = 0;
  27849. #endif
  27850. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  27851. /* Not always defined in the headers as it ought to be */
  27852. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  27853. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  27854. ** bytes of writable memory.
  27855. */
  27856. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  27857. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  27858. memset(pHostID, 0, PROXY_HOSTIDLEN);
  27859. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  27860. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  27861. {
  27862. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  27863. if( gethostuuid(pHostID, &timeout) ){
  27864. int err = errno;
  27865. if( pError ){
  27866. *pError = err;
  27867. }
  27868. return SQLITE_IOERR;
  27869. }
  27870. }
  27871. #else
  27872. UNUSED_PARAMETER(pError);
  27873. #endif
  27874. #ifdef SQLITE_TEST
  27875. /* simulate multiple hosts by creating unique hostid file paths */
  27876. if( sqlite3_hostid_num != 0){
  27877. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  27878. }
  27879. #endif
  27880. return SQLITE_OK;
  27881. }
  27882. /* The conch file contains the header, host id and lock file path
  27883. */
  27884. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  27885. #define PROXY_HEADERLEN 1 /* conch file header length */
  27886. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  27887. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  27888. /*
  27889. ** Takes an open conch file, copies the contents to a new path and then moves
  27890. ** it back. The newly created file's file descriptor is assigned to the
  27891. ** conch file structure and finally the original conch file descriptor is
  27892. ** closed. Returns zero if successful.
  27893. */
  27894. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  27895. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27896. unixFile *conchFile = pCtx->conchFile;
  27897. char tPath[MAXPATHLEN];
  27898. char buf[PROXY_MAXCONCHLEN];
  27899. char *cPath = pCtx->conchFilePath;
  27900. size_t readLen = 0;
  27901. size_t pathLen = 0;
  27902. char errmsg[64] = "";
  27903. int fd = -1;
  27904. int rc = -1;
  27905. UNUSED_PARAMETER(myHostID);
  27906. /* create a new path by replace the trailing '-conch' with '-break' */
  27907. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  27908. if( pathLen>MAXPATHLEN || pathLen<6 ||
  27909. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  27910. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  27911. goto end_breaklock;
  27912. }
  27913. /* read the conch content */
  27914. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  27915. if( readLen<PROXY_PATHINDEX ){
  27916. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  27917. goto end_breaklock;
  27918. }
  27919. /* write it out to the temporary break file */
  27920. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  27921. if( fd<0 ){
  27922. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  27923. goto end_breaklock;
  27924. }
  27925. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  27926. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  27927. goto end_breaklock;
  27928. }
  27929. if( rename(tPath, cPath) ){
  27930. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  27931. goto end_breaklock;
  27932. }
  27933. rc = 0;
  27934. fprintf(stderr, "broke stale lock on %s\n", cPath);
  27935. robust_close(pFile, conchFile->h, __LINE__);
  27936. conchFile->h = fd;
  27937. conchFile->openFlags = O_RDWR | O_CREAT;
  27938. end_breaklock:
  27939. if( rc ){
  27940. if( fd>=0 ){
  27941. osUnlink(tPath);
  27942. robust_close(pFile, fd, __LINE__);
  27943. }
  27944. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  27945. }
  27946. return rc;
  27947. }
  27948. /* Take the requested lock on the conch file and break a stale lock if the
  27949. ** host id matches.
  27950. */
  27951. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  27952. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27953. unixFile *conchFile = pCtx->conchFile;
  27954. int rc = SQLITE_OK;
  27955. int nTries = 0;
  27956. struct timespec conchModTime;
  27957. memset(&conchModTime, 0, sizeof(conchModTime));
  27958. do {
  27959. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  27960. nTries ++;
  27961. if( rc==SQLITE_BUSY ){
  27962. /* If the lock failed (busy):
  27963. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  27964. * 2nd try: fail if the mod time changed or host id is different, wait
  27965. * 10 sec and try again
  27966. * 3rd try: break the lock unless the mod time has changed.
  27967. */
  27968. struct stat buf;
  27969. if( osFstat(conchFile->h, &buf) ){
  27970. pFile->lastErrno = errno;
  27971. return SQLITE_IOERR_LOCK;
  27972. }
  27973. if( nTries==1 ){
  27974. conchModTime = buf.st_mtimespec;
  27975. usleep(500000); /* wait 0.5 sec and try the lock again*/
  27976. continue;
  27977. }
  27978. assert( nTries>1 );
  27979. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  27980. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  27981. return SQLITE_BUSY;
  27982. }
  27983. if( nTries==2 ){
  27984. char tBuf[PROXY_MAXCONCHLEN];
  27985. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  27986. if( len<0 ){
  27987. pFile->lastErrno = errno;
  27988. return SQLITE_IOERR_LOCK;
  27989. }
  27990. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  27991. /* don't break the lock if the host id doesn't match */
  27992. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  27993. return SQLITE_BUSY;
  27994. }
  27995. }else{
  27996. /* don't break the lock on short read or a version mismatch */
  27997. return SQLITE_BUSY;
  27998. }
  27999. usleep(10000000); /* wait 10 sec and try the lock again */
  28000. continue;
  28001. }
  28002. assert( nTries==3 );
  28003. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  28004. rc = SQLITE_OK;
  28005. if( lockType==EXCLUSIVE_LOCK ){
  28006. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  28007. }
  28008. if( !rc ){
  28009. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28010. }
  28011. }
  28012. }
  28013. } while( rc==SQLITE_BUSY && nTries<3 );
  28014. return rc;
  28015. }
  28016. /* Takes the conch by taking a shared lock and read the contents conch, if
  28017. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  28018. ** lockPath means that the lockPath in the conch file will be used if the
  28019. ** host IDs match, or a new lock path will be generated automatically
  28020. ** and written to the conch file.
  28021. */
  28022. static int proxyTakeConch(unixFile *pFile){
  28023. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28024. if( pCtx->conchHeld!=0 ){
  28025. return SQLITE_OK;
  28026. }else{
  28027. unixFile *conchFile = pCtx->conchFile;
  28028. uuid_t myHostID;
  28029. int pError = 0;
  28030. char readBuf[PROXY_MAXCONCHLEN];
  28031. char lockPath[MAXPATHLEN];
  28032. char *tempLockPath = NULL;
  28033. int rc = SQLITE_OK;
  28034. int createConch = 0;
  28035. int hostIdMatch = 0;
  28036. int readLen = 0;
  28037. int tryOldLockPath = 0;
  28038. int forceNewLockPath = 0;
  28039. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  28040. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  28041. rc = proxyGetHostID(myHostID, &pError);
  28042. if( (rc&0xff)==SQLITE_IOERR ){
  28043. pFile->lastErrno = pError;
  28044. goto end_takeconch;
  28045. }
  28046. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  28047. if( rc!=SQLITE_OK ){
  28048. goto end_takeconch;
  28049. }
  28050. /* read the existing conch file */
  28051. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  28052. if( readLen<0 ){
  28053. /* I/O error: lastErrno set by seekAndRead */
  28054. pFile->lastErrno = conchFile->lastErrno;
  28055. rc = SQLITE_IOERR_READ;
  28056. goto end_takeconch;
  28057. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  28058. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  28059. /* a short read or version format mismatch means we need to create a new
  28060. ** conch file.
  28061. */
  28062. createConch = 1;
  28063. }
  28064. /* if the host id matches and the lock path already exists in the conch
  28065. ** we'll try to use the path there, if we can't open that path, we'll
  28066. ** retry with a new auto-generated path
  28067. */
  28068. do { /* in case we need to try again for an :auto: named lock file */
  28069. if( !createConch && !forceNewLockPath ){
  28070. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  28071. PROXY_HOSTIDLEN);
  28072. /* if the conch has data compare the contents */
  28073. if( !pCtx->lockProxyPath ){
  28074. /* for auto-named local lock file, just check the host ID and we'll
  28075. ** use the local lock file path that's already in there
  28076. */
  28077. if( hostIdMatch ){
  28078. size_t pathLen = (readLen - PROXY_PATHINDEX);
  28079. if( pathLen>=MAXPATHLEN ){
  28080. pathLen=MAXPATHLEN-1;
  28081. }
  28082. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  28083. lockPath[pathLen] = 0;
  28084. tempLockPath = lockPath;
  28085. tryOldLockPath = 1;
  28086. /* create a copy of the lock path if the conch is taken */
  28087. goto end_takeconch;
  28088. }
  28089. }else if( hostIdMatch
  28090. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  28091. readLen-PROXY_PATHINDEX)
  28092. ){
  28093. /* conch host and lock path match */
  28094. goto end_takeconch;
  28095. }
  28096. }
  28097. /* if the conch isn't writable and doesn't match, we can't take it */
  28098. if( (conchFile->openFlags&O_RDWR) == 0 ){
  28099. rc = SQLITE_BUSY;
  28100. goto end_takeconch;
  28101. }
  28102. /* either the conch didn't match or we need to create a new one */
  28103. if( !pCtx->lockProxyPath ){
  28104. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  28105. tempLockPath = lockPath;
  28106. /* create a copy of the lock path _only_ if the conch is taken */
  28107. }
  28108. /* update conch with host and path (this will fail if other process
  28109. ** has a shared lock already), if the host id matches, use the big
  28110. ** stick.
  28111. */
  28112. futimes(conchFile->h, NULL);
  28113. if( hostIdMatch && !createConch ){
  28114. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  28115. /* We are trying for an exclusive lock but another thread in this
  28116. ** same process is still holding a shared lock. */
  28117. rc = SQLITE_BUSY;
  28118. } else {
  28119. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  28120. }
  28121. }else{
  28122. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  28123. }
  28124. if( rc==SQLITE_OK ){
  28125. char writeBuffer[PROXY_MAXCONCHLEN];
  28126. int writeSize = 0;
  28127. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  28128. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  28129. if( pCtx->lockProxyPath!=NULL ){
  28130. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  28131. }else{
  28132. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  28133. }
  28134. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  28135. robust_ftruncate(conchFile->h, writeSize);
  28136. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  28137. fsync(conchFile->h);
  28138. /* If we created a new conch file (not just updated the contents of a
  28139. ** valid conch file), try to match the permissions of the database
  28140. */
  28141. if( rc==SQLITE_OK && createConch ){
  28142. struct stat buf;
  28143. int err = osFstat(pFile->h, &buf);
  28144. if( err==0 ){
  28145. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  28146. S_IROTH|S_IWOTH);
  28147. /* try to match the database file R/W permissions, ignore failure */
  28148. #ifndef SQLITE_PROXY_DEBUG
  28149. osFchmod(conchFile->h, cmode);
  28150. #else
  28151. do{
  28152. rc = osFchmod(conchFile->h, cmode);
  28153. }while( rc==(-1) && errno==EINTR );
  28154. if( rc!=0 ){
  28155. int code = errno;
  28156. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  28157. cmode, code, strerror(code));
  28158. } else {
  28159. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  28160. }
  28161. }else{
  28162. int code = errno;
  28163. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  28164. err, code, strerror(code));
  28165. #endif
  28166. }
  28167. }
  28168. }
  28169. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  28170. end_takeconch:
  28171. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  28172. if( rc==SQLITE_OK && pFile->openFlags ){
  28173. int fd;
  28174. if( pFile->h>=0 ){
  28175. robust_close(pFile, pFile->h, __LINE__);
  28176. }
  28177. pFile->h = -1;
  28178. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  28179. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  28180. if( fd>=0 ){
  28181. pFile->h = fd;
  28182. }else{
  28183. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  28184. during locking */
  28185. }
  28186. }
  28187. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  28188. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  28189. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  28190. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  28191. /* we couldn't create the proxy lock file with the old lock file path
  28192. ** so try again via auto-naming
  28193. */
  28194. forceNewLockPath = 1;
  28195. tryOldLockPath = 0;
  28196. continue; /* go back to the do {} while start point, try again */
  28197. }
  28198. }
  28199. if( rc==SQLITE_OK ){
  28200. /* Need to make a copy of path if we extracted the value
  28201. ** from the conch file or the path was allocated on the stack
  28202. */
  28203. if( tempLockPath ){
  28204. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  28205. if( !pCtx->lockProxyPath ){
  28206. rc = SQLITE_NOMEM;
  28207. }
  28208. }
  28209. }
  28210. if( rc==SQLITE_OK ){
  28211. pCtx->conchHeld = 1;
  28212. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  28213. afpLockingContext *afpCtx;
  28214. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  28215. afpCtx->dbPath = pCtx->lockProxyPath;
  28216. }
  28217. } else {
  28218. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28219. }
  28220. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  28221. rc==SQLITE_OK?"ok":"failed"));
  28222. return rc;
  28223. } while (1); /* in case we need to retry the :auto: lock file -
  28224. ** we should never get here except via the 'continue' call. */
  28225. }
  28226. }
  28227. /*
  28228. ** If pFile holds a lock on a conch file, then release that lock.
  28229. */
  28230. static int proxyReleaseConch(unixFile *pFile){
  28231. int rc = SQLITE_OK; /* Subroutine return code */
  28232. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  28233. unixFile *conchFile; /* Name of the conch file */
  28234. pCtx = (proxyLockingContext *)pFile->lockingContext;
  28235. conchFile = pCtx->conchFile;
  28236. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  28237. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  28238. getpid()));
  28239. if( pCtx->conchHeld>0 ){
  28240. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28241. }
  28242. pCtx->conchHeld = 0;
  28243. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  28244. (rc==SQLITE_OK ? "ok" : "failed")));
  28245. return rc;
  28246. }
  28247. /*
  28248. ** Given the name of a database file, compute the name of its conch file.
  28249. ** Store the conch filename in memory obtained from sqlite3_malloc().
  28250. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  28251. ** or SQLITE_NOMEM if unable to obtain memory.
  28252. **
  28253. ** The caller is responsible for ensuring that the allocated memory
  28254. ** space is eventually freed.
  28255. **
  28256. ** *pConchPath is set to NULL if a memory allocation error occurs.
  28257. */
  28258. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  28259. int i; /* Loop counter */
  28260. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  28261. char *conchPath; /* buffer in which to construct conch name */
  28262. /* Allocate space for the conch filename and initialize the name to
  28263. ** the name of the original database file. */
  28264. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  28265. if( conchPath==0 ){
  28266. return SQLITE_NOMEM;
  28267. }
  28268. memcpy(conchPath, dbPath, len+1);
  28269. /* now insert a "." before the last / character */
  28270. for( i=(len-1); i>=0; i-- ){
  28271. if( conchPath[i]=='/' ){
  28272. i++;
  28273. break;
  28274. }
  28275. }
  28276. conchPath[i]='.';
  28277. while ( i<len ){
  28278. conchPath[i+1]=dbPath[i];
  28279. i++;
  28280. }
  28281. /* append the "-conch" suffix to the file */
  28282. memcpy(&conchPath[i+1], "-conch", 7);
  28283. assert( (int)strlen(conchPath) == len+7 );
  28284. return SQLITE_OK;
  28285. }
  28286. /* Takes a fully configured proxy locking-style unix file and switches
  28287. ** the local lock file path
  28288. */
  28289. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  28290. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28291. char *oldPath = pCtx->lockProxyPath;
  28292. int rc = SQLITE_OK;
  28293. if( pFile->eFileLock!=NO_LOCK ){
  28294. return SQLITE_BUSY;
  28295. }
  28296. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  28297. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  28298. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  28299. return SQLITE_OK;
  28300. }else{
  28301. unixFile *lockProxy = pCtx->lockProxy;
  28302. pCtx->lockProxy=NULL;
  28303. pCtx->conchHeld = 0;
  28304. if( lockProxy!=NULL ){
  28305. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  28306. if( rc ) return rc;
  28307. sqlite3_free(lockProxy);
  28308. }
  28309. sqlite3_free(oldPath);
  28310. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  28311. }
  28312. return rc;
  28313. }
  28314. /*
  28315. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  28316. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  28317. **
  28318. ** This routine find the filename associated with pFile and writes it
  28319. ** int dbPath.
  28320. */
  28321. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  28322. #if defined(__APPLE__)
  28323. if( pFile->pMethod == &afpIoMethods ){
  28324. /* afp style keeps a reference to the db path in the filePath field
  28325. ** of the struct */
  28326. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28327. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  28328. } else
  28329. #endif
  28330. if( pFile->pMethod == &dotlockIoMethods ){
  28331. /* dot lock style uses the locking context to store the dot lock
  28332. ** file path */
  28333. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  28334. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  28335. }else{
  28336. /* all other styles use the locking context to store the db file path */
  28337. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28338. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  28339. }
  28340. return SQLITE_OK;
  28341. }
  28342. /*
  28343. ** Takes an already filled in unix file and alters it so all file locking
  28344. ** will be performed on the local proxy lock file. The following fields
  28345. ** are preserved in the locking context so that they can be restored and
  28346. ** the unix structure properly cleaned up at close time:
  28347. ** ->lockingContext
  28348. ** ->pMethod
  28349. */
  28350. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  28351. proxyLockingContext *pCtx;
  28352. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  28353. char *lockPath=NULL;
  28354. int rc = SQLITE_OK;
  28355. if( pFile->eFileLock!=NO_LOCK ){
  28356. return SQLITE_BUSY;
  28357. }
  28358. proxyGetDbPathForUnixFile(pFile, dbPath);
  28359. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  28360. lockPath=NULL;
  28361. }else{
  28362. lockPath=(char *)path;
  28363. }
  28364. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  28365. (lockPath ? lockPath : ":auto:"), getpid()));
  28366. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28367. if( pCtx==0 ){
  28368. return SQLITE_NOMEM;
  28369. }
  28370. memset(pCtx, 0, sizeof(*pCtx));
  28371. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  28372. if( rc==SQLITE_OK ){
  28373. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  28374. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  28375. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  28376. ** (c) the file system is read-only, then enable no-locking access.
  28377. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  28378. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  28379. */
  28380. struct statfs fsInfo;
  28381. struct stat conchInfo;
  28382. int goLockless = 0;
  28383. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  28384. int err = errno;
  28385. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  28386. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  28387. }
  28388. }
  28389. if( goLockless ){
  28390. pCtx->conchHeld = -1; /* read only FS/ lockless */
  28391. rc = SQLITE_OK;
  28392. }
  28393. }
  28394. }
  28395. if( rc==SQLITE_OK && lockPath ){
  28396. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  28397. }
  28398. if( rc==SQLITE_OK ){
  28399. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  28400. if( pCtx->dbPath==NULL ){
  28401. rc = SQLITE_NOMEM;
  28402. }
  28403. }
  28404. if( rc==SQLITE_OK ){
  28405. /* all memory is allocated, proxys are created and assigned,
  28406. ** switch the locking context and pMethod then return.
  28407. */
  28408. pCtx->oldLockingContext = pFile->lockingContext;
  28409. pFile->lockingContext = pCtx;
  28410. pCtx->pOldMethod = pFile->pMethod;
  28411. pFile->pMethod = &proxyIoMethods;
  28412. }else{
  28413. if( pCtx->conchFile ){
  28414. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  28415. sqlite3_free(pCtx->conchFile);
  28416. }
  28417. sqlite3DbFree(0, pCtx->lockProxyPath);
  28418. sqlite3_free(pCtx->conchFilePath);
  28419. sqlite3_free(pCtx);
  28420. }
  28421. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  28422. (rc==SQLITE_OK ? "ok" : "failed")));
  28423. return rc;
  28424. }
  28425. /*
  28426. ** This routine handles sqlite3_file_control() calls that are specific
  28427. ** to proxy locking.
  28428. */
  28429. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  28430. switch( op ){
  28431. case SQLITE_GET_LOCKPROXYFILE: {
  28432. unixFile *pFile = (unixFile*)id;
  28433. if( pFile->pMethod == &proxyIoMethods ){
  28434. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28435. proxyTakeConch(pFile);
  28436. if( pCtx->lockProxyPath ){
  28437. *(const char **)pArg = pCtx->lockProxyPath;
  28438. }else{
  28439. *(const char **)pArg = ":auto: (not held)";
  28440. }
  28441. } else {
  28442. *(const char **)pArg = NULL;
  28443. }
  28444. return SQLITE_OK;
  28445. }
  28446. case SQLITE_SET_LOCKPROXYFILE: {
  28447. unixFile *pFile = (unixFile*)id;
  28448. int rc = SQLITE_OK;
  28449. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  28450. if( pArg==NULL || (const char *)pArg==0 ){
  28451. if( isProxyStyle ){
  28452. /* turn off proxy locking - not supported */
  28453. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  28454. }else{
  28455. /* turn off proxy locking - already off - NOOP */
  28456. rc = SQLITE_OK;
  28457. }
  28458. }else{
  28459. const char *proxyPath = (const char *)pArg;
  28460. if( isProxyStyle ){
  28461. proxyLockingContext *pCtx =
  28462. (proxyLockingContext*)pFile->lockingContext;
  28463. if( !strcmp(pArg, ":auto:")
  28464. || (pCtx->lockProxyPath &&
  28465. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  28466. ){
  28467. rc = SQLITE_OK;
  28468. }else{
  28469. rc = switchLockProxyPath(pFile, proxyPath);
  28470. }
  28471. }else{
  28472. /* turn on proxy file locking */
  28473. rc = proxyTransformUnixFile(pFile, proxyPath);
  28474. }
  28475. }
  28476. return rc;
  28477. }
  28478. default: {
  28479. assert( 0 ); /* The call assures that only valid opcodes are sent */
  28480. }
  28481. }
  28482. /*NOTREACHED*/
  28483. return SQLITE_ERROR;
  28484. }
  28485. /*
  28486. ** Within this division (the proxying locking implementation) the procedures
  28487. ** above this point are all utilities. The lock-related methods of the
  28488. ** proxy-locking sqlite3_io_method object follow.
  28489. */
  28490. /*
  28491. ** This routine checks if there is a RESERVED lock held on the specified
  28492. ** file by this or any other process. If such a lock is held, set *pResOut
  28493. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28494. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28495. */
  28496. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28497. unixFile *pFile = (unixFile*)id;
  28498. int rc = proxyTakeConch(pFile);
  28499. if( rc==SQLITE_OK ){
  28500. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28501. if( pCtx->conchHeld>0 ){
  28502. unixFile *proxy = pCtx->lockProxy;
  28503. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  28504. }else{ /* conchHeld < 0 is lockless */
  28505. pResOut=0;
  28506. }
  28507. }
  28508. return rc;
  28509. }
  28510. /*
  28511. ** Lock the file with the lock specified by parameter eFileLock - one
  28512. ** of the following:
  28513. **
  28514. ** (1) SHARED_LOCK
  28515. ** (2) RESERVED_LOCK
  28516. ** (3) PENDING_LOCK
  28517. ** (4) EXCLUSIVE_LOCK
  28518. **
  28519. ** Sometimes when requesting one lock state, additional lock states
  28520. ** are inserted in between. The locking might fail on one of the later
  28521. ** transitions leaving the lock state different from what it started but
  28522. ** still short of its goal. The following chart shows the allowed
  28523. ** transitions and the inserted intermediate states:
  28524. **
  28525. ** UNLOCKED -> SHARED
  28526. ** SHARED -> RESERVED
  28527. ** SHARED -> (PENDING) -> EXCLUSIVE
  28528. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28529. ** PENDING -> EXCLUSIVE
  28530. **
  28531. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28532. ** routine to lower a locking level.
  28533. */
  28534. static int proxyLock(sqlite3_file *id, int eFileLock) {
  28535. unixFile *pFile = (unixFile*)id;
  28536. int rc = proxyTakeConch(pFile);
  28537. if( rc==SQLITE_OK ){
  28538. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28539. if( pCtx->conchHeld>0 ){
  28540. unixFile *proxy = pCtx->lockProxy;
  28541. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  28542. pFile->eFileLock = proxy->eFileLock;
  28543. }else{
  28544. /* conchHeld < 0 is lockless */
  28545. }
  28546. }
  28547. return rc;
  28548. }
  28549. /*
  28550. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28551. ** must be either NO_LOCK or SHARED_LOCK.
  28552. **
  28553. ** If the locking level of the file descriptor is already at or below
  28554. ** the requested locking level, this routine is a no-op.
  28555. */
  28556. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  28557. unixFile *pFile = (unixFile*)id;
  28558. int rc = proxyTakeConch(pFile);
  28559. if( rc==SQLITE_OK ){
  28560. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28561. if( pCtx->conchHeld>0 ){
  28562. unixFile *proxy = pCtx->lockProxy;
  28563. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  28564. pFile->eFileLock = proxy->eFileLock;
  28565. }else{
  28566. /* conchHeld < 0 is lockless */
  28567. }
  28568. }
  28569. return rc;
  28570. }
  28571. /*
  28572. ** Close a file that uses proxy locks.
  28573. */
  28574. static int proxyClose(sqlite3_file *id) {
  28575. if( id ){
  28576. unixFile *pFile = (unixFile*)id;
  28577. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28578. unixFile *lockProxy = pCtx->lockProxy;
  28579. unixFile *conchFile = pCtx->conchFile;
  28580. int rc = SQLITE_OK;
  28581. if( lockProxy ){
  28582. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  28583. if( rc ) return rc;
  28584. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  28585. if( rc ) return rc;
  28586. sqlite3_free(lockProxy);
  28587. pCtx->lockProxy = 0;
  28588. }
  28589. if( conchFile ){
  28590. if( pCtx->conchHeld ){
  28591. rc = proxyReleaseConch(pFile);
  28592. if( rc ) return rc;
  28593. }
  28594. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  28595. if( rc ) return rc;
  28596. sqlite3_free(conchFile);
  28597. }
  28598. sqlite3DbFree(0, pCtx->lockProxyPath);
  28599. sqlite3_free(pCtx->conchFilePath);
  28600. sqlite3DbFree(0, pCtx->dbPath);
  28601. /* restore the original locking context and pMethod then close it */
  28602. pFile->lockingContext = pCtx->oldLockingContext;
  28603. pFile->pMethod = pCtx->pOldMethod;
  28604. sqlite3_free(pCtx);
  28605. return pFile->pMethod->xClose(id);
  28606. }
  28607. return SQLITE_OK;
  28608. }
  28609. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28610. /*
  28611. ** The proxy locking style is intended for use with AFP filesystems.
  28612. ** And since AFP is only supported on MacOSX, the proxy locking is also
  28613. ** restricted to MacOSX.
  28614. **
  28615. **
  28616. ******************* End of the proxy lock implementation **********************
  28617. ******************************************************************************/
  28618. /*
  28619. ** Initialize the operating system interface.
  28620. **
  28621. ** This routine registers all VFS implementations for unix-like operating
  28622. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  28623. ** should be the only routines in this file that are visible from other
  28624. ** files.
  28625. **
  28626. ** This routine is called once during SQLite initialization and by a
  28627. ** single thread. The memory allocation and mutex subsystems have not
  28628. ** necessarily been initialized when this routine is called, and so they
  28629. ** should not be used.
  28630. */
  28631. SQLITE_API int sqlite3_os_init(void){
  28632. /*
  28633. ** The following macro defines an initializer for an sqlite3_vfs object.
  28634. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  28635. ** to the "finder" function. (pAppData is a pointer to a pointer because
  28636. ** silly C90 rules prohibit a void* from being cast to a function pointer
  28637. ** and so we have to go through the intermediate pointer to avoid problems
  28638. ** when compiling with -pedantic-errors on GCC.)
  28639. **
  28640. ** The FINDER parameter to this macro is the name of the pointer to the
  28641. ** finder-function. The finder-function returns a pointer to the
  28642. ** sqlite_io_methods object that implements the desired locking
  28643. ** behaviors. See the division above that contains the IOMETHODS
  28644. ** macro for addition information on finder-functions.
  28645. **
  28646. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  28647. ** object. But the "autolockIoFinder" available on MacOSX does a little
  28648. ** more than that; it looks at the filesystem type that hosts the
  28649. ** database file and tries to choose an locking method appropriate for
  28650. ** that filesystem time.
  28651. */
  28652. #define UNIXVFS(VFSNAME, FINDER) { \
  28653. 3, /* iVersion */ \
  28654. sizeof(unixFile), /* szOsFile */ \
  28655. MAX_PATHNAME, /* mxPathname */ \
  28656. 0, /* pNext */ \
  28657. VFSNAME, /* zName */ \
  28658. (void*)&FINDER, /* pAppData */ \
  28659. unixOpen, /* xOpen */ \
  28660. unixDelete, /* xDelete */ \
  28661. unixAccess, /* xAccess */ \
  28662. unixFullPathname, /* xFullPathname */ \
  28663. unixDlOpen, /* xDlOpen */ \
  28664. unixDlError, /* xDlError */ \
  28665. unixDlSym, /* xDlSym */ \
  28666. unixDlClose, /* xDlClose */ \
  28667. unixRandomness, /* xRandomness */ \
  28668. unixSleep, /* xSleep */ \
  28669. unixCurrentTime, /* xCurrentTime */ \
  28670. unixGetLastError, /* xGetLastError */ \
  28671. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  28672. unixSetSystemCall, /* xSetSystemCall */ \
  28673. unixGetSystemCall, /* xGetSystemCall */ \
  28674. unixNextSystemCall, /* xNextSystemCall */ \
  28675. }
  28676. /*
  28677. ** All default VFSes for unix are contained in the following array.
  28678. **
  28679. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  28680. ** by the SQLite core when the VFS is registered. So the following
  28681. ** array cannot be const.
  28682. */
  28683. static sqlite3_vfs aVfs[] = {
  28684. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  28685. UNIXVFS("unix", autolockIoFinder ),
  28686. #else
  28687. UNIXVFS("unix", posixIoFinder ),
  28688. #endif
  28689. UNIXVFS("unix-none", nolockIoFinder ),
  28690. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  28691. UNIXVFS("unix-excl", posixIoFinder ),
  28692. #if OS_VXWORKS
  28693. UNIXVFS("unix-namedsem", semIoFinder ),
  28694. #endif
  28695. #if SQLITE_ENABLE_LOCKING_STYLE
  28696. UNIXVFS("unix-posix", posixIoFinder ),
  28697. #if !OS_VXWORKS
  28698. UNIXVFS("unix-flock", flockIoFinder ),
  28699. #endif
  28700. #endif
  28701. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28702. UNIXVFS("unix-afp", afpIoFinder ),
  28703. UNIXVFS("unix-nfs", nfsIoFinder ),
  28704. UNIXVFS("unix-proxy", proxyIoFinder ),
  28705. #endif
  28706. };
  28707. unsigned int i; /* Loop counter */
  28708. /* Double-check that the aSyscall[] array has been constructed
  28709. ** correctly. See ticket [bb3a86e890c8e96ab] */
  28710. assert( ArraySize(aSyscall)==24 );
  28711. /* Register all VFSes defined in the aVfs[] array */
  28712. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  28713. sqlite3_vfs_register(&aVfs[i], i==0);
  28714. }
  28715. return SQLITE_OK;
  28716. }
  28717. /*
  28718. ** Shutdown the operating system interface.
  28719. **
  28720. ** Some operating systems might need to do some cleanup in this routine,
  28721. ** to release dynamically allocated objects. But not on unix.
  28722. ** This routine is a no-op for unix.
  28723. */
  28724. SQLITE_API int sqlite3_os_end(void){
  28725. return SQLITE_OK;
  28726. }
  28727. #endif /* SQLITE_OS_UNIX */
  28728. /************** End of os_unix.c *********************************************/
  28729. /************** Begin file os_win.c ******************************************/
  28730. /*
  28731. ** 2004 May 22
  28732. **
  28733. ** The author disclaims copyright to this source code. In place of
  28734. ** a legal notice, here is a blessing:
  28735. **
  28736. ** May you do good and not evil.
  28737. ** May you find forgiveness for yourself and forgive others.
  28738. ** May you share freely, never taking more than you give.
  28739. **
  28740. ******************************************************************************
  28741. **
  28742. ** This file contains code that is specific to Windows.
  28743. */
  28744. #if SQLITE_OS_WIN /* This file is used for Windows only */
  28745. #ifdef __CYGWIN__
  28746. # include <sys/cygwin.h>
  28747. #endif
  28748. /*
  28749. ** Include code that is common to all os_*.c files
  28750. */
  28751. /************** Include os_common.h in the middle of os_win.c ****************/
  28752. /************** Begin file os_common.h ***************************************/
  28753. /*
  28754. ** 2004 May 22
  28755. **
  28756. ** The author disclaims copyright to this source code. In place of
  28757. ** a legal notice, here is a blessing:
  28758. **
  28759. ** May you do good and not evil.
  28760. ** May you find forgiveness for yourself and forgive others.
  28761. ** May you share freely, never taking more than you give.
  28762. **
  28763. ******************************************************************************
  28764. **
  28765. ** This file contains macros and a little bit of code that is common to
  28766. ** all of the platform-specific files (os_*.c) and is #included into those
  28767. ** files.
  28768. **
  28769. ** This file should be #included by the os_*.c files only. It is not a
  28770. ** general purpose header file.
  28771. */
  28772. #ifndef _OS_COMMON_H_
  28773. #define _OS_COMMON_H_
  28774. /*
  28775. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28776. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28777. ** switch. The following code should catch this problem at compile-time.
  28778. */
  28779. #ifdef MEMORY_DEBUG
  28780. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28781. #endif
  28782. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28783. # ifndef SQLITE_DEBUG_OS_TRACE
  28784. # define SQLITE_DEBUG_OS_TRACE 0
  28785. # endif
  28786. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  28787. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  28788. #else
  28789. # define OSTRACE(X)
  28790. #endif
  28791. /*
  28792. ** Macros for performance tracing. Normally turned off. Only works
  28793. ** on i486 hardware.
  28794. */
  28795. #ifdef SQLITE_PERFORMANCE_TRACE
  28796. /*
  28797. ** hwtime.h contains inline assembler code for implementing
  28798. ** high-performance timing routines.
  28799. */
  28800. /************** Include hwtime.h in the middle of os_common.h ****************/
  28801. /************** Begin file hwtime.h ******************************************/
  28802. /*
  28803. ** 2008 May 27
  28804. **
  28805. ** The author disclaims copyright to this source code. In place of
  28806. ** a legal notice, here is a blessing:
  28807. **
  28808. ** May you do good and not evil.
  28809. ** May you find forgiveness for yourself and forgive others.
  28810. ** May you share freely, never taking more than you give.
  28811. **
  28812. ******************************************************************************
  28813. **
  28814. ** This file contains inline asm code for retrieving "high-performance"
  28815. ** counters for x86 class CPUs.
  28816. */
  28817. #ifndef _HWTIME_H_
  28818. #define _HWTIME_H_
  28819. /*
  28820. ** The following routine only works on pentium-class (or newer) processors.
  28821. ** It uses the RDTSC opcode to read the cycle count value out of the
  28822. ** processor and returns that value. This can be used for high-res
  28823. ** profiling.
  28824. */
  28825. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28826. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  28827. #if defined(__GNUC__)
  28828. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28829. unsigned int lo, hi;
  28830. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  28831. return (sqlite_uint64)hi << 32 | lo;
  28832. }
  28833. #elif defined(_MSC_VER)
  28834. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  28835. __asm {
  28836. rdtsc
  28837. ret ; return value at EDX:EAX
  28838. }
  28839. }
  28840. #endif
  28841. #elif (defined(__GNUC__) && defined(__x86_64__))
  28842. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28843. unsigned long val;
  28844. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  28845. return val;
  28846. }
  28847. #elif (defined(__GNUC__) && defined(__ppc__))
  28848. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28849. unsigned long long retval;
  28850. unsigned long junk;
  28851. __asm__ __volatile__ ("\n\
  28852. 1: mftbu %1\n\
  28853. mftb %L0\n\
  28854. mftbu %0\n\
  28855. cmpw %0,%1\n\
  28856. bne 1b"
  28857. : "=r" (retval), "=r" (junk));
  28858. return retval;
  28859. }
  28860. #else
  28861. #error Need implementation of sqlite3Hwtime() for your platform.
  28862. /*
  28863. ** To compile without implementing sqlite3Hwtime() for your platform,
  28864. ** you can remove the above #error and use the following
  28865. ** stub function. You will lose timing support for many
  28866. ** of the debugging and testing utilities, but it should at
  28867. ** least compile and run.
  28868. */
  28869. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  28870. #endif
  28871. #endif /* !defined(_HWTIME_H_) */
  28872. /************** End of hwtime.h **********************************************/
  28873. /************** Continuing where we left off in os_common.h ******************/
  28874. static sqlite_uint64 g_start;
  28875. static sqlite_uint64 g_elapsed;
  28876. #define TIMER_START g_start=sqlite3Hwtime()
  28877. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  28878. #define TIMER_ELAPSED g_elapsed
  28879. #else
  28880. #define TIMER_START
  28881. #define TIMER_END
  28882. #define TIMER_ELAPSED ((sqlite_uint64)0)
  28883. #endif
  28884. /*
  28885. ** If we compile with the SQLITE_TEST macro set, then the following block
  28886. ** of code will give us the ability to simulate a disk I/O error. This
  28887. ** is used for testing the I/O recovery logic.
  28888. */
  28889. #ifdef SQLITE_TEST
  28890. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  28891. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  28892. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  28893. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  28894. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  28895. SQLITE_API int sqlite3_diskfull_pending = 0;
  28896. SQLITE_API int sqlite3_diskfull = 0;
  28897. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  28898. #define SimulateIOError(CODE) \
  28899. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  28900. || sqlite3_io_error_pending-- == 1 ) \
  28901. { local_ioerr(); CODE; }
  28902. static void local_ioerr(){
  28903. IOTRACE(("IOERR\n"));
  28904. sqlite3_io_error_hit++;
  28905. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  28906. }
  28907. #define SimulateDiskfullError(CODE) \
  28908. if( sqlite3_diskfull_pending ){ \
  28909. if( sqlite3_diskfull_pending == 1 ){ \
  28910. local_ioerr(); \
  28911. sqlite3_diskfull = 1; \
  28912. sqlite3_io_error_hit = 1; \
  28913. CODE; \
  28914. }else{ \
  28915. sqlite3_diskfull_pending--; \
  28916. } \
  28917. }
  28918. #else
  28919. #define SimulateIOErrorBenign(X)
  28920. #define SimulateIOError(A)
  28921. #define SimulateDiskfullError(A)
  28922. #endif
  28923. /*
  28924. ** When testing, keep a count of the number of open files.
  28925. */
  28926. #ifdef SQLITE_TEST
  28927. SQLITE_API int sqlite3_open_file_count = 0;
  28928. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  28929. #else
  28930. #define OpenCounter(X)
  28931. #endif
  28932. #endif /* !defined(_OS_COMMON_H_) */
  28933. /************** End of os_common.h *******************************************/
  28934. /************** Continuing where we left off in os_win.c *********************/
  28935. /*
  28936. ** Compiling and using WAL mode requires several APIs that are only
  28937. ** available in Windows platforms based on the NT kernel.
  28938. */
  28939. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  28940. # error "WAL mode requires support from the Windows NT kernel, compile\
  28941. with SQLITE_OMIT_WAL."
  28942. #endif
  28943. /*
  28944. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  28945. ** based on the sub-platform)?
  28946. */
  28947. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  28948. # define SQLITE_WIN32_HAS_ANSI
  28949. #endif
  28950. /*
  28951. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  28952. ** based on the sub-platform)?
  28953. */
  28954. #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
  28955. # define SQLITE_WIN32_HAS_WIDE
  28956. #endif
  28957. /*
  28958. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  28959. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  28960. ** are not present in the header file)?
  28961. */
  28962. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  28963. /*
  28964. ** Two of the file mapping APIs are different under WinRT. Figure out which
  28965. ** set we need.
  28966. */
  28967. #if SQLITE_OS_WINRT
  28968. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  28969. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  28970. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  28971. #else
  28972. #if defined(SQLITE_WIN32_HAS_ANSI)
  28973. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  28974. DWORD, DWORD, DWORD, LPCSTR);
  28975. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  28976. #if defined(SQLITE_WIN32_HAS_WIDE)
  28977. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  28978. DWORD, DWORD, DWORD, LPCWSTR);
  28979. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  28980. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  28981. #endif /* SQLITE_OS_WINRT */
  28982. /*
  28983. ** This file mapping API is common to both Win32 and WinRT.
  28984. */
  28985. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  28986. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  28987. /*
  28988. ** Macro to find the minimum of two numeric values.
  28989. */
  28990. #ifndef MIN
  28991. # define MIN(x,y) ((x)<(y)?(x):(y))
  28992. #endif
  28993. /*
  28994. ** Some Microsoft compilers lack this definition.
  28995. */
  28996. #ifndef INVALID_FILE_ATTRIBUTES
  28997. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  28998. #endif
  28999. #ifndef FILE_FLAG_MASK
  29000. # define FILE_FLAG_MASK (0xFF3C0000)
  29001. #endif
  29002. #ifndef FILE_ATTRIBUTE_MASK
  29003. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  29004. #endif
  29005. #ifndef SQLITE_OMIT_WAL
  29006. /* Forward references */
  29007. typedef struct winShm winShm; /* A connection to shared-memory */
  29008. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  29009. #endif
  29010. /*
  29011. ** WinCE lacks native support for file locking so we have to fake it
  29012. ** with some code of our own.
  29013. */
  29014. #if SQLITE_OS_WINCE
  29015. typedef struct winceLock {
  29016. int nReaders; /* Number of reader locks obtained */
  29017. BOOL bPending; /* Indicates a pending lock has been obtained */
  29018. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  29019. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  29020. } winceLock;
  29021. #endif
  29022. /*
  29023. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  29024. ** portability layer.
  29025. */
  29026. typedef struct winFile winFile;
  29027. struct winFile {
  29028. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  29029. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  29030. HANDLE h; /* Handle for accessing the file */
  29031. u8 locktype; /* Type of lock currently held on this file */
  29032. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  29033. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  29034. DWORD lastErrno; /* The Windows errno from the last I/O error */
  29035. #ifndef SQLITE_OMIT_WAL
  29036. winShm *pShm; /* Instance of shared memory on this file */
  29037. #endif
  29038. const char *zPath; /* Full pathname of this file */
  29039. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  29040. #if SQLITE_OS_WINCE
  29041. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  29042. HANDLE hMutex; /* Mutex used to control access to shared lock */
  29043. HANDLE hShared; /* Shared memory segment used for locking */
  29044. winceLock local; /* Locks obtained by this instance of winFile */
  29045. winceLock *shared; /* Global shared lock memory for the file */
  29046. #endif
  29047. #if SQLITE_MAX_MMAP_SIZE>0
  29048. int nFetchOut; /* Number of outstanding xFetch references */
  29049. HANDLE hMap; /* Handle for accessing memory mapping */
  29050. void *pMapRegion; /* Area memory mapped */
  29051. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  29052. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  29053. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  29054. #endif
  29055. };
  29056. /*
  29057. ** Allowed values for winFile.ctrlFlags
  29058. */
  29059. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  29060. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  29061. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  29062. /*
  29063. * The size of the buffer used by sqlite3_win32_write_debug().
  29064. */
  29065. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  29066. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  29067. #endif
  29068. /*
  29069. * The value used with sqlite3_win32_set_directory() to specify that
  29070. * the data directory should be changed.
  29071. */
  29072. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  29073. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  29074. #endif
  29075. /*
  29076. * The value used with sqlite3_win32_set_directory() to specify that
  29077. * the temporary directory should be changed.
  29078. */
  29079. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  29080. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  29081. #endif
  29082. /*
  29083. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  29084. * various Win32 API heap functions instead of our own.
  29085. */
  29086. #ifdef SQLITE_WIN32_MALLOC
  29087. /*
  29088. * If this is non-zero, an isolated heap will be created by the native Win32
  29089. * allocator subsystem; otherwise, the default process heap will be used. This
  29090. * setting has no effect when compiling for WinRT. By default, this is enabled
  29091. * and an isolated heap will be created to store all allocated data.
  29092. *
  29093. ******************************************************************************
  29094. * WARNING: It is important to note that when this setting is non-zero and the
  29095. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  29096. * function), all data that was allocated using the isolated heap will
  29097. * be freed immediately and any attempt to access any of that freed
  29098. * data will almost certainly result in an immediate access violation.
  29099. ******************************************************************************
  29100. */
  29101. #ifndef SQLITE_WIN32_HEAP_CREATE
  29102. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  29103. #endif
  29104. /*
  29105. * The initial size of the Win32-specific heap. This value may be zero.
  29106. */
  29107. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  29108. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  29109. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  29110. #endif
  29111. /*
  29112. * The maximum size of the Win32-specific heap. This value may be zero.
  29113. */
  29114. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  29115. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  29116. #endif
  29117. /*
  29118. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  29119. * zero for the default behavior.
  29120. */
  29121. #ifndef SQLITE_WIN32_HEAP_FLAGS
  29122. # define SQLITE_WIN32_HEAP_FLAGS (0)
  29123. #endif
  29124. /*
  29125. ** The winMemData structure stores information required by the Win32-specific
  29126. ** sqlite3_mem_methods implementation.
  29127. */
  29128. typedef struct winMemData winMemData;
  29129. struct winMemData {
  29130. #ifndef NDEBUG
  29131. u32 magic; /* Magic number to detect structure corruption. */
  29132. #endif
  29133. HANDLE hHeap; /* The handle to our heap. */
  29134. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  29135. };
  29136. #ifndef NDEBUG
  29137. #define WINMEM_MAGIC 0x42b2830b
  29138. #endif
  29139. static struct winMemData win_mem_data = {
  29140. #ifndef NDEBUG
  29141. WINMEM_MAGIC,
  29142. #endif
  29143. NULL, FALSE
  29144. };
  29145. #ifndef NDEBUG
  29146. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  29147. #else
  29148. #define winMemAssertMagic()
  29149. #endif
  29150. #define winMemGetHeap() win_mem_data.hHeap
  29151. static void *winMemMalloc(int nBytes);
  29152. static void winMemFree(void *pPrior);
  29153. static void *winMemRealloc(void *pPrior, int nBytes);
  29154. static int winMemSize(void *p);
  29155. static int winMemRoundup(int n);
  29156. static int winMemInit(void *pAppData);
  29157. static void winMemShutdown(void *pAppData);
  29158. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  29159. #endif /* SQLITE_WIN32_MALLOC */
  29160. /*
  29161. ** The following variable is (normally) set once and never changes
  29162. ** thereafter. It records whether the operating system is Win9x
  29163. ** or WinNT.
  29164. **
  29165. ** 0: Operating system unknown.
  29166. ** 1: Operating system is Win9x.
  29167. ** 2: Operating system is WinNT.
  29168. **
  29169. ** In order to facilitate testing on a WinNT system, the test fixture
  29170. ** can manually set this value to 1 to emulate Win98 behavior.
  29171. */
  29172. #ifdef SQLITE_TEST
  29173. SQLITE_API int sqlite3_os_type = 0;
  29174. #else
  29175. static int sqlite3_os_type = 0;
  29176. #endif
  29177. #ifndef SYSCALL
  29178. # define SYSCALL sqlite3_syscall_ptr
  29179. #endif
  29180. /*
  29181. ** This function is not available on Windows CE or WinRT.
  29182. */
  29183. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29184. # define osAreFileApisANSI() 1
  29185. #endif
  29186. /*
  29187. ** Many system calls are accessed through pointer-to-functions so that
  29188. ** they may be overridden at runtime to facilitate fault injection during
  29189. ** testing and sandboxing. The following array holds the names and pointers
  29190. ** to all overrideable system calls.
  29191. */
  29192. static struct win_syscall {
  29193. const char *zName; /* Name of the system call */
  29194. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  29195. sqlite3_syscall_ptr pDefault; /* Default value */
  29196. } aSyscall[] = {
  29197. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29198. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  29199. #else
  29200. { "AreFileApisANSI", (SYSCALL)0, 0 },
  29201. #endif
  29202. #ifndef osAreFileApisANSI
  29203. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  29204. #endif
  29205. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29206. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  29207. #else
  29208. { "CharLowerW", (SYSCALL)0, 0 },
  29209. #endif
  29210. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  29211. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29212. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  29213. #else
  29214. { "CharUpperW", (SYSCALL)0, 0 },
  29215. #endif
  29216. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  29217. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  29218. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  29219. #if defined(SQLITE_WIN32_HAS_ANSI)
  29220. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  29221. #else
  29222. { "CreateFileA", (SYSCALL)0, 0 },
  29223. #endif
  29224. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  29225. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  29226. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29227. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  29228. #else
  29229. { "CreateFileW", (SYSCALL)0, 0 },
  29230. #endif
  29231. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  29232. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  29233. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  29234. !defined(SQLITE_OMIT_WAL))
  29235. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  29236. #else
  29237. { "CreateFileMappingA", (SYSCALL)0, 0 },
  29238. #endif
  29239. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29240. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  29241. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29242. !defined(SQLITE_OMIT_WAL))
  29243. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  29244. #else
  29245. { "CreateFileMappingW", (SYSCALL)0, 0 },
  29246. #endif
  29247. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29248. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  29249. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29250. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  29251. #else
  29252. { "CreateMutexW", (SYSCALL)0, 0 },
  29253. #endif
  29254. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  29255. LPCWSTR))aSyscall[8].pCurrent)
  29256. #if defined(SQLITE_WIN32_HAS_ANSI)
  29257. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  29258. #else
  29259. { "DeleteFileA", (SYSCALL)0, 0 },
  29260. #endif
  29261. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  29262. #if defined(SQLITE_WIN32_HAS_WIDE)
  29263. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  29264. #else
  29265. { "DeleteFileW", (SYSCALL)0, 0 },
  29266. #endif
  29267. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  29268. #if SQLITE_OS_WINCE
  29269. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  29270. #else
  29271. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  29272. #endif
  29273. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29274. LPFILETIME))aSyscall[11].pCurrent)
  29275. #if SQLITE_OS_WINCE
  29276. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  29277. #else
  29278. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  29279. #endif
  29280. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29281. LPSYSTEMTIME))aSyscall[12].pCurrent)
  29282. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  29283. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  29284. #if defined(SQLITE_WIN32_HAS_ANSI)
  29285. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  29286. #else
  29287. { "FormatMessageA", (SYSCALL)0, 0 },
  29288. #endif
  29289. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  29290. DWORD,va_list*))aSyscall[14].pCurrent)
  29291. #if defined(SQLITE_WIN32_HAS_WIDE)
  29292. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  29293. #else
  29294. { "FormatMessageW", (SYSCALL)0, 0 },
  29295. #endif
  29296. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  29297. DWORD,va_list*))aSyscall[15].pCurrent)
  29298. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29299. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  29300. #else
  29301. { "FreeLibrary", (SYSCALL)0, 0 },
  29302. #endif
  29303. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  29304. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  29305. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  29306. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29307. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  29308. #else
  29309. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  29310. #endif
  29311. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  29312. LPDWORD))aSyscall[18].pCurrent)
  29313. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29314. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  29315. #else
  29316. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  29317. #endif
  29318. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  29319. LPDWORD))aSyscall[19].pCurrent)
  29320. #if defined(SQLITE_WIN32_HAS_ANSI)
  29321. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  29322. #else
  29323. { "GetFileAttributesA", (SYSCALL)0, 0 },
  29324. #endif
  29325. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  29326. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29327. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  29328. #else
  29329. { "GetFileAttributesW", (SYSCALL)0, 0 },
  29330. #endif
  29331. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  29332. #if defined(SQLITE_WIN32_HAS_WIDE)
  29333. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  29334. #else
  29335. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  29336. #endif
  29337. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  29338. LPVOID))aSyscall[22].pCurrent)
  29339. #if !SQLITE_OS_WINRT
  29340. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  29341. #else
  29342. { "GetFileSize", (SYSCALL)0, 0 },
  29343. #endif
  29344. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  29345. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29346. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  29347. #else
  29348. { "GetFullPathNameA", (SYSCALL)0, 0 },
  29349. #endif
  29350. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  29351. LPSTR*))aSyscall[24].pCurrent)
  29352. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29353. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  29354. #else
  29355. { "GetFullPathNameW", (SYSCALL)0, 0 },
  29356. #endif
  29357. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  29358. LPWSTR*))aSyscall[25].pCurrent)
  29359. { "GetLastError", (SYSCALL)GetLastError, 0 },
  29360. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  29361. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29362. #if SQLITE_OS_WINCE
  29363. /* The GetProcAddressA() routine is only available on Windows CE. */
  29364. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  29365. #else
  29366. /* All other Windows platforms expect GetProcAddress() to take
  29367. ** an ANSI string regardless of the _UNICODE setting */
  29368. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  29369. #endif
  29370. #else
  29371. { "GetProcAddressA", (SYSCALL)0, 0 },
  29372. #endif
  29373. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  29374. LPCSTR))aSyscall[27].pCurrent)
  29375. #if !SQLITE_OS_WINRT
  29376. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  29377. #else
  29378. { "GetSystemInfo", (SYSCALL)0, 0 },
  29379. #endif
  29380. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  29381. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  29382. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  29383. #if !SQLITE_OS_WINCE
  29384. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  29385. #else
  29386. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  29387. #endif
  29388. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  29389. LPFILETIME))aSyscall[30].pCurrent)
  29390. #if defined(SQLITE_WIN32_HAS_ANSI)
  29391. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  29392. #else
  29393. { "GetTempPathA", (SYSCALL)0, 0 },
  29394. #endif
  29395. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  29396. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29397. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  29398. #else
  29399. { "GetTempPathW", (SYSCALL)0, 0 },
  29400. #endif
  29401. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  29402. #if !SQLITE_OS_WINRT
  29403. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  29404. #else
  29405. { "GetTickCount", (SYSCALL)0, 0 },
  29406. #endif
  29407. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  29408. #if defined(SQLITE_WIN32_HAS_ANSI)
  29409. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  29410. #else
  29411. { "GetVersionExA", (SYSCALL)0, 0 },
  29412. #endif
  29413. #define osGetVersionExA ((BOOL(WINAPI*)( \
  29414. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  29415. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  29416. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  29417. SIZE_T))aSyscall[35].pCurrent)
  29418. #if !SQLITE_OS_WINRT
  29419. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  29420. #else
  29421. { "HeapCreate", (SYSCALL)0, 0 },
  29422. #endif
  29423. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  29424. SIZE_T))aSyscall[36].pCurrent)
  29425. #if !SQLITE_OS_WINRT
  29426. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  29427. #else
  29428. { "HeapDestroy", (SYSCALL)0, 0 },
  29429. #endif
  29430. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
  29431. { "HeapFree", (SYSCALL)HeapFree, 0 },
  29432. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
  29433. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  29434. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  29435. SIZE_T))aSyscall[39].pCurrent)
  29436. { "HeapSize", (SYSCALL)HeapSize, 0 },
  29437. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  29438. LPCVOID))aSyscall[40].pCurrent)
  29439. #if !SQLITE_OS_WINRT
  29440. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  29441. #else
  29442. { "HeapValidate", (SYSCALL)0, 0 },
  29443. #endif
  29444. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  29445. LPCVOID))aSyscall[41].pCurrent)
  29446. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29447. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  29448. #else
  29449. { "LoadLibraryA", (SYSCALL)0, 0 },
  29450. #endif
  29451. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
  29452. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29453. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29454. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  29455. #else
  29456. { "LoadLibraryW", (SYSCALL)0, 0 },
  29457. #endif
  29458. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
  29459. #if !SQLITE_OS_WINRT
  29460. { "LocalFree", (SYSCALL)LocalFree, 0 },
  29461. #else
  29462. { "LocalFree", (SYSCALL)0, 0 },
  29463. #endif
  29464. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
  29465. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29466. { "LockFile", (SYSCALL)LockFile, 0 },
  29467. #else
  29468. { "LockFile", (SYSCALL)0, 0 },
  29469. #endif
  29470. #ifndef osLockFile
  29471. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29472. DWORD))aSyscall[45].pCurrent)
  29473. #endif
  29474. #if !SQLITE_OS_WINCE
  29475. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  29476. #else
  29477. { "LockFileEx", (SYSCALL)0, 0 },
  29478. #endif
  29479. #ifndef osLockFileEx
  29480. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  29481. LPOVERLAPPED))aSyscall[46].pCurrent)
  29482. #endif
  29483. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  29484. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  29485. #else
  29486. { "MapViewOfFile", (SYSCALL)0, 0 },
  29487. #endif
  29488. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29489. SIZE_T))aSyscall[47].pCurrent)
  29490. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  29491. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  29492. int))aSyscall[48].pCurrent)
  29493. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  29494. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  29495. LARGE_INTEGER*))aSyscall[49].pCurrent)
  29496. { "ReadFile", (SYSCALL)ReadFile, 0 },
  29497. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  29498. LPOVERLAPPED))aSyscall[50].pCurrent)
  29499. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  29500. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
  29501. #if !SQLITE_OS_WINRT
  29502. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  29503. #else
  29504. { "SetFilePointer", (SYSCALL)0, 0 },
  29505. #endif
  29506. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  29507. DWORD))aSyscall[52].pCurrent)
  29508. #if !SQLITE_OS_WINRT
  29509. { "Sleep", (SYSCALL)Sleep, 0 },
  29510. #else
  29511. { "Sleep", (SYSCALL)0, 0 },
  29512. #endif
  29513. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
  29514. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  29515. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  29516. LPFILETIME))aSyscall[54].pCurrent)
  29517. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29518. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  29519. #else
  29520. { "UnlockFile", (SYSCALL)0, 0 },
  29521. #endif
  29522. #ifndef osUnlockFile
  29523. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29524. DWORD))aSyscall[55].pCurrent)
  29525. #endif
  29526. #if !SQLITE_OS_WINCE
  29527. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  29528. #else
  29529. { "UnlockFileEx", (SYSCALL)0, 0 },
  29530. #endif
  29531. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29532. LPOVERLAPPED))aSyscall[56].pCurrent)
  29533. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  29534. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  29535. #else
  29536. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  29537. #endif
  29538. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
  29539. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  29540. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  29541. LPCSTR,LPBOOL))aSyscall[58].pCurrent)
  29542. { "WriteFile", (SYSCALL)WriteFile, 0 },
  29543. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  29544. LPOVERLAPPED))aSyscall[59].pCurrent)
  29545. #if SQLITE_OS_WINRT
  29546. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  29547. #else
  29548. { "CreateEventExW", (SYSCALL)0, 0 },
  29549. #endif
  29550. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  29551. DWORD,DWORD))aSyscall[60].pCurrent)
  29552. #if !SQLITE_OS_WINRT
  29553. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  29554. #else
  29555. { "WaitForSingleObject", (SYSCALL)0, 0 },
  29556. #endif
  29557. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  29558. DWORD))aSyscall[61].pCurrent)
  29559. #if SQLITE_OS_WINRT
  29560. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  29561. #else
  29562. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  29563. #endif
  29564. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  29565. BOOL))aSyscall[62].pCurrent)
  29566. #if SQLITE_OS_WINRT
  29567. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  29568. #else
  29569. { "SetFilePointerEx", (SYSCALL)0, 0 },
  29570. #endif
  29571. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  29572. PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
  29573. #if SQLITE_OS_WINRT
  29574. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  29575. #else
  29576. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  29577. #endif
  29578. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  29579. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
  29580. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29581. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  29582. #else
  29583. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  29584. #endif
  29585. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  29586. SIZE_T))aSyscall[65].pCurrent)
  29587. #if SQLITE_OS_WINRT
  29588. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  29589. #else
  29590. { "CreateFile2", (SYSCALL)0, 0 },
  29591. #endif
  29592. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  29593. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
  29594. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29595. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  29596. #else
  29597. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  29598. #endif
  29599. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  29600. DWORD))aSyscall[67].pCurrent)
  29601. #if SQLITE_OS_WINRT
  29602. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  29603. #else
  29604. { "GetTickCount64", (SYSCALL)0, 0 },
  29605. #endif
  29606. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
  29607. #if SQLITE_OS_WINRT
  29608. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  29609. #else
  29610. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  29611. #endif
  29612. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  29613. LPSYSTEM_INFO))aSyscall[69].pCurrent)
  29614. #if defined(SQLITE_WIN32_HAS_ANSI)
  29615. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  29616. #else
  29617. { "OutputDebugStringA", (SYSCALL)0, 0 },
  29618. #endif
  29619. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
  29620. #if defined(SQLITE_WIN32_HAS_WIDE)
  29621. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  29622. #else
  29623. { "OutputDebugStringW", (SYSCALL)0, 0 },
  29624. #endif
  29625. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
  29626. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  29627. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
  29628. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29629. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  29630. #else
  29631. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  29632. #endif
  29633. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  29634. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
  29635. }; /* End of the overrideable system calls */
  29636. /*
  29637. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  29638. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  29639. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  29640. ** system call named zName.
  29641. */
  29642. static int winSetSystemCall(
  29643. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  29644. const char *zName, /* Name of system call to override */
  29645. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  29646. ){
  29647. unsigned int i;
  29648. int rc = SQLITE_NOTFOUND;
  29649. UNUSED_PARAMETER(pNotUsed);
  29650. if( zName==0 ){
  29651. /* If no zName is given, restore all system calls to their default
  29652. ** settings and return NULL
  29653. */
  29654. rc = SQLITE_OK;
  29655. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29656. if( aSyscall[i].pDefault ){
  29657. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  29658. }
  29659. }
  29660. }else{
  29661. /* If zName is specified, operate on only the one system call
  29662. ** specified.
  29663. */
  29664. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29665. if( strcmp(zName, aSyscall[i].zName)==0 ){
  29666. if( aSyscall[i].pDefault==0 ){
  29667. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  29668. }
  29669. rc = SQLITE_OK;
  29670. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  29671. aSyscall[i].pCurrent = pNewFunc;
  29672. break;
  29673. }
  29674. }
  29675. }
  29676. return rc;
  29677. }
  29678. /*
  29679. ** Return the value of a system call. Return NULL if zName is not a
  29680. ** recognized system call name. NULL is also returned if the system call
  29681. ** is currently undefined.
  29682. */
  29683. static sqlite3_syscall_ptr winGetSystemCall(
  29684. sqlite3_vfs *pNotUsed,
  29685. const char *zName
  29686. ){
  29687. unsigned int i;
  29688. UNUSED_PARAMETER(pNotUsed);
  29689. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29690. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  29691. }
  29692. return 0;
  29693. }
  29694. /*
  29695. ** Return the name of the first system call after zName. If zName==NULL
  29696. ** then return the name of the first system call. Return NULL if zName
  29697. ** is the last system call or if zName is not the name of a valid
  29698. ** system call.
  29699. */
  29700. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  29701. int i = -1;
  29702. UNUSED_PARAMETER(p);
  29703. if( zName ){
  29704. for(i=0; i<ArraySize(aSyscall)-1; i++){
  29705. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  29706. }
  29707. }
  29708. for(i++; i<ArraySize(aSyscall); i++){
  29709. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  29710. }
  29711. return 0;
  29712. }
  29713. /*
  29714. ** This function outputs the specified (ANSI) string to the Win32 debugger
  29715. ** (if available).
  29716. */
  29717. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  29718. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  29719. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  29720. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  29721. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  29722. #if defined(SQLITE_WIN32_HAS_ANSI)
  29723. if( nMin>0 ){
  29724. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29725. memcpy(zDbgBuf, zBuf, nMin);
  29726. osOutputDebugStringA(zDbgBuf);
  29727. }else{
  29728. osOutputDebugStringA(zBuf);
  29729. }
  29730. #elif defined(SQLITE_WIN32_HAS_WIDE)
  29731. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29732. if ( osMultiByteToWideChar(
  29733. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  29734. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  29735. return;
  29736. }
  29737. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  29738. #else
  29739. if( nMin>0 ){
  29740. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29741. memcpy(zDbgBuf, zBuf, nMin);
  29742. fprintf(stderr, "%s", zDbgBuf);
  29743. }else{
  29744. fprintf(stderr, "%s", zBuf);
  29745. }
  29746. #endif
  29747. }
  29748. /*
  29749. ** The following routine suspends the current thread for at least ms
  29750. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  29751. */
  29752. #if SQLITE_OS_WINRT
  29753. static HANDLE sleepObj = NULL;
  29754. #endif
  29755. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  29756. #if SQLITE_OS_WINRT
  29757. if ( sleepObj==NULL ){
  29758. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  29759. SYNCHRONIZE);
  29760. }
  29761. assert( sleepObj!=NULL );
  29762. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  29763. #else
  29764. osSleep(milliseconds);
  29765. #endif
  29766. }
  29767. /*
  29768. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  29769. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  29770. **
  29771. ** Here is an interesting observation: Win95, Win98, and WinME lack
  29772. ** the LockFileEx() API. But we can still statically link against that
  29773. ** API as long as we don't call it when running Win95/98/ME. A call to
  29774. ** this routine is used to determine if the host is Win95/98/ME or
  29775. ** WinNT/2K/XP so that we will know whether or not we can safely call
  29776. ** the LockFileEx() API.
  29777. */
  29778. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29779. # define isNT() (1)
  29780. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  29781. # define isNT() (0)
  29782. #else
  29783. static int isNT(void){
  29784. if( sqlite3_os_type==0 ){
  29785. OSVERSIONINFOA sInfo;
  29786. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  29787. osGetVersionExA(&sInfo);
  29788. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  29789. }
  29790. return sqlite3_os_type==2;
  29791. }
  29792. #endif
  29793. #ifdef SQLITE_WIN32_MALLOC
  29794. /*
  29795. ** Allocate nBytes of memory.
  29796. */
  29797. static void *winMemMalloc(int nBytes){
  29798. HANDLE hHeap;
  29799. void *p;
  29800. winMemAssertMagic();
  29801. hHeap = winMemGetHeap();
  29802. assert( hHeap!=0 );
  29803. assert( hHeap!=INVALID_HANDLE_VALUE );
  29804. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29805. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29806. #endif
  29807. assert( nBytes>=0 );
  29808. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  29809. if( !p ){
  29810. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
  29811. nBytes, osGetLastError(), (void*)hHeap);
  29812. }
  29813. return p;
  29814. }
  29815. /*
  29816. ** Free memory.
  29817. */
  29818. static void winMemFree(void *pPrior){
  29819. HANDLE hHeap;
  29820. winMemAssertMagic();
  29821. hHeap = winMemGetHeap();
  29822. assert( hHeap!=0 );
  29823. assert( hHeap!=INVALID_HANDLE_VALUE );
  29824. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29825. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  29826. #endif
  29827. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  29828. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  29829. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
  29830. pPrior, osGetLastError(), (void*)hHeap);
  29831. }
  29832. }
  29833. /*
  29834. ** Change the size of an existing memory allocation
  29835. */
  29836. static void *winMemRealloc(void *pPrior, int nBytes){
  29837. HANDLE hHeap;
  29838. void *p;
  29839. winMemAssertMagic();
  29840. hHeap = winMemGetHeap();
  29841. assert( hHeap!=0 );
  29842. assert( hHeap!=INVALID_HANDLE_VALUE );
  29843. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29844. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  29845. #endif
  29846. assert( nBytes>=0 );
  29847. if( !pPrior ){
  29848. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  29849. }else{
  29850. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  29851. }
  29852. if( !p ){
  29853. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
  29854. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  29855. (void*)hHeap);
  29856. }
  29857. return p;
  29858. }
  29859. /*
  29860. ** Return the size of an outstanding allocation, in bytes.
  29861. */
  29862. static int winMemSize(void *p){
  29863. HANDLE hHeap;
  29864. SIZE_T n;
  29865. winMemAssertMagic();
  29866. hHeap = winMemGetHeap();
  29867. assert( hHeap!=0 );
  29868. assert( hHeap!=INVALID_HANDLE_VALUE );
  29869. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29870. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29871. #endif
  29872. if( !p ) return 0;
  29873. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  29874. if( n==(SIZE_T)-1 ){
  29875. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
  29876. p, osGetLastError(), (void*)hHeap);
  29877. return 0;
  29878. }
  29879. return (int)n;
  29880. }
  29881. /*
  29882. ** Round up a request size to the next valid allocation size.
  29883. */
  29884. static int winMemRoundup(int n){
  29885. return n;
  29886. }
  29887. /*
  29888. ** Initialize this module.
  29889. */
  29890. static int winMemInit(void *pAppData){
  29891. winMemData *pWinMemData = (winMemData *)pAppData;
  29892. if( !pWinMemData ) return SQLITE_ERROR;
  29893. assert( pWinMemData->magic==WINMEM_MAGIC );
  29894. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  29895. if( !pWinMemData->hHeap ){
  29896. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  29897. SQLITE_WIN32_HEAP_INIT_SIZE,
  29898. SQLITE_WIN32_HEAP_MAX_SIZE);
  29899. if( !pWinMemData->hHeap ){
  29900. sqlite3_log(SQLITE_NOMEM,
  29901. "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
  29902. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  29903. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  29904. return SQLITE_NOMEM;
  29905. }
  29906. pWinMemData->bOwned = TRUE;
  29907. assert( pWinMemData->bOwned );
  29908. }
  29909. #else
  29910. pWinMemData->hHeap = osGetProcessHeap();
  29911. if( !pWinMemData->hHeap ){
  29912. sqlite3_log(SQLITE_NOMEM,
  29913. "failed to GetProcessHeap (%d)", osGetLastError());
  29914. return SQLITE_NOMEM;
  29915. }
  29916. pWinMemData->bOwned = FALSE;
  29917. assert( !pWinMemData->bOwned );
  29918. #endif
  29919. assert( pWinMemData->hHeap!=0 );
  29920. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  29921. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29922. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29923. #endif
  29924. return SQLITE_OK;
  29925. }
  29926. /*
  29927. ** Deinitialize this module.
  29928. */
  29929. static void winMemShutdown(void *pAppData){
  29930. winMemData *pWinMemData = (winMemData *)pAppData;
  29931. if( !pWinMemData ) return;
  29932. if( pWinMemData->hHeap ){
  29933. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  29934. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29935. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29936. #endif
  29937. if( pWinMemData->bOwned ){
  29938. if( !osHeapDestroy(pWinMemData->hHeap) ){
  29939. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
  29940. osGetLastError(), (void*)pWinMemData->hHeap);
  29941. }
  29942. pWinMemData->bOwned = FALSE;
  29943. }
  29944. pWinMemData->hHeap = NULL;
  29945. }
  29946. }
  29947. /*
  29948. ** Populate the low-level memory allocation function pointers in
  29949. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  29950. ** arguments specify the block of memory to manage.
  29951. **
  29952. ** This routine is only called by sqlite3_config(), and therefore
  29953. ** is not required to be threadsafe (it is not).
  29954. */
  29955. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  29956. static const sqlite3_mem_methods winMemMethods = {
  29957. winMemMalloc,
  29958. winMemFree,
  29959. winMemRealloc,
  29960. winMemSize,
  29961. winMemRoundup,
  29962. winMemInit,
  29963. winMemShutdown,
  29964. &win_mem_data
  29965. };
  29966. return &winMemMethods;
  29967. }
  29968. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  29969. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  29970. }
  29971. #endif /* SQLITE_WIN32_MALLOC */
  29972. /*
  29973. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  29974. **
  29975. ** Space to hold the returned string is obtained from malloc.
  29976. */
  29977. static LPWSTR utf8ToUnicode(const char *zFilename){
  29978. int nChar;
  29979. LPWSTR zWideFilename;
  29980. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  29981. if( nChar==0 ){
  29982. return 0;
  29983. }
  29984. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  29985. if( zWideFilename==0 ){
  29986. return 0;
  29987. }
  29988. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  29989. nChar);
  29990. if( nChar==0 ){
  29991. sqlite3_free(zWideFilename);
  29992. zWideFilename = 0;
  29993. }
  29994. return zWideFilename;
  29995. }
  29996. /*
  29997. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  29998. ** obtained from sqlite3_malloc().
  29999. */
  30000. static char *unicodeToUtf8(LPCWSTR zWideFilename){
  30001. int nByte;
  30002. char *zFilename;
  30003. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  30004. if( nByte == 0 ){
  30005. return 0;
  30006. }
  30007. zFilename = sqlite3MallocZero( nByte );
  30008. if( zFilename==0 ){
  30009. return 0;
  30010. }
  30011. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  30012. 0, 0);
  30013. if( nByte == 0 ){
  30014. sqlite3_free(zFilename);
  30015. zFilename = 0;
  30016. }
  30017. return zFilename;
  30018. }
  30019. /*
  30020. ** Convert an ANSI string to Microsoft Unicode, based on the
  30021. ** current codepage settings for file apis.
  30022. **
  30023. ** Space to hold the returned string is obtained
  30024. ** from sqlite3_malloc.
  30025. */
  30026. static LPWSTR mbcsToUnicode(const char *zFilename){
  30027. int nByte;
  30028. LPWSTR zMbcsFilename;
  30029. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30030. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  30031. 0)*sizeof(WCHAR);
  30032. if( nByte==0 ){
  30033. return 0;
  30034. }
  30035. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  30036. if( zMbcsFilename==0 ){
  30037. return 0;
  30038. }
  30039. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  30040. nByte);
  30041. if( nByte==0 ){
  30042. sqlite3_free(zMbcsFilename);
  30043. zMbcsFilename = 0;
  30044. }
  30045. return zMbcsFilename;
  30046. }
  30047. /*
  30048. ** Convert Microsoft Unicode to multi-byte character string, based on the
  30049. ** user's ANSI codepage.
  30050. **
  30051. ** Space to hold the returned string is obtained from
  30052. ** sqlite3_malloc().
  30053. */
  30054. static char *unicodeToMbcs(LPCWSTR zWideFilename){
  30055. int nByte;
  30056. char *zFilename;
  30057. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30058. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  30059. if( nByte == 0 ){
  30060. return 0;
  30061. }
  30062. zFilename = sqlite3MallocZero( nByte );
  30063. if( zFilename==0 ){
  30064. return 0;
  30065. }
  30066. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  30067. nByte, 0, 0);
  30068. if( nByte == 0 ){
  30069. sqlite3_free(zFilename);
  30070. zFilename = 0;
  30071. }
  30072. return zFilename;
  30073. }
  30074. /*
  30075. ** Convert multibyte character string to UTF-8. Space to hold the
  30076. ** returned string is obtained from sqlite3_malloc().
  30077. */
  30078. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  30079. char *zFilenameUtf8;
  30080. LPWSTR zTmpWide;
  30081. zTmpWide = mbcsToUnicode(zFilename);
  30082. if( zTmpWide==0 ){
  30083. return 0;
  30084. }
  30085. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  30086. sqlite3_free(zTmpWide);
  30087. return zFilenameUtf8;
  30088. }
  30089. /*
  30090. ** Convert UTF-8 to multibyte character string. Space to hold the
  30091. ** returned string is obtained from sqlite3_malloc().
  30092. */
  30093. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  30094. char *zFilenameMbcs;
  30095. LPWSTR zTmpWide;
  30096. zTmpWide = utf8ToUnicode(zFilename);
  30097. if( zTmpWide==0 ){
  30098. return 0;
  30099. }
  30100. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  30101. sqlite3_free(zTmpWide);
  30102. return zFilenameMbcs;
  30103. }
  30104. /*
  30105. ** This function sets the data directory or the temporary directory based on
  30106. ** the provided arguments. The type argument must be 1 in order to set the
  30107. ** data directory or 2 in order to set the temporary directory. The zValue
  30108. ** argument is the name of the directory to use. The return value will be
  30109. ** SQLITE_OK if successful.
  30110. */
  30111. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  30112. char **ppDirectory = 0;
  30113. #ifndef SQLITE_OMIT_AUTOINIT
  30114. int rc = sqlite3_initialize();
  30115. if( rc ) return rc;
  30116. #endif
  30117. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  30118. ppDirectory = &sqlite3_data_directory;
  30119. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  30120. ppDirectory = &sqlite3_temp_directory;
  30121. }
  30122. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30123. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30124. );
  30125. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  30126. if( ppDirectory ){
  30127. char *zValueUtf8 = 0;
  30128. if( zValue && zValue[0] ){
  30129. zValueUtf8 = unicodeToUtf8(zValue);
  30130. if ( zValueUtf8==0 ){
  30131. return SQLITE_NOMEM;
  30132. }
  30133. }
  30134. sqlite3_free(*ppDirectory);
  30135. *ppDirectory = zValueUtf8;
  30136. return SQLITE_OK;
  30137. }
  30138. return SQLITE_ERROR;
  30139. }
  30140. /*
  30141. ** The return value of getLastErrorMsg
  30142. ** is zero if the error message fits in the buffer, or non-zero
  30143. ** otherwise (if the message was truncated).
  30144. */
  30145. static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  30146. /* FormatMessage returns 0 on failure. Otherwise it
  30147. ** returns the number of TCHARs written to the output
  30148. ** buffer, excluding the terminating null char.
  30149. */
  30150. DWORD dwLen = 0;
  30151. char *zOut = 0;
  30152. if( isNT() ){
  30153. #if SQLITE_OS_WINRT
  30154. WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
  30155. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  30156. FORMAT_MESSAGE_IGNORE_INSERTS,
  30157. NULL,
  30158. lastErrno,
  30159. 0,
  30160. zTempWide,
  30161. MAX_PATH,
  30162. 0);
  30163. #else
  30164. LPWSTR zTempWide = NULL;
  30165. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30166. FORMAT_MESSAGE_FROM_SYSTEM |
  30167. FORMAT_MESSAGE_IGNORE_INSERTS,
  30168. NULL,
  30169. lastErrno,
  30170. 0,
  30171. (LPWSTR) &zTempWide,
  30172. 0,
  30173. 0);
  30174. #endif
  30175. if( dwLen > 0 ){
  30176. /* allocate a buffer and convert to UTF8 */
  30177. sqlite3BeginBenignMalloc();
  30178. zOut = unicodeToUtf8(zTempWide);
  30179. sqlite3EndBenignMalloc();
  30180. #if !SQLITE_OS_WINRT
  30181. /* free the system buffer allocated by FormatMessage */
  30182. osLocalFree(zTempWide);
  30183. #endif
  30184. }
  30185. }
  30186. #ifdef SQLITE_WIN32_HAS_ANSI
  30187. else{
  30188. char *zTemp = NULL;
  30189. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30190. FORMAT_MESSAGE_FROM_SYSTEM |
  30191. FORMAT_MESSAGE_IGNORE_INSERTS,
  30192. NULL,
  30193. lastErrno,
  30194. 0,
  30195. (LPSTR) &zTemp,
  30196. 0,
  30197. 0);
  30198. if( dwLen > 0 ){
  30199. /* allocate a buffer and convert to UTF8 */
  30200. sqlite3BeginBenignMalloc();
  30201. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  30202. sqlite3EndBenignMalloc();
  30203. /* free the system buffer allocated by FormatMessage */
  30204. osLocalFree(zTemp);
  30205. }
  30206. }
  30207. #endif
  30208. if( 0 == dwLen ){
  30209. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  30210. }else{
  30211. /* copy a maximum of nBuf chars to output buffer */
  30212. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  30213. /* free the UTF8 buffer */
  30214. sqlite3_free(zOut);
  30215. }
  30216. return 0;
  30217. }
  30218. /*
  30219. **
  30220. ** This function - winLogErrorAtLine() - is only ever called via the macro
  30221. ** winLogError().
  30222. **
  30223. ** This routine is invoked after an error occurs in an OS function.
  30224. ** It logs a message using sqlite3_log() containing the current value of
  30225. ** error code and, if possible, the human-readable equivalent from
  30226. ** FormatMessage.
  30227. **
  30228. ** The first argument passed to the macro should be the error code that
  30229. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  30230. ** The two subsequent arguments should be the name of the OS function that
  30231. ** failed and the associated file-system path, if any.
  30232. */
  30233. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  30234. static int winLogErrorAtLine(
  30235. int errcode, /* SQLite error code */
  30236. DWORD lastErrno, /* Win32 last error */
  30237. const char *zFunc, /* Name of OS function that failed */
  30238. const char *zPath, /* File path associated with error */
  30239. int iLine /* Source line number where error occurred */
  30240. ){
  30241. char zMsg[500]; /* Human readable error text */
  30242. int i; /* Loop counter */
  30243. zMsg[0] = 0;
  30244. getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  30245. assert( errcode!=SQLITE_OK );
  30246. if( zPath==0 ) zPath = "";
  30247. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  30248. zMsg[i] = 0;
  30249. sqlite3_log(errcode,
  30250. "os_win.c:%d: (%lu) %s(%s) - %s",
  30251. iLine, lastErrno, zFunc, zPath, zMsg
  30252. );
  30253. return errcode;
  30254. }
  30255. /*
  30256. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  30257. ** will be retried following a locking error - probably caused by
  30258. ** antivirus software. Also the initial delay before the first retry.
  30259. ** The delay increases linearly with each retry.
  30260. */
  30261. #ifndef SQLITE_WIN32_IOERR_RETRY
  30262. # define SQLITE_WIN32_IOERR_RETRY 10
  30263. #endif
  30264. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  30265. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  30266. #endif
  30267. static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  30268. static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  30269. /*
  30270. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  30271. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  30272. ** to give up with an error.
  30273. */
  30274. static int retryIoerr(int *pnRetry, DWORD *pError){
  30275. DWORD e = osGetLastError();
  30276. if( *pnRetry>=win32IoerrRetry ){
  30277. if( pError ){
  30278. *pError = e;
  30279. }
  30280. return 0;
  30281. }
  30282. if( e==ERROR_ACCESS_DENIED ||
  30283. e==ERROR_LOCK_VIOLATION ||
  30284. e==ERROR_SHARING_VIOLATION ){
  30285. sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
  30286. ++*pnRetry;
  30287. return 1;
  30288. }
  30289. if( pError ){
  30290. *pError = e;
  30291. }
  30292. return 0;
  30293. }
  30294. /*
  30295. ** Log a I/O error retry episode.
  30296. */
  30297. static void logIoerr(int nRetry){
  30298. if( nRetry ){
  30299. sqlite3_log(SQLITE_IOERR,
  30300. "delayed %dms for lock/sharing conflict",
  30301. win32IoerrRetryDelay*nRetry*(nRetry+1)/2
  30302. );
  30303. }
  30304. }
  30305. #if SQLITE_OS_WINCE
  30306. /*************************************************************************
  30307. ** This section contains code for WinCE only.
  30308. */
  30309. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  30310. /*
  30311. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  30312. ** create a substitute.
  30313. */
  30314. /* #include <time.h> */
  30315. struct tm *__cdecl localtime(const time_t *t)
  30316. {
  30317. static struct tm y;
  30318. FILETIME uTm, lTm;
  30319. SYSTEMTIME pTm;
  30320. sqlite3_int64 t64;
  30321. t64 = *t;
  30322. t64 = (t64 + 11644473600)*10000000;
  30323. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  30324. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  30325. osFileTimeToLocalFileTime(&uTm,&lTm);
  30326. osFileTimeToSystemTime(&lTm,&pTm);
  30327. y.tm_year = pTm.wYear - 1900;
  30328. y.tm_mon = pTm.wMonth - 1;
  30329. y.tm_wday = pTm.wDayOfWeek;
  30330. y.tm_mday = pTm.wDay;
  30331. y.tm_hour = pTm.wHour;
  30332. y.tm_min = pTm.wMinute;
  30333. y.tm_sec = pTm.wSecond;
  30334. return &y;
  30335. }
  30336. #endif
  30337. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  30338. /*
  30339. ** Acquire a lock on the handle h
  30340. */
  30341. static void winceMutexAcquire(HANDLE h){
  30342. DWORD dwErr;
  30343. do {
  30344. dwErr = osWaitForSingleObject(h, INFINITE);
  30345. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  30346. }
  30347. /*
  30348. ** Release a lock acquired by winceMutexAcquire()
  30349. */
  30350. #define winceMutexRelease(h) ReleaseMutex(h)
  30351. /*
  30352. ** Create the mutex and shared memory used for locking in the file
  30353. ** descriptor pFile
  30354. */
  30355. static int winceCreateLock(const char *zFilename, winFile *pFile){
  30356. LPWSTR zTok;
  30357. LPWSTR zName;
  30358. DWORD lastErrno;
  30359. BOOL bLogged = FALSE;
  30360. BOOL bInit = TRUE;
  30361. zName = utf8ToUnicode(zFilename);
  30362. if( zName==0 ){
  30363. /* out of memory */
  30364. return SQLITE_IOERR_NOMEM;
  30365. }
  30366. /* Initialize the local lockdata */
  30367. memset(&pFile->local, 0, sizeof(pFile->local));
  30368. /* Replace the backslashes from the filename and lowercase it
  30369. ** to derive a mutex name. */
  30370. zTok = osCharLowerW(zName);
  30371. for (;*zTok;zTok++){
  30372. if (*zTok == '\\') *zTok = '_';
  30373. }
  30374. /* Create/open the named mutex */
  30375. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  30376. if (!pFile->hMutex){
  30377. pFile->lastErrno = osGetLastError();
  30378. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30379. "winceCreateLock1", zFilename);
  30380. sqlite3_free(zName);
  30381. return SQLITE_IOERR;
  30382. }
  30383. /* Acquire the mutex before continuing */
  30384. winceMutexAcquire(pFile->hMutex);
  30385. /* Since the names of named mutexes, semaphores, file mappings etc are
  30386. ** case-sensitive, take advantage of that by uppercasing the mutex name
  30387. ** and using that as the shared filemapping name.
  30388. */
  30389. osCharUpperW(zName);
  30390. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  30391. PAGE_READWRITE, 0, sizeof(winceLock),
  30392. zName);
  30393. /* Set a flag that indicates we're the first to create the memory so it
  30394. ** must be zero-initialized */
  30395. lastErrno = osGetLastError();
  30396. if (lastErrno == ERROR_ALREADY_EXISTS){
  30397. bInit = FALSE;
  30398. }
  30399. sqlite3_free(zName);
  30400. /* If we succeeded in making the shared memory handle, map it. */
  30401. if( pFile->hShared ){
  30402. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  30403. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  30404. /* If mapping failed, close the shared memory handle and erase it */
  30405. if( !pFile->shared ){
  30406. pFile->lastErrno = osGetLastError();
  30407. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30408. "winceCreateLock2", zFilename);
  30409. bLogged = TRUE;
  30410. osCloseHandle(pFile->hShared);
  30411. pFile->hShared = NULL;
  30412. }
  30413. }
  30414. /* If shared memory could not be created, then close the mutex and fail */
  30415. if( pFile->hShared==NULL ){
  30416. if( !bLogged ){
  30417. pFile->lastErrno = lastErrno;
  30418. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30419. "winceCreateLock3", zFilename);
  30420. bLogged = TRUE;
  30421. }
  30422. winceMutexRelease(pFile->hMutex);
  30423. osCloseHandle(pFile->hMutex);
  30424. pFile->hMutex = NULL;
  30425. return SQLITE_IOERR;
  30426. }
  30427. /* Initialize the shared memory if we're supposed to */
  30428. if( bInit ){
  30429. memset(pFile->shared, 0, sizeof(winceLock));
  30430. }
  30431. winceMutexRelease(pFile->hMutex);
  30432. return SQLITE_OK;
  30433. }
  30434. /*
  30435. ** Destroy the part of winFile that deals with wince locks
  30436. */
  30437. static void winceDestroyLock(winFile *pFile){
  30438. if (pFile->hMutex){
  30439. /* Acquire the mutex */
  30440. winceMutexAcquire(pFile->hMutex);
  30441. /* The following blocks should probably assert in debug mode, but they
  30442. are to cleanup in case any locks remained open */
  30443. if (pFile->local.nReaders){
  30444. pFile->shared->nReaders --;
  30445. }
  30446. if (pFile->local.bReserved){
  30447. pFile->shared->bReserved = FALSE;
  30448. }
  30449. if (pFile->local.bPending){
  30450. pFile->shared->bPending = FALSE;
  30451. }
  30452. if (pFile->local.bExclusive){
  30453. pFile->shared->bExclusive = FALSE;
  30454. }
  30455. /* De-reference and close our copy of the shared memory handle */
  30456. osUnmapViewOfFile(pFile->shared);
  30457. osCloseHandle(pFile->hShared);
  30458. /* Done with the mutex */
  30459. winceMutexRelease(pFile->hMutex);
  30460. osCloseHandle(pFile->hMutex);
  30461. pFile->hMutex = NULL;
  30462. }
  30463. }
  30464. /*
  30465. ** An implementation of the LockFile() API of Windows for CE
  30466. */
  30467. static BOOL winceLockFile(
  30468. LPHANDLE phFile,
  30469. DWORD dwFileOffsetLow,
  30470. DWORD dwFileOffsetHigh,
  30471. DWORD nNumberOfBytesToLockLow,
  30472. DWORD nNumberOfBytesToLockHigh
  30473. ){
  30474. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  30475. BOOL bReturn = FALSE;
  30476. UNUSED_PARAMETER(dwFileOffsetHigh);
  30477. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  30478. if (!pFile->hMutex) return TRUE;
  30479. winceMutexAcquire(pFile->hMutex);
  30480. /* Wanting an exclusive lock? */
  30481. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  30482. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  30483. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  30484. pFile->shared->bExclusive = TRUE;
  30485. pFile->local.bExclusive = TRUE;
  30486. bReturn = TRUE;
  30487. }
  30488. }
  30489. /* Want a read-only lock? */
  30490. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  30491. nNumberOfBytesToLockLow == 1){
  30492. if (pFile->shared->bExclusive == 0){
  30493. pFile->local.nReaders ++;
  30494. if (pFile->local.nReaders == 1){
  30495. pFile->shared->nReaders ++;
  30496. }
  30497. bReturn = TRUE;
  30498. }
  30499. }
  30500. /* Want a pending lock? */
  30501. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  30502. && nNumberOfBytesToLockLow == 1){
  30503. /* If no pending lock has been acquired, then acquire it */
  30504. if (pFile->shared->bPending == 0) {
  30505. pFile->shared->bPending = TRUE;
  30506. pFile->local.bPending = TRUE;
  30507. bReturn = TRUE;
  30508. }
  30509. }
  30510. /* Want a reserved lock? */
  30511. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  30512. && nNumberOfBytesToLockLow == 1){
  30513. if (pFile->shared->bReserved == 0) {
  30514. pFile->shared->bReserved = TRUE;
  30515. pFile->local.bReserved = TRUE;
  30516. bReturn = TRUE;
  30517. }
  30518. }
  30519. winceMutexRelease(pFile->hMutex);
  30520. return bReturn;
  30521. }
  30522. /*
  30523. ** An implementation of the UnlockFile API of Windows for CE
  30524. */
  30525. static BOOL winceUnlockFile(
  30526. LPHANDLE phFile,
  30527. DWORD dwFileOffsetLow,
  30528. DWORD dwFileOffsetHigh,
  30529. DWORD nNumberOfBytesToUnlockLow,
  30530. DWORD nNumberOfBytesToUnlockHigh
  30531. ){
  30532. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  30533. BOOL bReturn = FALSE;
  30534. UNUSED_PARAMETER(dwFileOffsetHigh);
  30535. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  30536. if (!pFile->hMutex) return TRUE;
  30537. winceMutexAcquire(pFile->hMutex);
  30538. /* Releasing a reader lock or an exclusive lock */
  30539. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  30540. /* Did we have an exclusive lock? */
  30541. if (pFile->local.bExclusive){
  30542. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  30543. pFile->local.bExclusive = FALSE;
  30544. pFile->shared->bExclusive = FALSE;
  30545. bReturn = TRUE;
  30546. }
  30547. /* Did we just have a reader lock? */
  30548. else if (pFile->local.nReaders){
  30549. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  30550. || nNumberOfBytesToUnlockLow == 1);
  30551. pFile->local.nReaders --;
  30552. if (pFile->local.nReaders == 0)
  30553. {
  30554. pFile->shared->nReaders --;
  30555. }
  30556. bReturn = TRUE;
  30557. }
  30558. }
  30559. /* Releasing a pending lock */
  30560. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  30561. && nNumberOfBytesToUnlockLow == 1){
  30562. if (pFile->local.bPending){
  30563. pFile->local.bPending = FALSE;
  30564. pFile->shared->bPending = FALSE;
  30565. bReturn = TRUE;
  30566. }
  30567. }
  30568. /* Releasing a reserved lock */
  30569. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  30570. && nNumberOfBytesToUnlockLow == 1){
  30571. if (pFile->local.bReserved) {
  30572. pFile->local.bReserved = FALSE;
  30573. pFile->shared->bReserved = FALSE;
  30574. bReturn = TRUE;
  30575. }
  30576. }
  30577. winceMutexRelease(pFile->hMutex);
  30578. return bReturn;
  30579. }
  30580. /*
  30581. ** End of the special code for wince
  30582. *****************************************************************************/
  30583. #endif /* SQLITE_OS_WINCE */
  30584. /*
  30585. ** Lock a file region.
  30586. */
  30587. static BOOL winLockFile(
  30588. LPHANDLE phFile,
  30589. DWORD flags,
  30590. DWORD offsetLow,
  30591. DWORD offsetHigh,
  30592. DWORD numBytesLow,
  30593. DWORD numBytesHigh
  30594. ){
  30595. #if SQLITE_OS_WINCE
  30596. /*
  30597. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30598. ** API LockFile.
  30599. */
  30600. return winceLockFile(phFile, offsetLow, offsetHigh,
  30601. numBytesLow, numBytesHigh);
  30602. #else
  30603. if( isNT() ){
  30604. OVERLAPPED ovlp;
  30605. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30606. ovlp.Offset = offsetLow;
  30607. ovlp.OffsetHigh = offsetHigh;
  30608. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  30609. }else{
  30610. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30611. numBytesHigh);
  30612. }
  30613. #endif
  30614. }
  30615. /*
  30616. ** Unlock a file region.
  30617. */
  30618. static BOOL winUnlockFile(
  30619. LPHANDLE phFile,
  30620. DWORD offsetLow,
  30621. DWORD offsetHigh,
  30622. DWORD numBytesLow,
  30623. DWORD numBytesHigh
  30624. ){
  30625. #if SQLITE_OS_WINCE
  30626. /*
  30627. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30628. ** API UnlockFile.
  30629. */
  30630. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  30631. numBytesLow, numBytesHigh);
  30632. #else
  30633. if( isNT() ){
  30634. OVERLAPPED ovlp;
  30635. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30636. ovlp.Offset = offsetLow;
  30637. ovlp.OffsetHigh = offsetHigh;
  30638. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  30639. }else{
  30640. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30641. numBytesHigh);
  30642. }
  30643. #endif
  30644. }
  30645. /*****************************************************************************
  30646. ** The next group of routines implement the I/O methods specified
  30647. ** by the sqlite3_io_methods object.
  30648. ******************************************************************************/
  30649. /*
  30650. ** Some Microsoft compilers lack this definition.
  30651. */
  30652. #ifndef INVALID_SET_FILE_POINTER
  30653. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  30654. #endif
  30655. /*
  30656. ** Move the current position of the file handle passed as the first
  30657. ** argument to offset iOffset within the file. If successful, return 0.
  30658. ** Otherwise, set pFile->lastErrno and return non-zero.
  30659. */
  30660. static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
  30661. #if !SQLITE_OS_WINRT
  30662. LONG upperBits; /* Most sig. 32 bits of new offset */
  30663. LONG lowerBits; /* Least sig. 32 bits of new offset */
  30664. DWORD dwRet; /* Value returned by SetFilePointer() */
  30665. DWORD lastErrno; /* Value returned by GetLastError() */
  30666. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  30667. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  30668. lowerBits = (LONG)(iOffset & 0xffffffff);
  30669. /* API oddity: If successful, SetFilePointer() returns a dword
  30670. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  30671. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  30672. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  30673. ** whether an error has actually occurred, it is also necessary to call
  30674. ** GetLastError().
  30675. */
  30676. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  30677. if( (dwRet==INVALID_SET_FILE_POINTER
  30678. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  30679. pFile->lastErrno = lastErrno;
  30680. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30681. "seekWinFile", pFile->zPath);
  30682. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  30683. return 1;
  30684. }
  30685. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  30686. return 0;
  30687. #else
  30688. /*
  30689. ** Same as above, except that this implementation works for WinRT.
  30690. */
  30691. LARGE_INTEGER x; /* The new offset */
  30692. BOOL bRet; /* Value returned by SetFilePointerEx() */
  30693. x.QuadPart = iOffset;
  30694. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  30695. if(!bRet){
  30696. pFile->lastErrno = osGetLastError();
  30697. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30698. "seekWinFile", pFile->zPath);
  30699. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  30700. return 1;
  30701. }
  30702. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  30703. return 0;
  30704. #endif
  30705. }
  30706. #if SQLITE_MAX_MMAP_SIZE>0
  30707. /* Forward references to VFS methods */
  30708. static int winUnmapfile(winFile*);
  30709. #endif
  30710. /*
  30711. ** Close a file.
  30712. **
  30713. ** It is reported that an attempt to close a handle might sometimes
  30714. ** fail. This is a very unreasonable result, but Windows is notorious
  30715. ** for being unreasonable so I do not doubt that it might happen. If
  30716. ** the close fails, we pause for 100 milliseconds and try again. As
  30717. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  30718. ** giving up and returning an error.
  30719. */
  30720. #define MX_CLOSE_ATTEMPT 3
  30721. static int winClose(sqlite3_file *id){
  30722. int rc, cnt = 0;
  30723. winFile *pFile = (winFile*)id;
  30724. assert( id!=0 );
  30725. #ifndef SQLITE_OMIT_WAL
  30726. assert( pFile->pShm==0 );
  30727. #endif
  30728. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  30729. OSTRACE(("CLOSE file=%p\n", pFile->h));
  30730. #if SQLITE_MAX_MMAP_SIZE>0
  30731. rc = winUnmapfile(pFile);
  30732. if( rc!=SQLITE_OK ) return rc;
  30733. #endif
  30734. do{
  30735. rc = osCloseHandle(pFile->h);
  30736. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  30737. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  30738. #if SQLITE_OS_WINCE
  30739. #define WINCE_DELETION_ATTEMPTS 3
  30740. winceDestroyLock(pFile);
  30741. if( pFile->zDeleteOnClose ){
  30742. int cnt = 0;
  30743. while(
  30744. osDeleteFileW(pFile->zDeleteOnClose)==0
  30745. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  30746. && cnt++ < WINCE_DELETION_ATTEMPTS
  30747. ){
  30748. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  30749. }
  30750. sqlite3_free(pFile->zDeleteOnClose);
  30751. }
  30752. #endif
  30753. if( rc ){
  30754. pFile->h = NULL;
  30755. }
  30756. OpenCounter(-1);
  30757. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  30758. return rc ? SQLITE_OK
  30759. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  30760. "winClose", pFile->zPath);
  30761. }
  30762. /*
  30763. ** Read data from a file into a buffer. Return SQLITE_OK if all
  30764. ** bytes were read successfully and SQLITE_IOERR if anything goes
  30765. ** wrong.
  30766. */
  30767. static int winRead(
  30768. sqlite3_file *id, /* File to read from */
  30769. void *pBuf, /* Write content into this buffer */
  30770. int amt, /* Number of bytes to read */
  30771. sqlite3_int64 offset /* Begin reading at this offset */
  30772. ){
  30773. #if !SQLITE_OS_WINCE
  30774. OVERLAPPED overlapped; /* The offset for ReadFile. */
  30775. #endif
  30776. winFile *pFile = (winFile*)id; /* file handle */
  30777. DWORD nRead; /* Number of bytes actually read from file */
  30778. int nRetry = 0; /* Number of retrys */
  30779. assert( id!=0 );
  30780. assert( amt>0 );
  30781. assert( offset>=0 );
  30782. SimulateIOError(return SQLITE_IOERR_READ);
  30783. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  30784. pFile->h, pBuf, amt, offset, pFile->locktype));
  30785. #if SQLITE_MAX_MMAP_SIZE>0
  30786. /* Deal with as much of this read request as possible by transfering
  30787. ** data from the memory mapping using memcpy(). */
  30788. if( offset<pFile->mmapSize ){
  30789. if( offset+amt <= pFile->mmapSize ){
  30790. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  30791. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  30792. return SQLITE_OK;
  30793. }else{
  30794. int nCopy = (int)(pFile->mmapSize - offset);
  30795. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  30796. pBuf = &((u8 *)pBuf)[nCopy];
  30797. amt -= nCopy;
  30798. offset += nCopy;
  30799. }
  30800. }
  30801. #endif
  30802. #if SQLITE_OS_WINCE
  30803. if( seekWinFile(pFile, offset) ){
  30804. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  30805. return SQLITE_FULL;
  30806. }
  30807. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  30808. #else
  30809. memset(&overlapped, 0, sizeof(OVERLAPPED));
  30810. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30811. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30812. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  30813. osGetLastError()!=ERROR_HANDLE_EOF ){
  30814. #endif
  30815. DWORD lastErrno;
  30816. if( retryIoerr(&nRetry, &lastErrno) ) continue;
  30817. pFile->lastErrno = lastErrno;
  30818. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  30819. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  30820. "winRead", pFile->zPath);
  30821. }
  30822. logIoerr(nRetry);
  30823. if( nRead<(DWORD)amt ){
  30824. /* Unread parts of the buffer must be zero-filled */
  30825. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  30826. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  30827. return SQLITE_IOERR_SHORT_READ;
  30828. }
  30829. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  30830. return SQLITE_OK;
  30831. }
  30832. /*
  30833. ** Write data from a buffer into a file. Return SQLITE_OK on success
  30834. ** or some other error code on failure.
  30835. */
  30836. static int winWrite(
  30837. sqlite3_file *id, /* File to write into */
  30838. const void *pBuf, /* The bytes to be written */
  30839. int amt, /* Number of bytes to write */
  30840. sqlite3_int64 offset /* Offset into the file to begin writing at */
  30841. ){
  30842. int rc = 0; /* True if error has occurred, else false */
  30843. winFile *pFile = (winFile*)id; /* File handle */
  30844. int nRetry = 0; /* Number of retries */
  30845. assert( amt>0 );
  30846. assert( pFile );
  30847. SimulateIOError(return SQLITE_IOERR_WRITE);
  30848. SimulateDiskfullError(return SQLITE_FULL);
  30849. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  30850. pFile->h, pBuf, amt, offset, pFile->locktype));
  30851. #if SQLITE_MAX_MMAP_SIZE>0
  30852. /* Deal with as much of this write request as possible by transfering
  30853. ** data from the memory mapping using memcpy(). */
  30854. if( offset<pFile->mmapSize ){
  30855. if( offset+amt <= pFile->mmapSize ){
  30856. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  30857. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  30858. return SQLITE_OK;
  30859. }else{
  30860. int nCopy = (int)(pFile->mmapSize - offset);
  30861. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  30862. pBuf = &((u8 *)pBuf)[nCopy];
  30863. amt -= nCopy;
  30864. offset += nCopy;
  30865. }
  30866. }
  30867. #endif
  30868. #if SQLITE_OS_WINCE
  30869. rc = seekWinFile(pFile, offset);
  30870. if( rc==0 ){
  30871. #else
  30872. {
  30873. #endif
  30874. #if !SQLITE_OS_WINCE
  30875. OVERLAPPED overlapped; /* The offset for WriteFile. */
  30876. #endif
  30877. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  30878. int nRem = amt; /* Number of bytes yet to be written */
  30879. DWORD nWrite; /* Bytes written by each WriteFile() call */
  30880. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  30881. #if !SQLITE_OS_WINCE
  30882. memset(&overlapped, 0, sizeof(OVERLAPPED));
  30883. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30884. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30885. #endif
  30886. while( nRem>0 ){
  30887. #if SQLITE_OS_WINCE
  30888. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  30889. #else
  30890. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  30891. #endif
  30892. if( retryIoerr(&nRetry, &lastErrno) ) continue;
  30893. break;
  30894. }
  30895. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  30896. if( nWrite==0 || nWrite>(DWORD)nRem ){
  30897. lastErrno = osGetLastError();
  30898. break;
  30899. }
  30900. #if !SQLITE_OS_WINCE
  30901. offset += nWrite;
  30902. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30903. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30904. #endif
  30905. aRem += nWrite;
  30906. nRem -= nWrite;
  30907. }
  30908. if( nRem>0 ){
  30909. pFile->lastErrno = lastErrno;
  30910. rc = 1;
  30911. }
  30912. }
  30913. if( rc ){
  30914. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  30915. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  30916. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  30917. return SQLITE_FULL;
  30918. }
  30919. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  30920. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  30921. "winWrite", pFile->zPath);
  30922. }else{
  30923. logIoerr(nRetry);
  30924. }
  30925. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  30926. return SQLITE_OK;
  30927. }
  30928. /*
  30929. ** Truncate an open file to a specified size
  30930. */
  30931. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  30932. winFile *pFile = (winFile*)id; /* File handle object */
  30933. int rc = SQLITE_OK; /* Return code for this function */
  30934. DWORD lastErrno;
  30935. assert( pFile );
  30936. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  30937. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  30938. pFile->h, nByte, pFile->locktype));
  30939. /* If the user has configured a chunk-size for this file, truncate the
  30940. ** file so that it consists of an integer number of chunks (i.e. the
  30941. ** actual file size after the operation may be larger than the requested
  30942. ** size).
  30943. */
  30944. if( pFile->szChunk>0 ){
  30945. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  30946. }
  30947. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  30948. if( seekWinFile(pFile, nByte) ){
  30949. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  30950. "winTruncate1", pFile->zPath);
  30951. }else if( 0==osSetEndOfFile(pFile->h) &&
  30952. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  30953. pFile->lastErrno = lastErrno;
  30954. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  30955. "winTruncate2", pFile->zPath);
  30956. }
  30957. #if SQLITE_MAX_MMAP_SIZE>0
  30958. /* If the file was truncated to a size smaller than the currently
  30959. ** mapped region, reduce the effective mapping size as well. SQLite will
  30960. ** use read() and write() to access data beyond this point from now on.
  30961. */
  30962. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  30963. pFile->mmapSize = nByte;
  30964. }
  30965. #endif
  30966. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  30967. return rc;
  30968. }
  30969. #ifdef SQLITE_TEST
  30970. /*
  30971. ** Count the number of fullsyncs and normal syncs. This is used to test
  30972. ** that syncs and fullsyncs are occuring at the right times.
  30973. */
  30974. SQLITE_API int sqlite3_sync_count = 0;
  30975. SQLITE_API int sqlite3_fullsync_count = 0;
  30976. #endif
  30977. /*
  30978. ** Make sure all writes to a particular file are committed to disk.
  30979. */
  30980. static int winSync(sqlite3_file *id, int flags){
  30981. #ifndef SQLITE_NO_SYNC
  30982. /*
  30983. ** Used only when SQLITE_NO_SYNC is not defined.
  30984. */
  30985. BOOL rc;
  30986. #endif
  30987. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  30988. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  30989. /*
  30990. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  30991. ** OSTRACE() macros.
  30992. */
  30993. winFile *pFile = (winFile*)id;
  30994. #else
  30995. UNUSED_PARAMETER(id);
  30996. #endif
  30997. assert( pFile );
  30998. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  30999. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31000. || (flags&0x0F)==SQLITE_SYNC_FULL
  31001. );
  31002. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31003. ** line is to test that doing so does not cause any problems.
  31004. */
  31005. SimulateDiskfullError( return SQLITE_FULL );
  31006. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  31007. pFile->h, flags, pFile->locktype));
  31008. #ifndef SQLITE_TEST
  31009. UNUSED_PARAMETER(flags);
  31010. #else
  31011. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  31012. sqlite3_fullsync_count++;
  31013. }
  31014. sqlite3_sync_count++;
  31015. #endif
  31016. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31017. ** no-op
  31018. */
  31019. #ifdef SQLITE_NO_SYNC
  31020. return SQLITE_OK;
  31021. #else
  31022. rc = osFlushFileBuffers(pFile->h);
  31023. SimulateIOError( rc=FALSE );
  31024. if( rc ){
  31025. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  31026. return SQLITE_OK;
  31027. }else{
  31028. pFile->lastErrno = osGetLastError();
  31029. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  31030. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  31031. "winSync", pFile->zPath);
  31032. }
  31033. #endif
  31034. }
  31035. /*
  31036. ** Determine the current size of a file in bytes
  31037. */
  31038. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  31039. winFile *pFile = (winFile*)id;
  31040. int rc = SQLITE_OK;
  31041. assert( id!=0 );
  31042. assert( pSize!=0 );
  31043. SimulateIOError(return SQLITE_IOERR_FSTAT);
  31044. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  31045. #if SQLITE_OS_WINRT
  31046. {
  31047. FILE_STANDARD_INFO info;
  31048. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  31049. &info, sizeof(info)) ){
  31050. *pSize = info.EndOfFile.QuadPart;
  31051. }else{
  31052. pFile->lastErrno = osGetLastError();
  31053. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31054. "winFileSize", pFile->zPath);
  31055. }
  31056. }
  31057. #else
  31058. {
  31059. DWORD upperBits;
  31060. DWORD lowerBits;
  31061. DWORD lastErrno;
  31062. lowerBits = osGetFileSize(pFile->h, &upperBits);
  31063. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  31064. if( (lowerBits == INVALID_FILE_SIZE)
  31065. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  31066. pFile->lastErrno = lastErrno;
  31067. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31068. "winFileSize", pFile->zPath);
  31069. }
  31070. }
  31071. #endif
  31072. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  31073. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  31074. return rc;
  31075. }
  31076. /*
  31077. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  31078. */
  31079. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  31080. # define LOCKFILE_FAIL_IMMEDIATELY 1
  31081. #endif
  31082. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  31083. # define LOCKFILE_EXCLUSIVE_LOCK 2
  31084. #endif
  31085. /*
  31086. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  31087. ** When the LockFile function was used, it was always expected to fail
  31088. ** immediately if the lock could not be obtained. Also, it always expected to
  31089. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  31090. ** and reflect those expectations; therefore, they should not be changed.
  31091. */
  31092. #ifndef SQLITE_LOCKFILE_FLAGS
  31093. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  31094. LOCKFILE_EXCLUSIVE_LOCK)
  31095. #endif
  31096. /*
  31097. ** Currently, SQLite never calls the LockFileEx function without wanting the
  31098. ** call to fail immediately if the lock cannot be obtained.
  31099. */
  31100. #ifndef SQLITE_LOCKFILEEX_FLAGS
  31101. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  31102. #endif
  31103. /*
  31104. ** Acquire a reader lock.
  31105. ** Different API routines are called depending on whether or not this
  31106. ** is Win9x or WinNT.
  31107. */
  31108. static int getReadLock(winFile *pFile){
  31109. int res;
  31110. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31111. if( isNT() ){
  31112. #if SQLITE_OS_WINCE
  31113. /*
  31114. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31115. ** API LockFileEx.
  31116. */
  31117. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  31118. #else
  31119. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  31120. SHARED_SIZE, 0);
  31121. #endif
  31122. }
  31123. #ifdef SQLITE_WIN32_HAS_ANSI
  31124. else{
  31125. int lk;
  31126. sqlite3_randomness(sizeof(lk), &lk);
  31127. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  31128. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31129. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31130. }
  31131. #endif
  31132. if( res == 0 ){
  31133. pFile->lastErrno = osGetLastError();
  31134. /* No need to log a failure to lock */
  31135. }
  31136. OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31137. return res;
  31138. }
  31139. /*
  31140. ** Undo a readlock
  31141. */
  31142. static int unlockReadLock(winFile *pFile){
  31143. int res;
  31144. DWORD lastErrno;
  31145. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31146. if( isNT() ){
  31147. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31148. }
  31149. #ifdef SQLITE_WIN32_HAS_ANSI
  31150. else{
  31151. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31152. }
  31153. #endif
  31154. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  31155. pFile->lastErrno = lastErrno;
  31156. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  31157. "unlockReadLock", pFile->zPath);
  31158. }
  31159. OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31160. return res;
  31161. }
  31162. /*
  31163. ** Lock the file with the lock specified by parameter locktype - one
  31164. ** of the following:
  31165. **
  31166. ** (1) SHARED_LOCK
  31167. ** (2) RESERVED_LOCK
  31168. ** (3) PENDING_LOCK
  31169. ** (4) EXCLUSIVE_LOCK
  31170. **
  31171. ** Sometimes when requesting one lock state, additional lock states
  31172. ** are inserted in between. The locking might fail on one of the later
  31173. ** transitions leaving the lock state different from what it started but
  31174. ** still short of its goal. The following chart shows the allowed
  31175. ** transitions and the inserted intermediate states:
  31176. **
  31177. ** UNLOCKED -> SHARED
  31178. ** SHARED -> RESERVED
  31179. ** SHARED -> (PENDING) -> EXCLUSIVE
  31180. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31181. ** PENDING -> EXCLUSIVE
  31182. **
  31183. ** This routine will only increase a lock. The winUnlock() routine
  31184. ** erases all locks at once and returns us immediately to locking level 0.
  31185. ** It is not possible to lower the locking level one step at a time. You
  31186. ** must go straight to locking level 0.
  31187. */
  31188. static int winLock(sqlite3_file *id, int locktype){
  31189. int rc = SQLITE_OK; /* Return code from subroutines */
  31190. int res = 1; /* Result of a Windows lock call */
  31191. int newLocktype; /* Set pFile->locktype to this value before exiting */
  31192. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  31193. winFile *pFile = (winFile*)id;
  31194. DWORD lastErrno = NO_ERROR;
  31195. assert( id!=0 );
  31196. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31197. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31198. /* If there is already a lock of this type or more restrictive on the
  31199. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  31200. ** sqlite3OsEnterMutex() hasn't been called yet.
  31201. */
  31202. if( pFile->locktype>=locktype ){
  31203. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  31204. return SQLITE_OK;
  31205. }
  31206. /* Make sure the locking sequence is correct
  31207. */
  31208. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  31209. assert( locktype!=PENDING_LOCK );
  31210. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  31211. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  31212. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  31213. ** the PENDING_LOCK byte is temporary.
  31214. */
  31215. newLocktype = pFile->locktype;
  31216. if( (pFile->locktype==NO_LOCK)
  31217. || ( (locktype==EXCLUSIVE_LOCK)
  31218. && (pFile->locktype==RESERVED_LOCK))
  31219. ){
  31220. int cnt = 3;
  31221. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31222. PENDING_BYTE, 0, 1, 0))==0 ){
  31223. /* Try 3 times to get the pending lock. This is needed to work
  31224. ** around problems caused by indexing and/or anti-virus software on
  31225. ** Windows systems.
  31226. ** If you are using this code as a model for alternative VFSes, do not
  31227. ** copy this retry logic. It is a hack intended for Windows only.
  31228. */
  31229. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
  31230. pFile->h, cnt, sqlite3ErrName(res)));
  31231. if( cnt ) sqlite3_win32_sleep(1);
  31232. }
  31233. gotPendingLock = res;
  31234. if( !res ){
  31235. lastErrno = osGetLastError();
  31236. }
  31237. }
  31238. /* Acquire a shared lock
  31239. */
  31240. if( locktype==SHARED_LOCK && res ){
  31241. assert( pFile->locktype==NO_LOCK );
  31242. res = getReadLock(pFile);
  31243. if( res ){
  31244. newLocktype = SHARED_LOCK;
  31245. }else{
  31246. lastErrno = osGetLastError();
  31247. }
  31248. }
  31249. /* Acquire a RESERVED lock
  31250. */
  31251. if( locktype==RESERVED_LOCK && res ){
  31252. assert( pFile->locktype==SHARED_LOCK );
  31253. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  31254. if( res ){
  31255. newLocktype = RESERVED_LOCK;
  31256. }else{
  31257. lastErrno = osGetLastError();
  31258. }
  31259. }
  31260. /* Acquire a PENDING lock
  31261. */
  31262. if( locktype==EXCLUSIVE_LOCK && res ){
  31263. newLocktype = PENDING_LOCK;
  31264. gotPendingLock = 0;
  31265. }
  31266. /* Acquire an EXCLUSIVE lock
  31267. */
  31268. if( locktype==EXCLUSIVE_LOCK && res ){
  31269. assert( pFile->locktype>=SHARED_LOCK );
  31270. res = unlockReadLock(pFile);
  31271. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  31272. SHARED_SIZE, 0);
  31273. if( res ){
  31274. newLocktype = EXCLUSIVE_LOCK;
  31275. }else{
  31276. lastErrno = osGetLastError();
  31277. getReadLock(pFile);
  31278. }
  31279. }
  31280. /* If we are holding a PENDING lock that ought to be released, then
  31281. ** release it now.
  31282. */
  31283. if( gotPendingLock && locktype==SHARED_LOCK ){
  31284. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31285. }
  31286. /* Update the state of the lock has held in the file descriptor then
  31287. ** return the appropriate result code.
  31288. */
  31289. if( res ){
  31290. rc = SQLITE_OK;
  31291. }else{
  31292. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  31293. pFile->h, locktype, newLocktype));
  31294. pFile->lastErrno = lastErrno;
  31295. rc = SQLITE_BUSY;
  31296. }
  31297. pFile->locktype = (u8)newLocktype;
  31298. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  31299. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31300. return rc;
  31301. }
  31302. /*
  31303. ** This routine checks if there is a RESERVED lock held on the specified
  31304. ** file by this or any other process. If such a lock is held, return
  31305. ** non-zero, otherwise zero.
  31306. */
  31307. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  31308. int rc;
  31309. winFile *pFile = (winFile*)id;
  31310. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31311. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  31312. assert( id!=0 );
  31313. if( pFile->locktype>=RESERVED_LOCK ){
  31314. rc = 1;
  31315. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
  31316. }else{
  31317. rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  31318. if( rc ){
  31319. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31320. }
  31321. rc = !rc;
  31322. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
  31323. }
  31324. *pResOut = rc;
  31325. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  31326. pFile->h, pResOut, *pResOut));
  31327. return SQLITE_OK;
  31328. }
  31329. /*
  31330. ** Lower the locking level on file descriptor id to locktype. locktype
  31331. ** must be either NO_LOCK or SHARED_LOCK.
  31332. **
  31333. ** If the locking level of the file descriptor is already at or below
  31334. ** the requested locking level, this routine is a no-op.
  31335. **
  31336. ** It is not possible for this routine to fail if the second argument
  31337. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  31338. ** might return SQLITE_IOERR;
  31339. */
  31340. static int winUnlock(sqlite3_file *id, int locktype){
  31341. int type;
  31342. winFile *pFile = (winFile*)id;
  31343. int rc = SQLITE_OK;
  31344. assert( pFile!=0 );
  31345. assert( locktype<=SHARED_LOCK );
  31346. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31347. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31348. type = pFile->locktype;
  31349. if( type>=EXCLUSIVE_LOCK ){
  31350. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31351. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  31352. /* This should never happen. We should always be able to
  31353. ** reacquire the read lock */
  31354. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  31355. "winUnlock", pFile->zPath);
  31356. }
  31357. }
  31358. if( type>=RESERVED_LOCK ){
  31359. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31360. }
  31361. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  31362. unlockReadLock(pFile);
  31363. }
  31364. if( type>=PENDING_LOCK ){
  31365. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31366. }
  31367. pFile->locktype = (u8)locktype;
  31368. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  31369. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31370. return rc;
  31371. }
  31372. /*
  31373. ** If *pArg is inititially negative then this is a query. Set *pArg to
  31374. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31375. **
  31376. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31377. */
  31378. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  31379. if( *pArg<0 ){
  31380. *pArg = (pFile->ctrlFlags & mask)!=0;
  31381. }else if( (*pArg)==0 ){
  31382. pFile->ctrlFlags &= ~mask;
  31383. }else{
  31384. pFile->ctrlFlags |= mask;
  31385. }
  31386. }
  31387. /* Forward declaration */
  31388. static int getTempname(int nBuf, char *zBuf);
  31389. /*
  31390. ** Control and query of the open file handle.
  31391. */
  31392. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  31393. winFile *pFile = (winFile*)id;
  31394. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  31395. switch( op ){
  31396. case SQLITE_FCNTL_LOCKSTATE: {
  31397. *(int*)pArg = pFile->locktype;
  31398. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31399. return SQLITE_OK;
  31400. }
  31401. case SQLITE_LAST_ERRNO: {
  31402. *(int*)pArg = (int)pFile->lastErrno;
  31403. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31404. return SQLITE_OK;
  31405. }
  31406. case SQLITE_FCNTL_CHUNK_SIZE: {
  31407. pFile->szChunk = *(int *)pArg;
  31408. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31409. return SQLITE_OK;
  31410. }
  31411. case SQLITE_FCNTL_SIZE_HINT: {
  31412. if( pFile->szChunk>0 ){
  31413. sqlite3_int64 oldSz;
  31414. int rc = winFileSize(id, &oldSz);
  31415. if( rc==SQLITE_OK ){
  31416. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  31417. if( newSz>oldSz ){
  31418. SimulateIOErrorBenign(1);
  31419. rc = winTruncate(id, newSz);
  31420. SimulateIOErrorBenign(0);
  31421. }
  31422. }
  31423. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31424. return rc;
  31425. }
  31426. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31427. return SQLITE_OK;
  31428. }
  31429. case SQLITE_FCNTL_PERSIST_WAL: {
  31430. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  31431. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31432. return SQLITE_OK;
  31433. }
  31434. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31435. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  31436. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31437. return SQLITE_OK;
  31438. }
  31439. case SQLITE_FCNTL_VFSNAME: {
  31440. *(char**)pArg = sqlite3_mprintf("win32");
  31441. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31442. return SQLITE_OK;
  31443. }
  31444. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  31445. int *a = (int*)pArg;
  31446. if( a[0]>0 ){
  31447. win32IoerrRetry = a[0];
  31448. }else{
  31449. a[0] = win32IoerrRetry;
  31450. }
  31451. if( a[1]>0 ){
  31452. win32IoerrRetryDelay = a[1];
  31453. }else{
  31454. a[1] = win32IoerrRetryDelay;
  31455. }
  31456. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31457. return SQLITE_OK;
  31458. }
  31459. case SQLITE_FCNTL_TEMPFILENAME: {
  31460. char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
  31461. if( zTFile ){
  31462. getTempname(pFile->pVfs->mxPathname, zTFile);
  31463. *(char**)pArg = zTFile;
  31464. }
  31465. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31466. return SQLITE_OK;
  31467. }
  31468. #if SQLITE_MAX_MMAP_SIZE>0
  31469. case SQLITE_FCNTL_MMAP_SIZE: {
  31470. i64 newLimit = *(i64*)pArg;
  31471. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  31472. newLimit = sqlite3GlobalConfig.mxMmap;
  31473. }
  31474. *(i64*)pArg = pFile->mmapSizeMax;
  31475. if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
  31476. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31477. return SQLITE_OK;
  31478. }
  31479. #endif
  31480. }
  31481. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  31482. return SQLITE_NOTFOUND;
  31483. }
  31484. /*
  31485. ** Return the sector size in bytes of the underlying block device for
  31486. ** the specified file. This is almost always 512 bytes, but may be
  31487. ** larger for some devices.
  31488. **
  31489. ** SQLite code assumes this function cannot fail. It also assumes that
  31490. ** if two files are created in the same file-system directory (i.e.
  31491. ** a database and its journal file) that the sector size will be the
  31492. ** same for both.
  31493. */
  31494. static int winSectorSize(sqlite3_file *id){
  31495. (void)id;
  31496. return SQLITE_DEFAULT_SECTOR_SIZE;
  31497. }
  31498. /*
  31499. ** Return a vector of device characteristics.
  31500. */
  31501. static int winDeviceCharacteristics(sqlite3_file *id){
  31502. winFile *p = (winFile*)id;
  31503. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  31504. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  31505. }
  31506. /*
  31507. ** Windows will only let you create file view mappings
  31508. ** on allocation size granularity boundaries.
  31509. ** During sqlite3_os_init() we do a GetSystemInfo()
  31510. ** to get the granularity size.
  31511. */
  31512. SYSTEM_INFO winSysInfo;
  31513. #ifndef SQLITE_OMIT_WAL
  31514. /*
  31515. ** Helper functions to obtain and relinquish the global mutex. The
  31516. ** global mutex is used to protect the winLockInfo objects used by
  31517. ** this file, all of which may be shared by multiple threads.
  31518. **
  31519. ** Function winShmMutexHeld() is used to assert() that the global mutex
  31520. ** is held when required. This function is only used as part of assert()
  31521. ** statements. e.g.
  31522. **
  31523. ** winShmEnterMutex()
  31524. ** assert( winShmMutexHeld() );
  31525. ** winShmLeaveMutex()
  31526. */
  31527. static void winShmEnterMutex(void){
  31528. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31529. }
  31530. static void winShmLeaveMutex(void){
  31531. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31532. }
  31533. #ifdef SQLITE_DEBUG
  31534. static int winShmMutexHeld(void) {
  31535. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  31536. }
  31537. #endif
  31538. /*
  31539. ** Object used to represent a single file opened and mmapped to provide
  31540. ** shared memory. When multiple threads all reference the same
  31541. ** log-summary, each thread has its own winFile object, but they all
  31542. ** point to a single instance of this object. In other words, each
  31543. ** log-summary is opened only once per process.
  31544. **
  31545. ** winShmMutexHeld() must be true when creating or destroying
  31546. ** this object or while reading or writing the following fields:
  31547. **
  31548. ** nRef
  31549. ** pNext
  31550. **
  31551. ** The following fields are read-only after the object is created:
  31552. **
  31553. ** fid
  31554. ** zFilename
  31555. **
  31556. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  31557. ** winShmMutexHeld() is true when reading or writing any other field
  31558. ** in this structure.
  31559. **
  31560. */
  31561. struct winShmNode {
  31562. sqlite3_mutex *mutex; /* Mutex to access this object */
  31563. char *zFilename; /* Name of the file */
  31564. winFile hFile; /* File handle from winOpen */
  31565. int szRegion; /* Size of shared-memory regions */
  31566. int nRegion; /* Size of array apRegion */
  31567. struct ShmRegion {
  31568. HANDLE hMap; /* File handle from CreateFileMapping */
  31569. void *pMap;
  31570. } *aRegion;
  31571. DWORD lastErrno; /* The Windows errno from the last I/O error */
  31572. int nRef; /* Number of winShm objects pointing to this */
  31573. winShm *pFirst; /* All winShm objects pointing to this */
  31574. winShmNode *pNext; /* Next in list of all winShmNode objects */
  31575. #ifdef SQLITE_DEBUG
  31576. u8 nextShmId; /* Next available winShm.id value */
  31577. #endif
  31578. };
  31579. /*
  31580. ** A global array of all winShmNode objects.
  31581. **
  31582. ** The winShmMutexHeld() must be true while reading or writing this list.
  31583. */
  31584. static winShmNode *winShmNodeList = 0;
  31585. /*
  31586. ** Structure used internally by this VFS to record the state of an
  31587. ** open shared memory connection.
  31588. **
  31589. ** The following fields are initialized when this object is created and
  31590. ** are read-only thereafter:
  31591. **
  31592. ** winShm.pShmNode
  31593. ** winShm.id
  31594. **
  31595. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  31596. ** while accessing any read/write fields.
  31597. */
  31598. struct winShm {
  31599. winShmNode *pShmNode; /* The underlying winShmNode object */
  31600. winShm *pNext; /* Next winShm with the same winShmNode */
  31601. u8 hasMutex; /* True if holding the winShmNode mutex */
  31602. u16 sharedMask; /* Mask of shared locks held */
  31603. u16 exclMask; /* Mask of exclusive locks held */
  31604. #ifdef SQLITE_DEBUG
  31605. u8 id; /* Id of this connection with its winShmNode */
  31606. #endif
  31607. };
  31608. /*
  31609. ** Constants used for locking
  31610. */
  31611. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  31612. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  31613. /*
  31614. ** Apply advisory locks for all n bytes beginning at ofst.
  31615. */
  31616. #define _SHM_UNLCK 1
  31617. #define _SHM_RDLCK 2
  31618. #define _SHM_WRLCK 3
  31619. static int winShmSystemLock(
  31620. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  31621. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  31622. int ofst, /* Offset to first byte to be locked/unlocked */
  31623. int nByte /* Number of bytes to lock or unlock */
  31624. ){
  31625. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  31626. /* Access to the winShmNode object is serialized by the caller */
  31627. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  31628. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  31629. pFile->hFile.h, lockType, ofst, nByte));
  31630. /* Release/Acquire the system-level lock */
  31631. if( lockType==_SHM_UNLCK ){
  31632. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  31633. }else{
  31634. /* Initialize the locking parameters */
  31635. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  31636. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  31637. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  31638. }
  31639. if( rc!= 0 ){
  31640. rc = SQLITE_OK;
  31641. }else{
  31642. pFile->lastErrno = osGetLastError();
  31643. rc = SQLITE_BUSY;
  31644. }
  31645. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  31646. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  31647. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  31648. return rc;
  31649. }
  31650. /* Forward references to VFS methods */
  31651. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  31652. static int winDelete(sqlite3_vfs *,const char*,int);
  31653. /*
  31654. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  31655. **
  31656. ** This is not a VFS shared-memory method; it is a utility function called
  31657. ** by VFS shared-memory methods.
  31658. */
  31659. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  31660. winShmNode **pp;
  31661. winShmNode *p;
  31662. BOOL bRc;
  31663. assert( winShmMutexHeld() );
  31664. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  31665. osGetCurrentProcessId(), deleteFlag));
  31666. pp = &winShmNodeList;
  31667. while( (p = *pp)!=0 ){
  31668. if( p->nRef==0 ){
  31669. int i;
  31670. if( p->mutex ) sqlite3_mutex_free(p->mutex);
  31671. for(i=0; i<p->nRegion; i++){
  31672. bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  31673. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  31674. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  31675. bRc = osCloseHandle(p->aRegion[i].hMap);
  31676. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  31677. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  31678. }
  31679. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  31680. SimulateIOErrorBenign(1);
  31681. winClose((sqlite3_file *)&p->hFile);
  31682. SimulateIOErrorBenign(0);
  31683. }
  31684. if( deleteFlag ){
  31685. SimulateIOErrorBenign(1);
  31686. sqlite3BeginBenignMalloc();
  31687. winDelete(pVfs, p->zFilename, 0);
  31688. sqlite3EndBenignMalloc();
  31689. SimulateIOErrorBenign(0);
  31690. }
  31691. *pp = p->pNext;
  31692. sqlite3_free(p->aRegion);
  31693. sqlite3_free(p);
  31694. }else{
  31695. pp = &p->pNext;
  31696. }
  31697. }
  31698. }
  31699. /*
  31700. ** Open the shared-memory area associated with database file pDbFd.
  31701. **
  31702. ** When opening a new shared-memory file, if no other instances of that
  31703. ** file are currently open, in this process or in other processes, then
  31704. ** the file must be truncated to zero length or have its header cleared.
  31705. */
  31706. static int winOpenSharedMemory(winFile *pDbFd){
  31707. struct winShm *p; /* The connection to be opened */
  31708. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  31709. int rc; /* Result code */
  31710. struct winShmNode *pNew; /* Newly allocated winShmNode */
  31711. int nName; /* Size of zName in bytes */
  31712. assert( pDbFd->pShm==0 ); /* Not previously opened */
  31713. /* Allocate space for the new sqlite3_shm object. Also speculatively
  31714. ** allocate space for a new winShmNode and filename.
  31715. */
  31716. p = sqlite3MallocZero( sizeof(*p) );
  31717. if( p==0 ) return SQLITE_IOERR_NOMEM;
  31718. nName = sqlite3Strlen30(pDbFd->zPath);
  31719. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  31720. if( pNew==0 ){
  31721. sqlite3_free(p);
  31722. return SQLITE_IOERR_NOMEM;
  31723. }
  31724. pNew->zFilename = (char*)&pNew[1];
  31725. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  31726. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  31727. /* Look to see if there is an existing winShmNode that can be used.
  31728. ** If no matching winShmNode currently exists, create a new one.
  31729. */
  31730. winShmEnterMutex();
  31731. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  31732. /* TBD need to come up with better match here. Perhaps
  31733. ** use FILE_ID_BOTH_DIR_INFO Structure.
  31734. */
  31735. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  31736. }
  31737. if( pShmNode ){
  31738. sqlite3_free(pNew);
  31739. }else{
  31740. pShmNode = pNew;
  31741. pNew = 0;
  31742. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  31743. pShmNode->pNext = winShmNodeList;
  31744. winShmNodeList = pShmNode;
  31745. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  31746. if( pShmNode->mutex==0 ){
  31747. rc = SQLITE_IOERR_NOMEM;
  31748. goto shm_open_err;
  31749. }
  31750. rc = winOpen(pDbFd->pVfs,
  31751. pShmNode->zFilename, /* Name of the file (UTF-8) */
  31752. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  31753. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  31754. 0);
  31755. if( SQLITE_OK!=rc ){
  31756. goto shm_open_err;
  31757. }
  31758. /* Check to see if another process is holding the dead-man switch.
  31759. ** If not, truncate the file to zero length.
  31760. */
  31761. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  31762. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  31763. if( rc!=SQLITE_OK ){
  31764. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  31765. "winOpenShm", pDbFd->zPath);
  31766. }
  31767. }
  31768. if( rc==SQLITE_OK ){
  31769. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31770. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  31771. }
  31772. if( rc ) goto shm_open_err;
  31773. }
  31774. /* Make the new connection a child of the winShmNode */
  31775. p->pShmNode = pShmNode;
  31776. #ifdef SQLITE_DEBUG
  31777. p->id = pShmNode->nextShmId++;
  31778. #endif
  31779. pShmNode->nRef++;
  31780. pDbFd->pShm = p;
  31781. winShmLeaveMutex();
  31782. /* The reference count on pShmNode has already been incremented under
  31783. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  31784. ** new (struct winShm) object to the pShmNode has been set. All that is
  31785. ** left to do is to link the new object into the linked list starting
  31786. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  31787. ** mutex.
  31788. */
  31789. sqlite3_mutex_enter(pShmNode->mutex);
  31790. p->pNext = pShmNode->pFirst;
  31791. pShmNode->pFirst = p;
  31792. sqlite3_mutex_leave(pShmNode->mutex);
  31793. return SQLITE_OK;
  31794. /* Jump here on any error */
  31795. shm_open_err:
  31796. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31797. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  31798. sqlite3_free(p);
  31799. sqlite3_free(pNew);
  31800. winShmLeaveMutex();
  31801. return rc;
  31802. }
  31803. /*
  31804. ** Close a connection to shared-memory. Delete the underlying
  31805. ** storage if deleteFlag is true.
  31806. */
  31807. static int winShmUnmap(
  31808. sqlite3_file *fd, /* Database holding shared memory */
  31809. int deleteFlag /* Delete after closing if true */
  31810. ){
  31811. winFile *pDbFd; /* Database holding shared-memory */
  31812. winShm *p; /* The connection to be closed */
  31813. winShmNode *pShmNode; /* The underlying shared-memory file */
  31814. winShm **pp; /* For looping over sibling connections */
  31815. pDbFd = (winFile*)fd;
  31816. p = pDbFd->pShm;
  31817. if( p==0 ) return SQLITE_OK;
  31818. pShmNode = p->pShmNode;
  31819. /* Remove connection p from the set of connections associated
  31820. ** with pShmNode */
  31821. sqlite3_mutex_enter(pShmNode->mutex);
  31822. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  31823. *pp = p->pNext;
  31824. /* Free the connection p */
  31825. sqlite3_free(p);
  31826. pDbFd->pShm = 0;
  31827. sqlite3_mutex_leave(pShmNode->mutex);
  31828. /* If pShmNode->nRef has reached 0, then close the underlying
  31829. ** shared-memory file, too */
  31830. winShmEnterMutex();
  31831. assert( pShmNode->nRef>0 );
  31832. pShmNode->nRef--;
  31833. if( pShmNode->nRef==0 ){
  31834. winShmPurge(pDbFd->pVfs, deleteFlag);
  31835. }
  31836. winShmLeaveMutex();
  31837. return SQLITE_OK;
  31838. }
  31839. /*
  31840. ** Change the lock state for a shared-memory segment.
  31841. */
  31842. static int winShmLock(
  31843. sqlite3_file *fd, /* Database file holding the shared memory */
  31844. int ofst, /* First lock to acquire or release */
  31845. int n, /* Number of locks to acquire or release */
  31846. int flags /* What to do with the lock */
  31847. ){
  31848. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  31849. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  31850. winShm *pX; /* For looping over all siblings */
  31851. winShmNode *pShmNode = p->pShmNode;
  31852. int rc = SQLITE_OK; /* Result code */
  31853. u16 mask; /* Mask of locks to take or release */
  31854. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  31855. assert( n>=1 );
  31856. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  31857. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  31858. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  31859. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  31860. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  31861. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  31862. assert( n>1 || mask==(1<<ofst) );
  31863. sqlite3_mutex_enter(pShmNode->mutex);
  31864. if( flags & SQLITE_SHM_UNLOCK ){
  31865. u16 allMask = 0; /* Mask of locks held by siblings */
  31866. /* See if any siblings hold this same lock */
  31867. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31868. if( pX==p ) continue;
  31869. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  31870. allMask |= pX->sharedMask;
  31871. }
  31872. /* Unlock the system-level locks */
  31873. if( (mask & allMask)==0 ){
  31874. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  31875. }else{
  31876. rc = SQLITE_OK;
  31877. }
  31878. /* Undo the local locks */
  31879. if( rc==SQLITE_OK ){
  31880. p->exclMask &= ~mask;
  31881. p->sharedMask &= ~mask;
  31882. }
  31883. }else if( flags & SQLITE_SHM_SHARED ){
  31884. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  31885. /* Find out which shared locks are already held by sibling connections.
  31886. ** If any sibling already holds an exclusive lock, go ahead and return
  31887. ** SQLITE_BUSY.
  31888. */
  31889. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31890. if( (pX->exclMask & mask)!=0 ){
  31891. rc = SQLITE_BUSY;
  31892. break;
  31893. }
  31894. allShared |= pX->sharedMask;
  31895. }
  31896. /* Get shared locks at the system level, if necessary */
  31897. if( rc==SQLITE_OK ){
  31898. if( (allShared & mask)==0 ){
  31899. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  31900. }else{
  31901. rc = SQLITE_OK;
  31902. }
  31903. }
  31904. /* Get the local shared locks */
  31905. if( rc==SQLITE_OK ){
  31906. p->sharedMask |= mask;
  31907. }
  31908. }else{
  31909. /* Make sure no sibling connections hold locks that will block this
  31910. ** lock. If any do, return SQLITE_BUSY right away.
  31911. */
  31912. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31913. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  31914. rc = SQLITE_BUSY;
  31915. break;
  31916. }
  31917. }
  31918. /* Get the exclusive locks at the system level. Then if successful
  31919. ** also mark the local connection as being locked.
  31920. */
  31921. if( rc==SQLITE_OK ){
  31922. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  31923. if( rc==SQLITE_OK ){
  31924. assert( (p->sharedMask & mask)==0 );
  31925. p->exclMask |= mask;
  31926. }
  31927. }
  31928. }
  31929. sqlite3_mutex_leave(pShmNode->mutex);
  31930. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  31931. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  31932. sqlite3ErrName(rc)));
  31933. return rc;
  31934. }
  31935. /*
  31936. ** Implement a memory barrier or memory fence on shared memory.
  31937. **
  31938. ** All loads and stores begun before the barrier must complete before
  31939. ** any load or store begun after the barrier.
  31940. */
  31941. static void winShmBarrier(
  31942. sqlite3_file *fd /* Database holding the shared memory */
  31943. ){
  31944. UNUSED_PARAMETER(fd);
  31945. /* MemoryBarrier(); // does not work -- do not know why not */
  31946. winShmEnterMutex();
  31947. winShmLeaveMutex();
  31948. }
  31949. /*
  31950. ** This function is called to obtain a pointer to region iRegion of the
  31951. ** shared-memory associated with the database file fd. Shared-memory regions
  31952. ** are numbered starting from zero. Each shared-memory region is szRegion
  31953. ** bytes in size.
  31954. **
  31955. ** If an error occurs, an error code is returned and *pp is set to NULL.
  31956. **
  31957. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  31958. ** region has not been allocated (by any client, including one running in a
  31959. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  31960. ** isWrite is non-zero and the requested shared-memory region has not yet
  31961. ** been allocated, it is allocated by this function.
  31962. **
  31963. ** If the shared-memory region has already been allocated or is allocated by
  31964. ** this call as described above, then it is mapped into this processes
  31965. ** address space (if it is not already), *pp is set to point to the mapped
  31966. ** memory and SQLITE_OK returned.
  31967. */
  31968. static int winShmMap(
  31969. sqlite3_file *fd, /* Handle open on database file */
  31970. int iRegion, /* Region to retrieve */
  31971. int szRegion, /* Size of regions */
  31972. int isWrite, /* True to extend file if necessary */
  31973. void volatile **pp /* OUT: Mapped memory */
  31974. ){
  31975. winFile *pDbFd = (winFile*)fd;
  31976. winShm *p = pDbFd->pShm;
  31977. winShmNode *pShmNode;
  31978. int rc = SQLITE_OK;
  31979. if( !p ){
  31980. rc = winOpenSharedMemory(pDbFd);
  31981. if( rc!=SQLITE_OK ) return rc;
  31982. p = pDbFd->pShm;
  31983. }
  31984. pShmNode = p->pShmNode;
  31985. sqlite3_mutex_enter(pShmNode->mutex);
  31986. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  31987. if( pShmNode->nRegion<=iRegion ){
  31988. struct ShmRegion *apNew; /* New aRegion[] array */
  31989. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  31990. sqlite3_int64 sz; /* Current size of wal-index file */
  31991. pShmNode->szRegion = szRegion;
  31992. /* The requested region is not mapped into this processes address space.
  31993. ** Check to see if it has been allocated (i.e. if the wal-index file is
  31994. ** large enough to contain the requested region).
  31995. */
  31996. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  31997. if( rc!=SQLITE_OK ){
  31998. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  31999. "winShmMap1", pDbFd->zPath);
  32000. goto shmpage_out;
  32001. }
  32002. if( sz<nByte ){
  32003. /* The requested memory region does not exist. If isWrite is set to
  32004. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32005. **
  32006. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  32007. ** the requested memory region.
  32008. */
  32009. if( !isWrite ) goto shmpage_out;
  32010. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  32011. if( rc!=SQLITE_OK ){
  32012. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32013. "winShmMap2", pDbFd->zPath);
  32014. goto shmpage_out;
  32015. }
  32016. }
  32017. /* Map the requested memory region into this processes address space. */
  32018. apNew = (struct ShmRegion *)sqlite3_realloc(
  32019. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  32020. );
  32021. if( !apNew ){
  32022. rc = SQLITE_IOERR_NOMEM;
  32023. goto shmpage_out;
  32024. }
  32025. pShmNode->aRegion = apNew;
  32026. while( pShmNode->nRegion<=iRegion ){
  32027. HANDLE hMap = NULL; /* file-mapping handle */
  32028. void *pMap = 0; /* Mapped memory region */
  32029. #if SQLITE_OS_WINRT
  32030. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  32031. NULL, PAGE_READWRITE, nByte, NULL
  32032. );
  32033. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32034. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  32035. NULL, PAGE_READWRITE, 0, nByte, NULL
  32036. );
  32037. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32038. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  32039. NULL, PAGE_READWRITE, 0, nByte, NULL
  32040. );
  32041. #endif
  32042. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  32043. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  32044. hMap ? "ok" : "failed"));
  32045. if( hMap ){
  32046. int iOffset = pShmNode->nRegion*szRegion;
  32047. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32048. #if SQLITE_OS_WINRT
  32049. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32050. iOffset - iOffsetShift, szRegion + iOffsetShift
  32051. );
  32052. #else
  32053. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32054. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  32055. );
  32056. #endif
  32057. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  32058. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  32059. szRegion, pMap ? "ok" : "failed"));
  32060. }
  32061. if( !pMap ){
  32062. pShmNode->lastErrno = osGetLastError();
  32063. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  32064. "winShmMap3", pDbFd->zPath);
  32065. if( hMap ) osCloseHandle(hMap);
  32066. goto shmpage_out;
  32067. }
  32068. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  32069. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  32070. pShmNode->nRegion++;
  32071. }
  32072. }
  32073. shmpage_out:
  32074. if( pShmNode->nRegion>iRegion ){
  32075. int iOffset = iRegion*szRegion;
  32076. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32077. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  32078. *pp = (void *)&p[iOffsetShift];
  32079. }else{
  32080. *pp = 0;
  32081. }
  32082. sqlite3_mutex_leave(pShmNode->mutex);
  32083. return rc;
  32084. }
  32085. #else
  32086. # define winShmMap 0
  32087. # define winShmLock 0
  32088. # define winShmBarrier 0
  32089. # define winShmUnmap 0
  32090. #endif /* #ifndef SQLITE_OMIT_WAL */
  32091. /*
  32092. ** Cleans up the mapped region of the specified file, if any.
  32093. */
  32094. #if SQLITE_MAX_MMAP_SIZE>0
  32095. static int winUnmapfile(winFile *pFile){
  32096. assert( pFile!=0 );
  32097. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  32098. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  32099. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  32100. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  32101. if( pFile->pMapRegion ){
  32102. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  32103. pFile->lastErrno = osGetLastError();
  32104. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  32105. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  32106. pFile->pMapRegion));
  32107. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32108. "winUnmap1", pFile->zPath);
  32109. }
  32110. pFile->pMapRegion = 0;
  32111. pFile->mmapSize = 0;
  32112. pFile->mmapSizeActual = 0;
  32113. }
  32114. if( pFile->hMap!=NULL ){
  32115. if( !osCloseHandle(pFile->hMap) ){
  32116. pFile->lastErrno = osGetLastError();
  32117. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  32118. osGetCurrentProcessId(), pFile, pFile->hMap));
  32119. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32120. "winUnmap2", pFile->zPath);
  32121. }
  32122. pFile->hMap = NULL;
  32123. }
  32124. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32125. osGetCurrentProcessId(), pFile));
  32126. return SQLITE_OK;
  32127. }
  32128. /*
  32129. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32130. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32131. ** there already exists a mapping for this file, and there are still
  32132. ** outstanding xFetch() references to it, this function is a no-op.
  32133. **
  32134. ** If parameter nByte is non-negative, then it is the requested size of
  32135. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32136. ** requested size is the size of the file on disk. The actual size of the
  32137. ** created mapping is either the requested size or the value configured
  32138. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  32139. **
  32140. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32141. ** recreated as a result of outstanding references) or an SQLite error
  32142. ** code otherwise.
  32143. */
  32144. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  32145. sqlite3_int64 nMap = nByte;
  32146. int rc;
  32147. assert( nMap>=0 || pFd->nFetchOut==0 );
  32148. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  32149. osGetCurrentProcessId(), pFd, nByte));
  32150. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32151. if( nMap<0 ){
  32152. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  32153. if( rc ){
  32154. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  32155. osGetCurrentProcessId(), pFd));
  32156. return SQLITE_IOERR_FSTAT;
  32157. }
  32158. }
  32159. if( nMap>pFd->mmapSizeMax ){
  32160. nMap = pFd->mmapSizeMax;
  32161. }
  32162. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  32163. if( nMap==0 && pFd->mmapSize>0 ){
  32164. winUnmapfile(pFd);
  32165. }
  32166. if( nMap!=pFd->mmapSize ){
  32167. void *pNew = 0;
  32168. DWORD protect = PAGE_READONLY;
  32169. DWORD flags = FILE_MAP_READ;
  32170. winUnmapfile(pFd);
  32171. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  32172. protect = PAGE_READWRITE;
  32173. flags |= FILE_MAP_WRITE;
  32174. }
  32175. #if SQLITE_OS_WINRT
  32176. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  32177. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32178. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  32179. (DWORD)((nMap>>32) & 0xffffffff),
  32180. (DWORD)(nMap & 0xffffffff), NULL);
  32181. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32182. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  32183. (DWORD)((nMap>>32) & 0xffffffff),
  32184. (DWORD)(nMap & 0xffffffff), NULL);
  32185. #endif
  32186. if( pFd->hMap==NULL ){
  32187. pFd->lastErrno = osGetLastError();
  32188. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32189. "winMapfile", pFd->zPath);
  32190. /* Log the error, but continue normal operation using xRead/xWrite */
  32191. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
  32192. osGetCurrentProcessId(), pFd));
  32193. return SQLITE_OK;
  32194. }
  32195. assert( (nMap % winSysInfo.dwPageSize)==0 );
  32196. #if SQLITE_OS_WINRT
  32197. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, nMap);
  32198. #else
  32199. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  32200. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  32201. #endif
  32202. if( pNew==NULL ){
  32203. osCloseHandle(pFd->hMap);
  32204. pFd->hMap = NULL;
  32205. pFd->lastErrno = osGetLastError();
  32206. winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32207. "winMapfile", pFd->zPath);
  32208. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
  32209. osGetCurrentProcessId(), pFd));
  32210. return SQLITE_OK;
  32211. }
  32212. pFd->pMapRegion = pNew;
  32213. pFd->mmapSize = nMap;
  32214. pFd->mmapSizeActual = nMap;
  32215. }
  32216. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32217. osGetCurrentProcessId(), pFd));
  32218. return SQLITE_OK;
  32219. }
  32220. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32221. /*
  32222. ** If possible, return a pointer to a mapping of file fd starting at offset
  32223. ** iOff. The mapping must be valid for at least nAmt bytes.
  32224. **
  32225. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32226. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32227. ** Finally, if an error does occur, return an SQLite error code. The final
  32228. ** value of *pp is undefined in this case.
  32229. **
  32230. ** If this function does return a pointer, the caller must eventually
  32231. ** release the reference by calling winUnfetch().
  32232. */
  32233. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32234. #if SQLITE_MAX_MMAP_SIZE>0
  32235. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32236. #endif
  32237. *pp = 0;
  32238. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  32239. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  32240. #if SQLITE_MAX_MMAP_SIZE>0
  32241. if( pFd->mmapSizeMax>0 ){
  32242. if( pFd->pMapRegion==0 ){
  32243. int rc = winMapfile(pFd, -1);
  32244. if( rc!=SQLITE_OK ){
  32245. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  32246. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32247. return rc;
  32248. }
  32249. }
  32250. if( pFd->mmapSize >= iOff+nAmt ){
  32251. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32252. pFd->nFetchOut++;
  32253. }
  32254. }
  32255. #endif
  32256. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  32257. osGetCurrentProcessId(), fd, pp, *pp));
  32258. return SQLITE_OK;
  32259. }
  32260. /*
  32261. ** If the third argument is non-NULL, then this function releases a
  32262. ** reference obtained by an earlier call to winFetch(). The second
  32263. ** argument passed to this function must be the same as the corresponding
  32264. ** argument that was passed to the winFetch() invocation.
  32265. **
  32266. ** Or, if the third argument is NULL, then this function is being called
  32267. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32268. ** may now be invalid and should be unmapped.
  32269. */
  32270. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32271. #if SQLITE_MAX_MMAP_SIZE>0
  32272. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32273. /* If p==0 (unmap the entire file) then there must be no outstanding
  32274. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32275. ** then there must be at least one outstanding. */
  32276. assert( (p==0)==(pFd->nFetchOut==0) );
  32277. /* If p!=0, it must match the iOff value. */
  32278. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32279. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  32280. osGetCurrentProcessId(), pFd, iOff, p));
  32281. if( p ){
  32282. pFd->nFetchOut--;
  32283. }else{
  32284. /* FIXME: If Windows truly always prevents truncating or deleting a
  32285. ** file while a mapping is held, then the following winUnmapfile() call
  32286. ** is unnecessary can can be omitted - potentially improving
  32287. ** performance. */
  32288. winUnmapfile(pFd);
  32289. }
  32290. assert( pFd->nFetchOut>=0 );
  32291. #endif
  32292. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32293. osGetCurrentProcessId(), fd));
  32294. return SQLITE_OK;
  32295. }
  32296. /*
  32297. ** Here ends the implementation of all sqlite3_file methods.
  32298. **
  32299. ********************** End sqlite3_file Methods *******************************
  32300. ******************************************************************************/
  32301. /*
  32302. ** This vector defines all the methods that can operate on an
  32303. ** sqlite3_file for win32.
  32304. */
  32305. static const sqlite3_io_methods winIoMethod = {
  32306. 3, /* iVersion */
  32307. winClose, /* xClose */
  32308. winRead, /* xRead */
  32309. winWrite, /* xWrite */
  32310. winTruncate, /* xTruncate */
  32311. winSync, /* xSync */
  32312. winFileSize, /* xFileSize */
  32313. winLock, /* xLock */
  32314. winUnlock, /* xUnlock */
  32315. winCheckReservedLock, /* xCheckReservedLock */
  32316. winFileControl, /* xFileControl */
  32317. winSectorSize, /* xSectorSize */
  32318. winDeviceCharacteristics, /* xDeviceCharacteristics */
  32319. winShmMap, /* xShmMap */
  32320. winShmLock, /* xShmLock */
  32321. winShmBarrier, /* xShmBarrier */
  32322. winShmUnmap, /* xShmUnmap */
  32323. winFetch, /* xFetch */
  32324. winUnfetch /* xUnfetch */
  32325. };
  32326. /****************************************************************************
  32327. **************************** sqlite3_vfs methods ****************************
  32328. **
  32329. ** This division contains the implementation of methods on the
  32330. ** sqlite3_vfs object.
  32331. */
  32332. /*
  32333. ** Convert a UTF-8 filename into whatever form the underlying
  32334. ** operating system wants filenames in. Space to hold the result
  32335. ** is obtained from malloc and must be freed by the calling
  32336. ** function.
  32337. */
  32338. static void *convertUtf8Filename(const char *zFilename){
  32339. void *zConverted = 0;
  32340. if( isNT() ){
  32341. zConverted = utf8ToUnicode(zFilename);
  32342. }
  32343. #ifdef SQLITE_WIN32_HAS_ANSI
  32344. else{
  32345. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  32346. }
  32347. #endif
  32348. /* caller will handle out of memory */
  32349. return zConverted;
  32350. }
  32351. /*
  32352. ** Create a temporary file name in zBuf. zBuf must be big enough to
  32353. ** hold at pVfs->mxPathname characters.
  32354. */
  32355. static int getTempname(int nBuf, char *zBuf){
  32356. static char zChars[] =
  32357. "abcdefghijklmnopqrstuvwxyz"
  32358. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  32359. "0123456789";
  32360. size_t i, j;
  32361. int nTempPath;
  32362. char zTempPath[MAX_PATH+2];
  32363. /* It's odd to simulate an io-error here, but really this is just
  32364. ** using the io-error infrastructure to test that SQLite handles this
  32365. ** function failing.
  32366. */
  32367. SimulateIOError( return SQLITE_IOERR );
  32368. memset(zTempPath, 0, MAX_PATH+2);
  32369. if( sqlite3_temp_directory ){
  32370. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  32371. }
  32372. #if !SQLITE_OS_WINRT
  32373. else if( isNT() ){
  32374. char *zMulti;
  32375. WCHAR zWidePath[MAX_PATH];
  32376. osGetTempPathW(MAX_PATH-30, zWidePath);
  32377. zMulti = unicodeToUtf8(zWidePath);
  32378. if( zMulti ){
  32379. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  32380. sqlite3_free(zMulti);
  32381. }else{
  32382. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32383. return SQLITE_IOERR_NOMEM;
  32384. }
  32385. }
  32386. #ifdef SQLITE_WIN32_HAS_ANSI
  32387. else{
  32388. char *zUtf8;
  32389. char zMbcsPath[MAX_PATH];
  32390. osGetTempPathA(MAX_PATH-30, zMbcsPath);
  32391. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  32392. if( zUtf8 ){
  32393. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  32394. sqlite3_free(zUtf8);
  32395. }else{
  32396. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32397. return SQLITE_IOERR_NOMEM;
  32398. }
  32399. }
  32400. #endif
  32401. #endif
  32402. /* Check that the output buffer is large enough for the temporary file
  32403. ** name. If it is not, return SQLITE_ERROR.
  32404. */
  32405. nTempPath = sqlite3Strlen30(zTempPath);
  32406. if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  32407. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  32408. return SQLITE_ERROR;
  32409. }
  32410. for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
  32411. zTempPath[i] = 0;
  32412. sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
  32413. "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
  32414. zTempPath);
  32415. j = sqlite3Strlen30(zBuf);
  32416. sqlite3_randomness(15, &zBuf[j]);
  32417. for(i=0; i<15; i++, j++){
  32418. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  32419. }
  32420. zBuf[j] = 0;
  32421. zBuf[j+1] = 0;
  32422. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  32423. return SQLITE_OK;
  32424. }
  32425. /*
  32426. ** Return TRUE if the named file is really a directory. Return false if
  32427. ** it is something other than a directory, or if there is any kind of memory
  32428. ** allocation failure.
  32429. */
  32430. static int winIsDir(const void *zConverted){
  32431. DWORD attr;
  32432. int rc = 0;
  32433. DWORD lastErrno;
  32434. if( isNT() ){
  32435. int cnt = 0;
  32436. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  32437. memset(&sAttrData, 0, sizeof(sAttrData));
  32438. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  32439. GetFileExInfoStandard,
  32440. &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
  32441. if( !rc ){
  32442. return 0; /* Invalid name? */
  32443. }
  32444. attr = sAttrData.dwFileAttributes;
  32445. #if SQLITE_OS_WINCE==0
  32446. }else{
  32447. attr = osGetFileAttributesA((char*)zConverted);
  32448. #endif
  32449. }
  32450. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  32451. }
  32452. /*
  32453. ** Open a file.
  32454. */
  32455. static int winOpen(
  32456. sqlite3_vfs *pVfs, /* Not used */
  32457. const char *zName, /* Name of the file (UTF-8) */
  32458. sqlite3_file *id, /* Write the SQLite file handle here */
  32459. int flags, /* Open mode flags */
  32460. int *pOutFlags /* Status return flags */
  32461. ){
  32462. HANDLE h;
  32463. DWORD lastErrno;
  32464. DWORD dwDesiredAccess;
  32465. DWORD dwShareMode;
  32466. DWORD dwCreationDisposition;
  32467. DWORD dwFlagsAndAttributes = 0;
  32468. #if SQLITE_OS_WINCE
  32469. int isTemp = 0;
  32470. #endif
  32471. winFile *pFile = (winFile*)id;
  32472. void *zConverted; /* Filename in OS encoding */
  32473. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  32474. int cnt = 0;
  32475. /* If argument zPath is a NULL pointer, this function is required to open
  32476. ** a temporary file. Use this buffer to store the file name in.
  32477. */
  32478. char zTmpname[MAX_PATH+2]; /* Buffer used to create temp filename */
  32479. int rc = SQLITE_OK; /* Function Return Code */
  32480. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  32481. int eType = flags&0xFFFFFF00; /* Type of file to open */
  32482. #endif
  32483. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  32484. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  32485. int isCreate = (flags & SQLITE_OPEN_CREATE);
  32486. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  32487. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  32488. #ifndef NDEBUG
  32489. int isOpenJournal = (isCreate && (
  32490. eType==SQLITE_OPEN_MASTER_JOURNAL
  32491. || eType==SQLITE_OPEN_MAIN_JOURNAL
  32492. || eType==SQLITE_OPEN_WAL
  32493. ));
  32494. #endif
  32495. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  32496. zUtf8Name, id, flags, pOutFlags));
  32497. /* Check the following statements are true:
  32498. **
  32499. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  32500. ** (b) if CREATE is set, then READWRITE must also be set, and
  32501. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  32502. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  32503. */
  32504. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  32505. assert(isCreate==0 || isReadWrite);
  32506. assert(isExclusive==0 || isCreate);
  32507. assert(isDelete==0 || isCreate);
  32508. /* The main DB, main journal, WAL file and master journal are never
  32509. ** automatically deleted. Nor are they ever temporary files. */
  32510. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  32511. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  32512. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  32513. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  32514. /* Assert that the upper layer has set one of the "file-type" flags. */
  32515. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  32516. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  32517. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  32518. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  32519. );
  32520. assert( pFile!=0 );
  32521. memset(pFile, 0, sizeof(winFile));
  32522. pFile->h = INVALID_HANDLE_VALUE;
  32523. #if SQLITE_OS_WINRT
  32524. if( !sqlite3_temp_directory ){
  32525. sqlite3_log(SQLITE_ERROR,
  32526. "sqlite3_temp_directory variable should be set for WinRT");
  32527. }
  32528. #endif
  32529. /* If the second argument to this function is NULL, generate a
  32530. ** temporary file name to use
  32531. */
  32532. if( !zUtf8Name ){
  32533. assert(isDelete && !isOpenJournal);
  32534. memset(zTmpname, 0, MAX_PATH+2);
  32535. rc = getTempname(MAX_PATH+2, zTmpname);
  32536. if( rc!=SQLITE_OK ){
  32537. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  32538. return rc;
  32539. }
  32540. zUtf8Name = zTmpname;
  32541. }
  32542. /* Database filenames are double-zero terminated if they are not
  32543. ** URIs with parameters. Hence, they can always be passed into
  32544. ** sqlite3_uri_parameter().
  32545. */
  32546. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  32547. zUtf8Name[strlen(zUtf8Name)+1]==0 );
  32548. /* Convert the filename to the system encoding. */
  32549. zConverted = convertUtf8Filename(zUtf8Name);
  32550. if( zConverted==0 ){
  32551. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  32552. return SQLITE_IOERR_NOMEM;
  32553. }
  32554. if( winIsDir(zConverted) ){
  32555. sqlite3_free(zConverted);
  32556. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  32557. return SQLITE_CANTOPEN_ISDIR;
  32558. }
  32559. if( isReadWrite ){
  32560. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  32561. }else{
  32562. dwDesiredAccess = GENERIC_READ;
  32563. }
  32564. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  32565. ** created. SQLite doesn't use it to indicate "exclusive access"
  32566. ** as it is usually understood.
  32567. */
  32568. if( isExclusive ){
  32569. /* Creates a new file, only if it does not already exist. */
  32570. /* If the file exists, it fails. */
  32571. dwCreationDisposition = CREATE_NEW;
  32572. }else if( isCreate ){
  32573. /* Open existing file, or create if it doesn't exist */
  32574. dwCreationDisposition = OPEN_ALWAYS;
  32575. }else{
  32576. /* Opens a file, only if it exists. */
  32577. dwCreationDisposition = OPEN_EXISTING;
  32578. }
  32579. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  32580. if( isDelete ){
  32581. #if SQLITE_OS_WINCE
  32582. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  32583. isTemp = 1;
  32584. #else
  32585. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  32586. | FILE_ATTRIBUTE_HIDDEN
  32587. | FILE_FLAG_DELETE_ON_CLOSE;
  32588. #endif
  32589. }else{
  32590. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  32591. }
  32592. /* Reports from the internet are that performance is always
  32593. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  32594. #if SQLITE_OS_WINCE
  32595. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  32596. #endif
  32597. if( isNT() ){
  32598. #if SQLITE_OS_WINRT
  32599. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  32600. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  32601. extendedParameters.dwFileAttributes =
  32602. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  32603. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  32604. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  32605. extendedParameters.lpSecurityAttributes = NULL;
  32606. extendedParameters.hTemplateFile = NULL;
  32607. while( (h = osCreateFile2((LPCWSTR)zConverted,
  32608. dwDesiredAccess,
  32609. dwShareMode,
  32610. dwCreationDisposition,
  32611. &extendedParameters))==INVALID_HANDLE_VALUE &&
  32612. retryIoerr(&cnt, &lastErrno) ){
  32613. /* Noop */
  32614. }
  32615. #else
  32616. while( (h = osCreateFileW((LPCWSTR)zConverted,
  32617. dwDesiredAccess,
  32618. dwShareMode, NULL,
  32619. dwCreationDisposition,
  32620. dwFlagsAndAttributes,
  32621. NULL))==INVALID_HANDLE_VALUE &&
  32622. retryIoerr(&cnt, &lastErrno) ){
  32623. /* Noop */
  32624. }
  32625. #endif
  32626. }
  32627. #ifdef SQLITE_WIN32_HAS_ANSI
  32628. else{
  32629. while( (h = osCreateFileA((LPCSTR)zConverted,
  32630. dwDesiredAccess,
  32631. dwShareMode, NULL,
  32632. dwCreationDisposition,
  32633. dwFlagsAndAttributes,
  32634. NULL))==INVALID_HANDLE_VALUE &&
  32635. retryIoerr(&cnt, &lastErrno) ){
  32636. /* Noop */
  32637. }
  32638. }
  32639. #endif
  32640. logIoerr(cnt);
  32641. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  32642. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  32643. if( h==INVALID_HANDLE_VALUE ){
  32644. pFile->lastErrno = lastErrno;
  32645. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  32646. sqlite3_free(zConverted);
  32647. if( isReadWrite && !isExclusive ){
  32648. return winOpen(pVfs, zName, id,
  32649. ((flags|SQLITE_OPEN_READONLY) &
  32650. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  32651. pOutFlags);
  32652. }else{
  32653. return SQLITE_CANTOPEN_BKPT;
  32654. }
  32655. }
  32656. if( pOutFlags ){
  32657. if( isReadWrite ){
  32658. *pOutFlags = SQLITE_OPEN_READWRITE;
  32659. }else{
  32660. *pOutFlags = SQLITE_OPEN_READONLY;
  32661. }
  32662. }
  32663. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  32664. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  32665. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  32666. #if SQLITE_OS_WINCE
  32667. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  32668. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  32669. ){
  32670. osCloseHandle(h);
  32671. sqlite3_free(zConverted);
  32672. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  32673. return rc;
  32674. }
  32675. if( isTemp ){
  32676. pFile->zDeleteOnClose = zConverted;
  32677. }else
  32678. #endif
  32679. {
  32680. sqlite3_free(zConverted);
  32681. }
  32682. pFile->pMethod = &winIoMethod;
  32683. pFile->pVfs = pVfs;
  32684. pFile->h = h;
  32685. if( isReadonly ){
  32686. pFile->ctrlFlags |= WINFILE_RDONLY;
  32687. }
  32688. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  32689. pFile->ctrlFlags |= WINFILE_PSOW;
  32690. }
  32691. pFile->lastErrno = NO_ERROR;
  32692. pFile->zPath = zName;
  32693. #if SQLITE_MAX_MMAP_SIZE>0
  32694. pFile->hMap = NULL;
  32695. pFile->pMapRegion = 0;
  32696. pFile->mmapSize = 0;
  32697. pFile->mmapSizeActual = 0;
  32698. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  32699. #endif
  32700. OpenCounter(+1);
  32701. return rc;
  32702. }
  32703. /*
  32704. ** Delete the named file.
  32705. **
  32706. ** Note that Windows does not allow a file to be deleted if some other
  32707. ** process has it open. Sometimes a virus scanner or indexing program
  32708. ** will open a journal file shortly after it is created in order to do
  32709. ** whatever it does. While this other process is holding the
  32710. ** file open, we will be unable to delete it. To work around this
  32711. ** problem, we delay 100 milliseconds and try to delete again. Up
  32712. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  32713. ** up and returning an error.
  32714. */
  32715. static int winDelete(
  32716. sqlite3_vfs *pVfs, /* Not used on win32 */
  32717. const char *zFilename, /* Name of file to delete */
  32718. int syncDir /* Not used on win32 */
  32719. ){
  32720. int cnt = 0;
  32721. int rc;
  32722. DWORD attr;
  32723. DWORD lastErrno;
  32724. void *zConverted;
  32725. UNUSED_PARAMETER(pVfs);
  32726. UNUSED_PARAMETER(syncDir);
  32727. SimulateIOError(return SQLITE_IOERR_DELETE);
  32728. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  32729. zConverted = convertUtf8Filename(zFilename);
  32730. if( zConverted==0 ){
  32731. return SQLITE_IOERR_NOMEM;
  32732. }
  32733. if( isNT() ){
  32734. do {
  32735. #if SQLITE_OS_WINRT
  32736. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  32737. memset(&sAttrData, 0, sizeof(sAttrData));
  32738. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  32739. &sAttrData) ){
  32740. attr = sAttrData.dwFileAttributes;
  32741. }else{
  32742. lastErrno = osGetLastError();
  32743. if( lastErrno==ERROR_FILE_NOT_FOUND
  32744. || lastErrno==ERROR_PATH_NOT_FOUND ){
  32745. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  32746. }else{
  32747. rc = SQLITE_ERROR;
  32748. }
  32749. break;
  32750. }
  32751. #else
  32752. attr = osGetFileAttributesW(zConverted);
  32753. #endif
  32754. if ( attr==INVALID_FILE_ATTRIBUTES ){
  32755. lastErrno = osGetLastError();
  32756. if( lastErrno==ERROR_FILE_NOT_FOUND
  32757. || lastErrno==ERROR_PATH_NOT_FOUND ){
  32758. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  32759. }else{
  32760. rc = SQLITE_ERROR;
  32761. }
  32762. break;
  32763. }
  32764. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  32765. rc = SQLITE_ERROR; /* Files only. */
  32766. break;
  32767. }
  32768. if ( osDeleteFileW(zConverted) ){
  32769. rc = SQLITE_OK; /* Deleted OK. */
  32770. break;
  32771. }
  32772. if ( !retryIoerr(&cnt, &lastErrno) ){
  32773. rc = SQLITE_ERROR; /* No more retries. */
  32774. break;
  32775. }
  32776. } while(1);
  32777. }
  32778. #ifdef SQLITE_WIN32_HAS_ANSI
  32779. else{
  32780. do {
  32781. attr = osGetFileAttributesA(zConverted);
  32782. if ( attr==INVALID_FILE_ATTRIBUTES ){
  32783. lastErrno = osGetLastError();
  32784. if( lastErrno==ERROR_FILE_NOT_FOUND
  32785. || lastErrno==ERROR_PATH_NOT_FOUND ){
  32786. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  32787. }else{
  32788. rc = SQLITE_ERROR;
  32789. }
  32790. break;
  32791. }
  32792. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  32793. rc = SQLITE_ERROR; /* Files only. */
  32794. break;
  32795. }
  32796. if ( osDeleteFileA(zConverted) ){
  32797. rc = SQLITE_OK; /* Deleted OK. */
  32798. break;
  32799. }
  32800. if ( !retryIoerr(&cnt, &lastErrno) ){
  32801. rc = SQLITE_ERROR; /* No more retries. */
  32802. break;
  32803. }
  32804. } while(1);
  32805. }
  32806. #endif
  32807. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  32808. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
  32809. "winDelete", zFilename);
  32810. }else{
  32811. logIoerr(cnt);
  32812. }
  32813. sqlite3_free(zConverted);
  32814. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  32815. return rc;
  32816. }
  32817. /*
  32818. ** Check the existence and status of a file.
  32819. */
  32820. static int winAccess(
  32821. sqlite3_vfs *pVfs, /* Not used on win32 */
  32822. const char *zFilename, /* Name of file to check */
  32823. int flags, /* Type of test to make on this file */
  32824. int *pResOut /* OUT: Result */
  32825. ){
  32826. DWORD attr;
  32827. int rc = 0;
  32828. DWORD lastErrno;
  32829. void *zConverted;
  32830. UNUSED_PARAMETER(pVfs);
  32831. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  32832. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  32833. zFilename, flags, pResOut));
  32834. zConverted = convertUtf8Filename(zFilename);
  32835. if( zConverted==0 ){
  32836. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  32837. return SQLITE_IOERR_NOMEM;
  32838. }
  32839. if( isNT() ){
  32840. int cnt = 0;
  32841. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  32842. memset(&sAttrData, 0, sizeof(sAttrData));
  32843. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  32844. GetFileExInfoStandard,
  32845. &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
  32846. if( rc ){
  32847. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  32848. ** as if it does not exist.
  32849. */
  32850. if( flags==SQLITE_ACCESS_EXISTS
  32851. && sAttrData.nFileSizeHigh==0
  32852. && sAttrData.nFileSizeLow==0 ){
  32853. attr = INVALID_FILE_ATTRIBUTES;
  32854. }else{
  32855. attr = sAttrData.dwFileAttributes;
  32856. }
  32857. }else{
  32858. logIoerr(cnt);
  32859. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  32860. winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
  32861. sqlite3_free(zConverted);
  32862. return SQLITE_IOERR_ACCESS;
  32863. }else{
  32864. attr = INVALID_FILE_ATTRIBUTES;
  32865. }
  32866. }
  32867. }
  32868. #ifdef SQLITE_WIN32_HAS_ANSI
  32869. else{
  32870. attr = osGetFileAttributesA((char*)zConverted);
  32871. }
  32872. #endif
  32873. sqlite3_free(zConverted);
  32874. switch( flags ){
  32875. case SQLITE_ACCESS_READ:
  32876. case SQLITE_ACCESS_EXISTS:
  32877. rc = attr!=INVALID_FILE_ATTRIBUTES;
  32878. break;
  32879. case SQLITE_ACCESS_READWRITE:
  32880. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  32881. (attr & FILE_ATTRIBUTE_READONLY)==0;
  32882. break;
  32883. default:
  32884. assert(!"Invalid flags argument");
  32885. }
  32886. *pResOut = rc;
  32887. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  32888. zFilename, pResOut, *pResOut));
  32889. return SQLITE_OK;
  32890. }
  32891. /*
  32892. ** Returns non-zero if the specified path name should be used verbatim. If
  32893. ** non-zero is returned from this function, the calling function must simply
  32894. ** use the provided path name verbatim -OR- resolve it into a full path name
  32895. ** using the GetFullPathName Win32 API function (if available).
  32896. */
  32897. static BOOL winIsVerbatimPathname(
  32898. const char *zPathname
  32899. ){
  32900. /*
  32901. ** If the path name starts with a forward slash or a backslash, it is either
  32902. ** a legal UNC name, a volume relative path, or an absolute path name in the
  32903. ** "Unix" format on Windows. There is no easy way to differentiate between
  32904. ** the final two cases; therefore, we return the safer return value of TRUE
  32905. ** so that callers of this function will simply use it verbatim.
  32906. */
  32907. if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
  32908. return TRUE;
  32909. }
  32910. /*
  32911. ** If the path name starts with a letter and a colon it is either a volume
  32912. ** relative path or an absolute path. Callers of this function must not
  32913. ** attempt to treat it as a relative path name (i.e. they should simply use
  32914. ** it verbatim).
  32915. */
  32916. if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
  32917. return TRUE;
  32918. }
  32919. /*
  32920. ** If we get to this point, the path name should almost certainly be a purely
  32921. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  32922. */
  32923. return FALSE;
  32924. }
  32925. /*
  32926. ** Turn a relative pathname into a full pathname. Write the full
  32927. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  32928. ** bytes in size.
  32929. */
  32930. static int winFullPathname(
  32931. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  32932. const char *zRelative, /* Possibly relative input path */
  32933. int nFull, /* Size of output buffer in bytes */
  32934. char *zFull /* Output buffer */
  32935. ){
  32936. #if defined(__CYGWIN__)
  32937. SimulateIOError( return SQLITE_ERROR );
  32938. UNUSED_PARAMETER(nFull);
  32939. assert( pVfs->mxPathname>=MAX_PATH );
  32940. assert( nFull>=pVfs->mxPathname );
  32941. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32942. /*
  32943. ** NOTE: We are dealing with a relative path name and the data
  32944. ** directory has been set. Therefore, use it as the basis
  32945. ** for converting the relative path name to an absolute
  32946. ** one by prepending the data directory and a slash.
  32947. */
  32948. char zOut[MAX_PATH+1];
  32949. memset(zOut, 0, MAX_PATH+1);
  32950. cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  32951. MAX_PATH+1);
  32952. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  32953. sqlite3_data_directory, zOut);
  32954. }else{
  32955. cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
  32956. }
  32957. return SQLITE_OK;
  32958. #endif
  32959. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  32960. SimulateIOError( return SQLITE_ERROR );
  32961. /* WinCE has no concept of a relative pathname, or so I am told. */
  32962. /* WinRT has no way to convert a relative path to an absolute one. */
  32963. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32964. /*
  32965. ** NOTE: We are dealing with a relative path name and the data
  32966. ** directory has been set. Therefore, use it as the basis
  32967. ** for converting the relative path name to an absolute
  32968. ** one by prepending the data directory and a backslash.
  32969. */
  32970. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  32971. sqlite3_data_directory, zRelative);
  32972. }else{
  32973. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  32974. }
  32975. return SQLITE_OK;
  32976. #endif
  32977. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  32978. DWORD nByte;
  32979. void *zConverted;
  32980. char *zOut;
  32981. /* If this path name begins with "/X:", where "X" is any alphabetic
  32982. ** character, discard the initial "/" from the pathname.
  32983. */
  32984. if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
  32985. zRelative++;
  32986. }
  32987. /* It's odd to simulate an io-error here, but really this is just
  32988. ** using the io-error infrastructure to test that SQLite handles this
  32989. ** function failing. This function could fail if, for example, the
  32990. ** current working directory has been unlinked.
  32991. */
  32992. SimulateIOError( return SQLITE_ERROR );
  32993. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32994. /*
  32995. ** NOTE: We are dealing with a relative path name and the data
  32996. ** directory has been set. Therefore, use it as the basis
  32997. ** for converting the relative path name to an absolute
  32998. ** one by prepending the data directory and a backslash.
  32999. */
  33000. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  33001. sqlite3_data_directory, zRelative);
  33002. return SQLITE_OK;
  33003. }
  33004. zConverted = convertUtf8Filename(zRelative);
  33005. if( zConverted==0 ){
  33006. return SQLITE_IOERR_NOMEM;
  33007. }
  33008. if( isNT() ){
  33009. LPWSTR zTemp;
  33010. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  33011. if( nByte==0 ){
  33012. winLogError(SQLITE_ERROR, osGetLastError(),
  33013. "GetFullPathNameW1", zConverted);
  33014. sqlite3_free(zConverted);
  33015. return SQLITE_CANTOPEN_FULLPATH;
  33016. }
  33017. nByte += 3;
  33018. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33019. if( zTemp==0 ){
  33020. sqlite3_free(zConverted);
  33021. return SQLITE_IOERR_NOMEM;
  33022. }
  33023. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  33024. if( nByte==0 ){
  33025. winLogError(SQLITE_ERROR, osGetLastError(),
  33026. "GetFullPathNameW2", zConverted);
  33027. sqlite3_free(zConverted);
  33028. sqlite3_free(zTemp);
  33029. return SQLITE_CANTOPEN_FULLPATH;
  33030. }
  33031. sqlite3_free(zConverted);
  33032. zOut = unicodeToUtf8(zTemp);
  33033. sqlite3_free(zTemp);
  33034. }
  33035. #ifdef SQLITE_WIN32_HAS_ANSI
  33036. else{
  33037. char *zTemp;
  33038. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  33039. if( nByte==0 ){
  33040. winLogError(SQLITE_ERROR, osGetLastError(),
  33041. "GetFullPathNameA1", zConverted);
  33042. sqlite3_free(zConverted);
  33043. return SQLITE_CANTOPEN_FULLPATH;
  33044. }
  33045. nByte += 3;
  33046. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33047. if( zTemp==0 ){
  33048. sqlite3_free(zConverted);
  33049. return SQLITE_IOERR_NOMEM;
  33050. }
  33051. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  33052. if( nByte==0 ){
  33053. winLogError(SQLITE_ERROR, osGetLastError(),
  33054. "GetFullPathNameA2", zConverted);
  33055. sqlite3_free(zConverted);
  33056. sqlite3_free(zTemp);
  33057. return SQLITE_CANTOPEN_FULLPATH;
  33058. }
  33059. sqlite3_free(zConverted);
  33060. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33061. sqlite3_free(zTemp);
  33062. }
  33063. #endif
  33064. if( zOut ){
  33065. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  33066. sqlite3_free(zOut);
  33067. return SQLITE_OK;
  33068. }else{
  33069. return SQLITE_IOERR_NOMEM;
  33070. }
  33071. #endif
  33072. }
  33073. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33074. /*
  33075. ** Interfaces for opening a shared library, finding entry points
  33076. ** within the shared library, and closing the shared library.
  33077. */
  33078. /*
  33079. ** Interfaces for opening a shared library, finding entry points
  33080. ** within the shared library, and closing the shared library.
  33081. */
  33082. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  33083. HANDLE h;
  33084. void *zConverted = convertUtf8Filename(zFilename);
  33085. UNUSED_PARAMETER(pVfs);
  33086. if( zConverted==0 ){
  33087. return 0;
  33088. }
  33089. if( isNT() ){
  33090. #if SQLITE_OS_WINRT
  33091. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  33092. #else
  33093. h = osLoadLibraryW((LPCWSTR)zConverted);
  33094. #endif
  33095. }
  33096. #ifdef SQLITE_WIN32_HAS_ANSI
  33097. else{
  33098. h = osLoadLibraryA((char*)zConverted);
  33099. }
  33100. #endif
  33101. sqlite3_free(zConverted);
  33102. return (void*)h;
  33103. }
  33104. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  33105. UNUSED_PARAMETER(pVfs);
  33106. getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  33107. }
  33108. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  33109. UNUSED_PARAMETER(pVfs);
  33110. return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
  33111. }
  33112. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  33113. UNUSED_PARAMETER(pVfs);
  33114. osFreeLibrary((HANDLE)pHandle);
  33115. }
  33116. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  33117. #define winDlOpen 0
  33118. #define winDlError 0
  33119. #define winDlSym 0
  33120. #define winDlClose 0
  33121. #endif
  33122. /*
  33123. ** Write up to nBuf bytes of randomness into zBuf.
  33124. */
  33125. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33126. int n = 0;
  33127. UNUSED_PARAMETER(pVfs);
  33128. #if defined(SQLITE_TEST)
  33129. n = nBuf;
  33130. memset(zBuf, 0, nBuf);
  33131. #else
  33132. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  33133. SYSTEMTIME x;
  33134. osGetSystemTime(&x);
  33135. memcpy(&zBuf[n], &x, sizeof(x));
  33136. n += sizeof(x);
  33137. }
  33138. if( sizeof(DWORD)<=nBuf-n ){
  33139. DWORD pid = osGetCurrentProcessId();
  33140. memcpy(&zBuf[n], &pid, sizeof(pid));
  33141. n += sizeof(pid);
  33142. }
  33143. #if SQLITE_OS_WINRT
  33144. if( sizeof(ULONGLONG)<=nBuf-n ){
  33145. ULONGLONG cnt = osGetTickCount64();
  33146. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33147. n += sizeof(cnt);
  33148. }
  33149. #else
  33150. if( sizeof(DWORD)<=nBuf-n ){
  33151. DWORD cnt = osGetTickCount();
  33152. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33153. n += sizeof(cnt);
  33154. }
  33155. #endif
  33156. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  33157. LARGE_INTEGER i;
  33158. osQueryPerformanceCounter(&i);
  33159. memcpy(&zBuf[n], &i, sizeof(i));
  33160. n += sizeof(i);
  33161. }
  33162. #endif
  33163. return n;
  33164. }
  33165. /*
  33166. ** Sleep for a little while. Return the amount of time slept.
  33167. */
  33168. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  33169. sqlite3_win32_sleep((microsec+999)/1000);
  33170. UNUSED_PARAMETER(pVfs);
  33171. return ((microsec+999)/1000)*1000;
  33172. }
  33173. /*
  33174. ** The following variable, if set to a non-zero value, is interpreted as
  33175. ** the number of seconds since 1970 and is used to set the result of
  33176. ** sqlite3OsCurrentTime() during testing.
  33177. */
  33178. #ifdef SQLITE_TEST
  33179. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  33180. #endif
  33181. /*
  33182. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  33183. ** the current time and date as a Julian Day number times 86_400_000. In
  33184. ** other words, write into *piNow the number of milliseconds since the Julian
  33185. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  33186. ** proleptic Gregorian calendar.
  33187. **
  33188. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  33189. ** cannot be found.
  33190. */
  33191. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  33192. /* FILETIME structure is a 64-bit value representing the number of
  33193. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  33194. */
  33195. FILETIME ft;
  33196. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  33197. #ifdef SQLITE_TEST
  33198. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  33199. #endif
  33200. /* 2^32 - to avoid use of LL and warnings in gcc */
  33201. static const sqlite3_int64 max32BitValue =
  33202. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  33203. (sqlite3_int64)294967296;
  33204. #if SQLITE_OS_WINCE
  33205. SYSTEMTIME time;
  33206. osGetSystemTime(&time);
  33207. /* if SystemTimeToFileTime() fails, it returns zero. */
  33208. if (!osSystemTimeToFileTime(&time,&ft)){
  33209. return SQLITE_ERROR;
  33210. }
  33211. #else
  33212. osGetSystemTimeAsFileTime( &ft );
  33213. #endif
  33214. *piNow = winFiletimeEpoch +
  33215. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  33216. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  33217. #ifdef SQLITE_TEST
  33218. if( sqlite3_current_time ){
  33219. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  33220. }
  33221. #endif
  33222. UNUSED_PARAMETER(pVfs);
  33223. return SQLITE_OK;
  33224. }
  33225. /*
  33226. ** Find the current time (in Universal Coordinated Time). Write the
  33227. ** current time and date as a Julian Day number into *prNow and
  33228. ** return 0. Return 1 if the time and date cannot be found.
  33229. */
  33230. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  33231. int rc;
  33232. sqlite3_int64 i;
  33233. rc = winCurrentTimeInt64(pVfs, &i);
  33234. if( !rc ){
  33235. *prNow = i/86400000.0;
  33236. }
  33237. return rc;
  33238. }
  33239. /*
  33240. ** The idea is that this function works like a combination of
  33241. ** GetLastError() and FormatMessage() on Windows (or errno and
  33242. ** strerror_r() on Unix). After an error is returned by an OS
  33243. ** function, SQLite calls this function with zBuf pointing to
  33244. ** a buffer of nBuf bytes. The OS layer should populate the
  33245. ** buffer with a nul-terminated UTF-8 encoded error message
  33246. ** describing the last IO error to have occurred within the calling
  33247. ** thread.
  33248. **
  33249. ** If the error message is too large for the supplied buffer,
  33250. ** it should be truncated. The return value of xGetLastError
  33251. ** is zero if the error message fits in the buffer, or non-zero
  33252. ** otherwise (if the message was truncated). If non-zero is returned,
  33253. ** then it is not necessary to include the nul-terminator character
  33254. ** in the output buffer.
  33255. **
  33256. ** Not supplying an error message will have no adverse effect
  33257. ** on SQLite. It is fine to have an implementation that never
  33258. ** returns an error message:
  33259. **
  33260. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33261. ** assert(zBuf[0]=='\0');
  33262. ** return 0;
  33263. ** }
  33264. **
  33265. ** However if an error message is supplied, it will be incorporated
  33266. ** by sqlite into the error message available to the user using
  33267. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  33268. */
  33269. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33270. UNUSED_PARAMETER(pVfs);
  33271. return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
  33272. }
  33273. /*
  33274. ** Initialize and deinitialize the operating system interface.
  33275. */
  33276. SQLITE_API int sqlite3_os_init(void){
  33277. static sqlite3_vfs winVfs = {
  33278. 3, /* iVersion */
  33279. sizeof(winFile), /* szOsFile */
  33280. MAX_PATH, /* mxPathname */
  33281. 0, /* pNext */
  33282. "win32", /* zName */
  33283. 0, /* pAppData */
  33284. winOpen, /* xOpen */
  33285. winDelete, /* xDelete */
  33286. winAccess, /* xAccess */
  33287. winFullPathname, /* xFullPathname */
  33288. winDlOpen, /* xDlOpen */
  33289. winDlError, /* xDlError */
  33290. winDlSym, /* xDlSym */
  33291. winDlClose, /* xDlClose */
  33292. winRandomness, /* xRandomness */
  33293. winSleep, /* xSleep */
  33294. winCurrentTime, /* xCurrentTime */
  33295. winGetLastError, /* xGetLastError */
  33296. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  33297. winSetSystemCall, /* xSetSystemCall */
  33298. winGetSystemCall, /* xGetSystemCall */
  33299. winNextSystemCall, /* xNextSystemCall */
  33300. };
  33301. /* Double-check that the aSyscall[] array has been constructed
  33302. ** correctly. See ticket [bb3a86e890c8e96ab] */
  33303. assert( ArraySize(aSyscall)==74 );
  33304. /* get memory map allocation granularity */
  33305. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  33306. #if SQLITE_OS_WINRT
  33307. osGetNativeSystemInfo(&winSysInfo);
  33308. #else
  33309. osGetSystemInfo(&winSysInfo);
  33310. #endif
  33311. assert( winSysInfo.dwAllocationGranularity>0 );
  33312. assert( winSysInfo.dwPageSize>0 );
  33313. sqlite3_vfs_register(&winVfs, 1);
  33314. return SQLITE_OK;
  33315. }
  33316. SQLITE_API int sqlite3_os_end(void){
  33317. #if SQLITE_OS_WINRT
  33318. if( sleepObj!=NULL ){
  33319. osCloseHandle(sleepObj);
  33320. sleepObj = NULL;
  33321. }
  33322. #endif
  33323. return SQLITE_OK;
  33324. }
  33325. #endif /* SQLITE_OS_WIN */
  33326. /************** End of os_win.c **********************************************/
  33327. /************** Begin file bitvec.c ******************************************/
  33328. /*
  33329. ** 2008 February 16
  33330. **
  33331. ** The author disclaims copyright to this source code. In place of
  33332. ** a legal notice, here is a blessing:
  33333. **
  33334. ** May you do good and not evil.
  33335. ** May you find forgiveness for yourself and forgive others.
  33336. ** May you share freely, never taking more than you give.
  33337. **
  33338. *************************************************************************
  33339. ** This file implements an object that represents a fixed-length
  33340. ** bitmap. Bits are numbered starting with 1.
  33341. **
  33342. ** A bitmap is used to record which pages of a database file have been
  33343. ** journalled during a transaction, or which pages have the "dont-write"
  33344. ** property. Usually only a few pages are meet either condition.
  33345. ** So the bitmap is usually sparse and has low cardinality.
  33346. ** But sometimes (for example when during a DROP of a large table) most
  33347. ** or all of the pages in a database can get journalled. In those cases,
  33348. ** the bitmap becomes dense with high cardinality. The algorithm needs
  33349. ** to handle both cases well.
  33350. **
  33351. ** The size of the bitmap is fixed when the object is created.
  33352. **
  33353. ** All bits are clear when the bitmap is created. Individual bits
  33354. ** may be set or cleared one at a time.
  33355. **
  33356. ** Test operations are about 100 times more common that set operations.
  33357. ** Clear operations are exceedingly rare. There are usually between
  33358. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  33359. ** sometimes grow into tens of thousands or larger. The size of the
  33360. ** Bitvec object is the number of pages in the database file at the
  33361. ** start of a transaction, and is thus usually less than a few thousand,
  33362. ** but can be as large as 2 billion for a really big database.
  33363. */
  33364. /* Size of the Bitvec structure in bytes. */
  33365. #define BITVEC_SZ 512
  33366. /* Round the union size down to the nearest pointer boundary, since that's how
  33367. ** it will be aligned within the Bitvec struct. */
  33368. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  33369. /* Type of the array "element" for the bitmap representation.
  33370. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  33371. ** Setting this to the "natural word" size of your CPU may improve
  33372. ** performance. */
  33373. #define BITVEC_TELEM u8
  33374. /* Size, in bits, of the bitmap element. */
  33375. #define BITVEC_SZELEM 8
  33376. /* Number of elements in a bitmap array. */
  33377. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  33378. /* Number of bits in the bitmap array. */
  33379. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  33380. /* Number of u32 values in hash table. */
  33381. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  33382. /* Maximum number of entries in hash table before
  33383. ** sub-dividing and re-hashing. */
  33384. #define BITVEC_MXHASH (BITVEC_NINT/2)
  33385. /* Hashing function for the aHash representation.
  33386. ** Empirical testing showed that the *37 multiplier
  33387. ** (an arbitrary prime)in the hash function provided
  33388. ** no fewer collisions than the no-op *1. */
  33389. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  33390. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  33391. /*
  33392. ** A bitmap is an instance of the following structure.
  33393. **
  33394. ** This bitmap records the existence of zero or more bits
  33395. ** with values between 1 and iSize, inclusive.
  33396. **
  33397. ** There are three possible representations of the bitmap.
  33398. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  33399. ** bitmap. The least significant bit is bit 1.
  33400. **
  33401. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  33402. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  33403. **
  33404. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  33405. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  33406. ** handles up to iDivisor separate values of i. apSub[0] holds
  33407. ** values between 1 and iDivisor. apSub[1] holds values between
  33408. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  33409. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  33410. ** to hold deal with values between 1 and iDivisor.
  33411. */
  33412. struct Bitvec {
  33413. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  33414. u32 nSet; /* Number of bits that are set - only valid for aHash
  33415. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  33416. ** this would be 125. */
  33417. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  33418. /* Should >=0 for apSub element. */
  33419. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  33420. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  33421. union {
  33422. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  33423. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  33424. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  33425. } u;
  33426. };
  33427. /*
  33428. ** Create a new bitmap object able to handle bits between 0 and iSize,
  33429. ** inclusive. Return a pointer to the new object. Return NULL if
  33430. ** malloc fails.
  33431. */
  33432. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  33433. Bitvec *p;
  33434. assert( sizeof(*p)==BITVEC_SZ );
  33435. p = sqlite3MallocZero( sizeof(*p) );
  33436. if( p ){
  33437. p->iSize = iSize;
  33438. }
  33439. return p;
  33440. }
  33441. /*
  33442. ** Check to see if the i-th bit is set. Return true or false.
  33443. ** If p is NULL (if the bitmap has not been created) or if
  33444. ** i is out of range, then return false.
  33445. */
  33446. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  33447. if( p==0 ) return 0;
  33448. if( i>p->iSize || i==0 ) return 0;
  33449. i--;
  33450. while( p->iDivisor ){
  33451. u32 bin = i/p->iDivisor;
  33452. i = i%p->iDivisor;
  33453. p = p->u.apSub[bin];
  33454. if (!p) {
  33455. return 0;
  33456. }
  33457. }
  33458. if( p->iSize<=BITVEC_NBIT ){
  33459. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  33460. } else{
  33461. u32 h = BITVEC_HASH(i++);
  33462. while( p->u.aHash[h] ){
  33463. if( p->u.aHash[h]==i ) return 1;
  33464. h = (h+1) % BITVEC_NINT;
  33465. }
  33466. return 0;
  33467. }
  33468. }
  33469. /*
  33470. ** Set the i-th bit. Return 0 on success and an error code if
  33471. ** anything goes wrong.
  33472. **
  33473. ** This routine might cause sub-bitmaps to be allocated. Failing
  33474. ** to get the memory needed to hold the sub-bitmap is the only
  33475. ** that can go wrong with an insert, assuming p and i are valid.
  33476. **
  33477. ** The calling function must ensure that p is a valid Bitvec object
  33478. ** and that the value for "i" is within range of the Bitvec object.
  33479. ** Otherwise the behavior is undefined.
  33480. */
  33481. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  33482. u32 h;
  33483. if( p==0 ) return SQLITE_OK;
  33484. assert( i>0 );
  33485. assert( i<=p->iSize );
  33486. i--;
  33487. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  33488. u32 bin = i/p->iDivisor;
  33489. i = i%p->iDivisor;
  33490. if( p->u.apSub[bin]==0 ){
  33491. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  33492. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  33493. }
  33494. p = p->u.apSub[bin];
  33495. }
  33496. if( p->iSize<=BITVEC_NBIT ){
  33497. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  33498. return SQLITE_OK;
  33499. }
  33500. h = BITVEC_HASH(i++);
  33501. /* if there wasn't a hash collision, and this doesn't */
  33502. /* completely fill the hash, then just add it without */
  33503. /* worring about sub-dividing and re-hashing. */
  33504. if( !p->u.aHash[h] ){
  33505. if (p->nSet<(BITVEC_NINT-1)) {
  33506. goto bitvec_set_end;
  33507. } else {
  33508. goto bitvec_set_rehash;
  33509. }
  33510. }
  33511. /* there was a collision, check to see if it's already */
  33512. /* in hash, if not, try to find a spot for it */
  33513. do {
  33514. if( p->u.aHash[h]==i ) return SQLITE_OK;
  33515. h++;
  33516. if( h>=BITVEC_NINT ) h = 0;
  33517. } while( p->u.aHash[h] );
  33518. /* we didn't find it in the hash. h points to the first */
  33519. /* available free spot. check to see if this is going to */
  33520. /* make our hash too "full". */
  33521. bitvec_set_rehash:
  33522. if( p->nSet>=BITVEC_MXHASH ){
  33523. unsigned int j;
  33524. int rc;
  33525. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  33526. if( aiValues==0 ){
  33527. return SQLITE_NOMEM;
  33528. }else{
  33529. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  33530. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  33531. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  33532. rc = sqlite3BitvecSet(p, i);
  33533. for(j=0; j<BITVEC_NINT; j++){
  33534. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  33535. }
  33536. sqlite3StackFree(0, aiValues);
  33537. return rc;
  33538. }
  33539. }
  33540. bitvec_set_end:
  33541. p->nSet++;
  33542. p->u.aHash[h] = i;
  33543. return SQLITE_OK;
  33544. }
  33545. /*
  33546. ** Clear the i-th bit.
  33547. **
  33548. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  33549. ** that BitvecClear can use to rebuilt its hash table.
  33550. */
  33551. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  33552. if( p==0 ) return;
  33553. assert( i>0 );
  33554. i--;
  33555. while( p->iDivisor ){
  33556. u32 bin = i/p->iDivisor;
  33557. i = i%p->iDivisor;
  33558. p = p->u.apSub[bin];
  33559. if (!p) {
  33560. return;
  33561. }
  33562. }
  33563. if( p->iSize<=BITVEC_NBIT ){
  33564. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  33565. }else{
  33566. unsigned int j;
  33567. u32 *aiValues = pBuf;
  33568. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  33569. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  33570. p->nSet = 0;
  33571. for(j=0; j<BITVEC_NINT; j++){
  33572. if( aiValues[j] && aiValues[j]!=(i+1) ){
  33573. u32 h = BITVEC_HASH(aiValues[j]-1);
  33574. p->nSet++;
  33575. while( p->u.aHash[h] ){
  33576. h++;
  33577. if( h>=BITVEC_NINT ) h = 0;
  33578. }
  33579. p->u.aHash[h] = aiValues[j];
  33580. }
  33581. }
  33582. }
  33583. }
  33584. /*
  33585. ** Destroy a bitmap object. Reclaim all memory used.
  33586. */
  33587. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  33588. if( p==0 ) return;
  33589. if( p->iDivisor ){
  33590. unsigned int i;
  33591. for(i=0; i<BITVEC_NPTR; i++){
  33592. sqlite3BitvecDestroy(p->u.apSub[i]);
  33593. }
  33594. }
  33595. sqlite3_free(p);
  33596. }
  33597. /*
  33598. ** Return the value of the iSize parameter specified when Bitvec *p
  33599. ** was created.
  33600. */
  33601. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  33602. return p->iSize;
  33603. }
  33604. #ifndef SQLITE_OMIT_BUILTIN_TEST
  33605. /*
  33606. ** Let V[] be an array of unsigned characters sufficient to hold
  33607. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  33608. ** Then the following macros can be used to set, clear, or test
  33609. ** individual bits within V.
  33610. */
  33611. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  33612. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  33613. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  33614. /*
  33615. ** This routine runs an extensive test of the Bitvec code.
  33616. **
  33617. ** The input is an array of integers that acts as a program
  33618. ** to test the Bitvec. The integers are opcodes followed
  33619. ** by 0, 1, or 3 operands, depending on the opcode. Another
  33620. ** opcode follows immediately after the last operand.
  33621. **
  33622. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  33623. ** "halt" opcode and causes the test to end.
  33624. **
  33625. ** 0 Halt and return the number of errors
  33626. ** 1 N S X Set N bits beginning with S and incrementing by X
  33627. ** 2 N S X Clear N bits beginning with S and incrementing by X
  33628. ** 3 N Set N randomly chosen bits
  33629. ** 4 N Clear N randomly chosen bits
  33630. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  33631. **
  33632. ** The opcodes 1 through 4 perform set and clear operations are performed
  33633. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  33634. ** Opcode 5 works on the linear array only, not on the Bitvec.
  33635. ** Opcode 5 is used to deliberately induce a fault in order to
  33636. ** confirm that error detection works.
  33637. **
  33638. ** At the conclusion of the test the linear array is compared
  33639. ** against the Bitvec object. If there are any differences,
  33640. ** an error is returned. If they are the same, zero is returned.
  33641. **
  33642. ** If a memory allocation error occurs, return -1.
  33643. */
  33644. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  33645. Bitvec *pBitvec = 0;
  33646. unsigned char *pV = 0;
  33647. int rc = -1;
  33648. int i, nx, pc, op;
  33649. void *pTmpSpace;
  33650. /* Allocate the Bitvec to be tested and a linear array of
  33651. ** bits to act as the reference */
  33652. pBitvec = sqlite3BitvecCreate( sz );
  33653. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  33654. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  33655. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  33656. /* NULL pBitvec tests */
  33657. sqlite3BitvecSet(0, 1);
  33658. sqlite3BitvecClear(0, 1, pTmpSpace);
  33659. /* Run the program */
  33660. pc = 0;
  33661. while( (op = aOp[pc])!=0 ){
  33662. switch( op ){
  33663. case 1:
  33664. case 2:
  33665. case 5: {
  33666. nx = 4;
  33667. i = aOp[pc+2] - 1;
  33668. aOp[pc+2] += aOp[pc+3];
  33669. break;
  33670. }
  33671. case 3:
  33672. case 4:
  33673. default: {
  33674. nx = 2;
  33675. sqlite3_randomness(sizeof(i), &i);
  33676. break;
  33677. }
  33678. }
  33679. if( (--aOp[pc+1]) > 0 ) nx = 0;
  33680. pc += nx;
  33681. i = (i & 0x7fffffff)%sz;
  33682. if( (op & 1)!=0 ){
  33683. SETBIT(pV, (i+1));
  33684. if( op!=5 ){
  33685. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  33686. }
  33687. }else{
  33688. CLEARBIT(pV, (i+1));
  33689. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  33690. }
  33691. }
  33692. /* Test to make sure the linear array exactly matches the
  33693. ** Bitvec object. Start with the assumption that they do
  33694. ** match (rc==0). Change rc to non-zero if a discrepancy
  33695. ** is found.
  33696. */
  33697. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  33698. + sqlite3BitvecTest(pBitvec, 0)
  33699. + (sqlite3BitvecSize(pBitvec) - sz);
  33700. for(i=1; i<=sz; i++){
  33701. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  33702. rc = i;
  33703. break;
  33704. }
  33705. }
  33706. /* Free allocated structure */
  33707. bitvec_end:
  33708. sqlite3_free(pTmpSpace);
  33709. sqlite3_free(pV);
  33710. sqlite3BitvecDestroy(pBitvec);
  33711. return rc;
  33712. }
  33713. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  33714. /************** End of bitvec.c **********************************************/
  33715. /************** Begin file pcache.c ******************************************/
  33716. /*
  33717. ** 2008 August 05
  33718. **
  33719. ** The author disclaims copyright to this source code. In place of
  33720. ** a legal notice, here is a blessing:
  33721. **
  33722. ** May you do good and not evil.
  33723. ** May you find forgiveness for yourself and forgive others.
  33724. ** May you share freely, never taking more than you give.
  33725. **
  33726. *************************************************************************
  33727. ** This file implements that page cache.
  33728. */
  33729. /*
  33730. ** A complete page cache is an instance of this structure.
  33731. */
  33732. struct PCache {
  33733. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  33734. PgHdr *pSynced; /* Last synced page in dirty page list */
  33735. int nRef; /* Number of referenced pages */
  33736. int szCache; /* Configured cache size */
  33737. int szPage; /* Size of every page in this cache */
  33738. int szExtra; /* Size of extra space for each page */
  33739. int bPurgeable; /* True if pages are on backing store */
  33740. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  33741. void *pStress; /* Argument to xStress */
  33742. sqlite3_pcache *pCache; /* Pluggable cache module */
  33743. PgHdr *pPage1; /* Reference to page 1 */
  33744. };
  33745. /*
  33746. ** Some of the assert() macros in this code are too expensive to run
  33747. ** even during normal debugging. Use them only rarely on long-running
  33748. ** tests. Enable the expensive asserts using the
  33749. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  33750. */
  33751. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  33752. # define expensive_assert(X) assert(X)
  33753. #else
  33754. # define expensive_assert(X)
  33755. #endif
  33756. /********************************** Linked List Management ********************/
  33757. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  33758. /*
  33759. ** Check that the pCache->pSynced variable is set correctly. If it
  33760. ** is not, either fail an assert or return zero. Otherwise, return
  33761. ** non-zero. This is only used in debugging builds, as follows:
  33762. **
  33763. ** expensive_assert( pcacheCheckSynced(pCache) );
  33764. */
  33765. static int pcacheCheckSynced(PCache *pCache){
  33766. PgHdr *p;
  33767. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  33768. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  33769. }
  33770. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  33771. }
  33772. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  33773. /*
  33774. ** Remove page pPage from the list of dirty pages.
  33775. */
  33776. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  33777. PCache *p = pPage->pCache;
  33778. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  33779. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  33780. /* Update the PCache1.pSynced variable if necessary. */
  33781. if( p->pSynced==pPage ){
  33782. PgHdr *pSynced = pPage->pDirtyPrev;
  33783. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  33784. pSynced = pSynced->pDirtyPrev;
  33785. }
  33786. p->pSynced = pSynced;
  33787. }
  33788. if( pPage->pDirtyNext ){
  33789. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  33790. }else{
  33791. assert( pPage==p->pDirtyTail );
  33792. p->pDirtyTail = pPage->pDirtyPrev;
  33793. }
  33794. if( pPage->pDirtyPrev ){
  33795. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  33796. }else{
  33797. assert( pPage==p->pDirty );
  33798. p->pDirty = pPage->pDirtyNext;
  33799. }
  33800. pPage->pDirtyNext = 0;
  33801. pPage->pDirtyPrev = 0;
  33802. expensive_assert( pcacheCheckSynced(p) );
  33803. }
  33804. /*
  33805. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  33806. ** pPage).
  33807. */
  33808. static void pcacheAddToDirtyList(PgHdr *pPage){
  33809. PCache *p = pPage->pCache;
  33810. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  33811. pPage->pDirtyNext = p->pDirty;
  33812. if( pPage->pDirtyNext ){
  33813. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  33814. pPage->pDirtyNext->pDirtyPrev = pPage;
  33815. }
  33816. p->pDirty = pPage;
  33817. if( !p->pDirtyTail ){
  33818. p->pDirtyTail = pPage;
  33819. }
  33820. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  33821. p->pSynced = pPage;
  33822. }
  33823. expensive_assert( pcacheCheckSynced(p) );
  33824. }
  33825. /*
  33826. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  33827. ** being used for an in-memory database, this function is a no-op.
  33828. */
  33829. static void pcacheUnpin(PgHdr *p){
  33830. PCache *pCache = p->pCache;
  33831. if( pCache->bPurgeable ){
  33832. if( p->pgno==1 ){
  33833. pCache->pPage1 = 0;
  33834. }
  33835. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  33836. }
  33837. }
  33838. /*************************************************** General Interfaces ******
  33839. **
  33840. ** Initialize and shutdown the page cache subsystem. Neither of these
  33841. ** functions are threadsafe.
  33842. */
  33843. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  33844. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  33845. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  33846. ** built-in default page cache is used instead of the application defined
  33847. ** page cache. */
  33848. sqlite3PCacheSetDefault();
  33849. }
  33850. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  33851. }
  33852. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  33853. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  33854. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  33855. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  33856. }
  33857. }
  33858. /*
  33859. ** Return the size in bytes of a PCache object.
  33860. */
  33861. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  33862. /*
  33863. ** Create a new PCache object. Storage space to hold the object
  33864. ** has already been allocated and is passed in as the p pointer.
  33865. ** The caller discovers how much space needs to be allocated by
  33866. ** calling sqlite3PcacheSize().
  33867. */
  33868. SQLITE_PRIVATE void sqlite3PcacheOpen(
  33869. int szPage, /* Size of every page */
  33870. int szExtra, /* Extra space associated with each page */
  33871. int bPurgeable, /* True if pages are on backing store */
  33872. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  33873. void *pStress, /* Argument to xStress */
  33874. PCache *p /* Preallocated space for the PCache */
  33875. ){
  33876. memset(p, 0, sizeof(PCache));
  33877. p->szPage = szPage;
  33878. p->szExtra = szExtra;
  33879. p->bPurgeable = bPurgeable;
  33880. p->xStress = xStress;
  33881. p->pStress = pStress;
  33882. p->szCache = 100;
  33883. }
  33884. /*
  33885. ** Change the page size for PCache object. The caller must ensure that there
  33886. ** are no outstanding page references when this function is called.
  33887. */
  33888. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  33889. assert( pCache->nRef==0 && pCache->pDirty==0 );
  33890. if( pCache->pCache ){
  33891. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  33892. pCache->pCache = 0;
  33893. pCache->pPage1 = 0;
  33894. }
  33895. pCache->szPage = szPage;
  33896. }
  33897. /*
  33898. ** Compute the number of pages of cache requested.
  33899. */
  33900. static int numberOfCachePages(PCache *p){
  33901. if( p->szCache>=0 ){
  33902. return p->szCache;
  33903. }else{
  33904. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  33905. }
  33906. }
  33907. /*
  33908. ** Try to obtain a page from the cache.
  33909. */
  33910. SQLITE_PRIVATE int sqlite3PcacheFetch(
  33911. PCache *pCache, /* Obtain the page from this cache */
  33912. Pgno pgno, /* Page number to obtain */
  33913. int createFlag, /* If true, create page if it does not exist already */
  33914. PgHdr **ppPage /* Write the page here */
  33915. ){
  33916. sqlite3_pcache_page *pPage = 0;
  33917. PgHdr *pPgHdr = 0;
  33918. int eCreate;
  33919. assert( pCache!=0 );
  33920. assert( createFlag==1 || createFlag==0 );
  33921. assert( pgno>0 );
  33922. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  33923. ** allocate it now.
  33924. */
  33925. if( !pCache->pCache && createFlag ){
  33926. sqlite3_pcache *p;
  33927. p = sqlite3GlobalConfig.pcache2.xCreate(
  33928. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  33929. );
  33930. if( !p ){
  33931. return SQLITE_NOMEM;
  33932. }
  33933. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  33934. pCache->pCache = p;
  33935. }
  33936. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  33937. if( pCache->pCache ){
  33938. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  33939. }
  33940. if( !pPage && eCreate==1 ){
  33941. PgHdr *pPg;
  33942. /* Find a dirty page to write-out and recycle. First try to find a
  33943. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  33944. ** cleared), but if that is not possible settle for any other
  33945. ** unreferenced dirty page.
  33946. */
  33947. expensive_assert( pcacheCheckSynced(pCache) );
  33948. for(pPg=pCache->pSynced;
  33949. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  33950. pPg=pPg->pDirtyPrev
  33951. );
  33952. pCache->pSynced = pPg;
  33953. if( !pPg ){
  33954. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  33955. }
  33956. if( pPg ){
  33957. int rc;
  33958. #ifdef SQLITE_LOG_CACHE_SPILL
  33959. sqlite3_log(SQLITE_FULL,
  33960. "spill page %d making room for %d - cache used: %d/%d",
  33961. pPg->pgno, pgno,
  33962. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  33963. numberOfCachePages(pCache));
  33964. #endif
  33965. rc = pCache->xStress(pCache->pStress, pPg);
  33966. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  33967. return rc;
  33968. }
  33969. }
  33970. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  33971. }
  33972. if( pPage ){
  33973. pPgHdr = (PgHdr *)pPage->pExtra;
  33974. if( !pPgHdr->pPage ){
  33975. memset(pPgHdr, 0, sizeof(PgHdr));
  33976. pPgHdr->pPage = pPage;
  33977. pPgHdr->pData = pPage->pBuf;
  33978. pPgHdr->pExtra = (void *)&pPgHdr[1];
  33979. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  33980. pPgHdr->pCache = pCache;
  33981. pPgHdr->pgno = pgno;
  33982. }
  33983. assert( pPgHdr->pCache==pCache );
  33984. assert( pPgHdr->pgno==pgno );
  33985. assert( pPgHdr->pData==pPage->pBuf );
  33986. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  33987. if( 0==pPgHdr->nRef ){
  33988. pCache->nRef++;
  33989. }
  33990. pPgHdr->nRef++;
  33991. if( pgno==1 ){
  33992. pCache->pPage1 = pPgHdr;
  33993. }
  33994. }
  33995. *ppPage = pPgHdr;
  33996. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  33997. }
  33998. /*
  33999. ** Decrement the reference count on a page. If the page is clean and the
  34000. ** reference count drops to 0, then it is made elible for recycling.
  34001. */
  34002. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  34003. assert( p->nRef>0 );
  34004. p->nRef--;
  34005. if( p->nRef==0 ){
  34006. PCache *pCache = p->pCache;
  34007. pCache->nRef--;
  34008. if( (p->flags&PGHDR_DIRTY)==0 ){
  34009. pcacheUnpin(p);
  34010. }else{
  34011. /* Move the page to the head of the dirty list. */
  34012. pcacheRemoveFromDirtyList(p);
  34013. pcacheAddToDirtyList(p);
  34014. }
  34015. }
  34016. }
  34017. /*
  34018. ** Increase the reference count of a supplied page by 1.
  34019. */
  34020. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  34021. assert(p->nRef>0);
  34022. p->nRef++;
  34023. }
  34024. /*
  34025. ** Drop a page from the cache. There must be exactly one reference to the
  34026. ** page. This function deletes that reference, so after it returns the
  34027. ** page pointed to by p is invalid.
  34028. */
  34029. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  34030. PCache *pCache;
  34031. assert( p->nRef==1 );
  34032. if( p->flags&PGHDR_DIRTY ){
  34033. pcacheRemoveFromDirtyList(p);
  34034. }
  34035. pCache = p->pCache;
  34036. pCache->nRef--;
  34037. if( p->pgno==1 ){
  34038. pCache->pPage1 = 0;
  34039. }
  34040. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  34041. }
  34042. /*
  34043. ** Make sure the page is marked as dirty. If it isn't dirty already,
  34044. ** make it so.
  34045. */
  34046. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  34047. p->flags &= ~PGHDR_DONT_WRITE;
  34048. assert( p->nRef>0 );
  34049. if( 0==(p->flags & PGHDR_DIRTY) ){
  34050. p->flags |= PGHDR_DIRTY;
  34051. pcacheAddToDirtyList( p);
  34052. }
  34053. }
  34054. /*
  34055. ** Make sure the page is marked as clean. If it isn't clean already,
  34056. ** make it so.
  34057. */
  34058. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  34059. if( (p->flags & PGHDR_DIRTY) ){
  34060. pcacheRemoveFromDirtyList(p);
  34061. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  34062. if( p->nRef==0 ){
  34063. pcacheUnpin(p);
  34064. }
  34065. }
  34066. }
  34067. /*
  34068. ** Make every page in the cache clean.
  34069. */
  34070. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  34071. PgHdr *p;
  34072. while( (p = pCache->pDirty)!=0 ){
  34073. sqlite3PcacheMakeClean(p);
  34074. }
  34075. }
  34076. /*
  34077. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  34078. */
  34079. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  34080. PgHdr *p;
  34081. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  34082. p->flags &= ~PGHDR_NEED_SYNC;
  34083. }
  34084. pCache->pSynced = pCache->pDirtyTail;
  34085. }
  34086. /*
  34087. ** Change the page number of page p to newPgno.
  34088. */
  34089. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  34090. PCache *pCache = p->pCache;
  34091. assert( p->nRef>0 );
  34092. assert( newPgno>0 );
  34093. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  34094. p->pgno = newPgno;
  34095. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  34096. pcacheRemoveFromDirtyList(p);
  34097. pcacheAddToDirtyList(p);
  34098. }
  34099. }
  34100. /*
  34101. ** Drop every cache entry whose page number is greater than "pgno". The
  34102. ** caller must ensure that there are no outstanding references to any pages
  34103. ** other than page 1 with a page number greater than pgno.
  34104. **
  34105. ** If there is a reference to page 1 and the pgno parameter passed to this
  34106. ** function is 0, then the data area associated with page 1 is zeroed, but
  34107. ** the page object is not dropped.
  34108. */
  34109. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  34110. if( pCache->pCache ){
  34111. PgHdr *p;
  34112. PgHdr *pNext;
  34113. for(p=pCache->pDirty; p; p=pNext){
  34114. pNext = p->pDirtyNext;
  34115. /* This routine never gets call with a positive pgno except right
  34116. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  34117. ** it must be that pgno==0.
  34118. */
  34119. assert( p->pgno>0 );
  34120. if( ALWAYS(p->pgno>pgno) ){
  34121. assert( p->flags&PGHDR_DIRTY );
  34122. sqlite3PcacheMakeClean(p);
  34123. }
  34124. }
  34125. if( pgno==0 && pCache->pPage1 ){
  34126. memset(pCache->pPage1->pData, 0, pCache->szPage);
  34127. pgno = 1;
  34128. }
  34129. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  34130. }
  34131. }
  34132. /*
  34133. ** Close a cache.
  34134. */
  34135. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  34136. if( pCache->pCache ){
  34137. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  34138. }
  34139. }
  34140. /*
  34141. ** Discard the contents of the cache.
  34142. */
  34143. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  34144. sqlite3PcacheTruncate(pCache, 0);
  34145. }
  34146. /*
  34147. ** Merge two lists of pages connected by pDirty and in pgno order.
  34148. ** Do not both fixing the pDirtyPrev pointers.
  34149. */
  34150. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  34151. PgHdr result, *pTail;
  34152. pTail = &result;
  34153. while( pA && pB ){
  34154. if( pA->pgno<pB->pgno ){
  34155. pTail->pDirty = pA;
  34156. pTail = pA;
  34157. pA = pA->pDirty;
  34158. }else{
  34159. pTail->pDirty = pB;
  34160. pTail = pB;
  34161. pB = pB->pDirty;
  34162. }
  34163. }
  34164. if( pA ){
  34165. pTail->pDirty = pA;
  34166. }else if( pB ){
  34167. pTail->pDirty = pB;
  34168. }else{
  34169. pTail->pDirty = 0;
  34170. }
  34171. return result.pDirty;
  34172. }
  34173. /*
  34174. ** Sort the list of pages in accending order by pgno. Pages are
  34175. ** connected by pDirty pointers. The pDirtyPrev pointers are
  34176. ** corrupted by this sort.
  34177. **
  34178. ** Since there cannot be more than 2^31 distinct pages in a database,
  34179. ** there cannot be more than 31 buckets required by the merge sorter.
  34180. ** One extra bucket is added to catch overflow in case something
  34181. ** ever changes to make the previous sentence incorrect.
  34182. */
  34183. #define N_SORT_BUCKET 32
  34184. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  34185. PgHdr *a[N_SORT_BUCKET], *p;
  34186. int i;
  34187. memset(a, 0, sizeof(a));
  34188. while( pIn ){
  34189. p = pIn;
  34190. pIn = p->pDirty;
  34191. p->pDirty = 0;
  34192. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  34193. if( a[i]==0 ){
  34194. a[i] = p;
  34195. break;
  34196. }else{
  34197. p = pcacheMergeDirtyList(a[i], p);
  34198. a[i] = 0;
  34199. }
  34200. }
  34201. if( NEVER(i==N_SORT_BUCKET-1) ){
  34202. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  34203. ** the input list. But that is impossible.
  34204. */
  34205. a[i] = pcacheMergeDirtyList(a[i], p);
  34206. }
  34207. }
  34208. p = a[0];
  34209. for(i=1; i<N_SORT_BUCKET; i++){
  34210. p = pcacheMergeDirtyList(p, a[i]);
  34211. }
  34212. return p;
  34213. }
  34214. /*
  34215. ** Return a list of all dirty pages in the cache, sorted by page number.
  34216. */
  34217. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  34218. PgHdr *p;
  34219. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  34220. p->pDirty = p->pDirtyNext;
  34221. }
  34222. return pcacheSortDirtyList(pCache->pDirty);
  34223. }
  34224. /*
  34225. ** Return the total number of referenced pages held by the cache.
  34226. */
  34227. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  34228. return pCache->nRef;
  34229. }
  34230. /*
  34231. ** Return the number of references to the page supplied as an argument.
  34232. */
  34233. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  34234. return p->nRef;
  34235. }
  34236. /*
  34237. ** Return the total number of pages in the cache.
  34238. */
  34239. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  34240. int nPage = 0;
  34241. if( pCache->pCache ){
  34242. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  34243. }
  34244. return nPage;
  34245. }
  34246. #ifdef SQLITE_TEST
  34247. /*
  34248. ** Get the suggested cache-size value.
  34249. */
  34250. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  34251. return numberOfCachePages(pCache);
  34252. }
  34253. #endif
  34254. /*
  34255. ** Set the suggested cache-size value.
  34256. */
  34257. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  34258. pCache->szCache = mxPage;
  34259. if( pCache->pCache ){
  34260. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  34261. numberOfCachePages(pCache));
  34262. }
  34263. }
  34264. /*
  34265. ** Free up as much memory as possible from the page cache.
  34266. */
  34267. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  34268. if( pCache->pCache ){
  34269. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  34270. }
  34271. }
  34272. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  34273. /*
  34274. ** For all dirty pages currently in the cache, invoke the specified
  34275. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  34276. ** defined.
  34277. */
  34278. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  34279. PgHdr *pDirty;
  34280. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  34281. xIter(pDirty);
  34282. }
  34283. }
  34284. #endif
  34285. /************** End of pcache.c **********************************************/
  34286. /************** Begin file pcache1.c *****************************************/
  34287. /*
  34288. ** 2008 November 05
  34289. **
  34290. ** The author disclaims copyright to this source code. In place of
  34291. ** a legal notice, here is a blessing:
  34292. **
  34293. ** May you do good and not evil.
  34294. ** May you find forgiveness for yourself and forgive others.
  34295. ** May you share freely, never taking more than you give.
  34296. **
  34297. *************************************************************************
  34298. **
  34299. ** This file implements the default page cache implementation (the
  34300. ** sqlite3_pcache interface). It also contains part of the implementation
  34301. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  34302. ** If the default page cache implementation is overriden, then neither of
  34303. ** these two features are available.
  34304. */
  34305. typedef struct PCache1 PCache1;
  34306. typedef struct PgHdr1 PgHdr1;
  34307. typedef struct PgFreeslot PgFreeslot;
  34308. typedef struct PGroup PGroup;
  34309. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  34310. ** of one or more PCaches that are able to recycle each others unpinned
  34311. ** pages when they are under memory pressure. A PGroup is an instance of
  34312. ** the following object.
  34313. **
  34314. ** This page cache implementation works in one of two modes:
  34315. **
  34316. ** (1) Every PCache is the sole member of its own PGroup. There is
  34317. ** one PGroup per PCache.
  34318. **
  34319. ** (2) There is a single global PGroup that all PCaches are a member
  34320. ** of.
  34321. **
  34322. ** Mode 1 uses more memory (since PCache instances are not able to rob
  34323. ** unused pages from other PCaches) but it also operates without a mutex,
  34324. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  34325. ** threadsafe, but recycles pages more efficiently.
  34326. **
  34327. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  34328. ** PGroup which is the pcache1.grp global variable and its mutex is
  34329. ** SQLITE_MUTEX_STATIC_LRU.
  34330. */
  34331. struct PGroup {
  34332. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  34333. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  34334. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  34335. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  34336. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  34337. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  34338. };
  34339. /* Each page cache is an instance of the following object. Every
  34340. ** open database file (including each in-memory database and each
  34341. ** temporary or transient database) has a single page cache which
  34342. ** is an instance of this object.
  34343. **
  34344. ** Pointers to structures of this type are cast and returned as
  34345. ** opaque sqlite3_pcache* handles.
  34346. */
  34347. struct PCache1 {
  34348. /* Cache configuration parameters. Page size (szPage) and the purgeable
  34349. ** flag (bPurgeable) are set when the cache is created. nMax may be
  34350. ** modified at any time by a call to the pcache1Cachesize() method.
  34351. ** The PGroup mutex must be held when accessing nMax.
  34352. */
  34353. PGroup *pGroup; /* PGroup this cache belongs to */
  34354. int szPage; /* Size of allocated pages in bytes */
  34355. int szExtra; /* Size of extra space in bytes */
  34356. int bPurgeable; /* True if cache is purgeable */
  34357. unsigned int nMin; /* Minimum number of pages reserved */
  34358. unsigned int nMax; /* Configured "cache_size" value */
  34359. unsigned int n90pct; /* nMax*9/10 */
  34360. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  34361. /* Hash table of all pages. The following variables may only be accessed
  34362. ** when the accessor is holding the PGroup mutex.
  34363. */
  34364. unsigned int nRecyclable; /* Number of pages in the LRU list */
  34365. unsigned int nPage; /* Total number of pages in apHash */
  34366. unsigned int nHash; /* Number of slots in apHash[] */
  34367. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  34368. };
  34369. /*
  34370. ** Each cache entry is represented by an instance of the following
  34371. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  34372. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  34373. ** in memory.
  34374. */
  34375. struct PgHdr1 {
  34376. sqlite3_pcache_page page;
  34377. unsigned int iKey; /* Key value (page number) */
  34378. PgHdr1 *pNext; /* Next in hash table chain */
  34379. PCache1 *pCache; /* Cache that currently owns this page */
  34380. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  34381. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  34382. };
  34383. /*
  34384. ** Free slots in the allocator used to divide up the buffer provided using
  34385. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  34386. */
  34387. struct PgFreeslot {
  34388. PgFreeslot *pNext; /* Next free slot */
  34389. };
  34390. /*
  34391. ** Global data used by this cache.
  34392. */
  34393. static SQLITE_WSD struct PCacheGlobal {
  34394. PGroup grp; /* The global PGroup for mode (2) */
  34395. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  34396. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  34397. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  34398. ** The nFreeSlot and pFree values do require mutex protection.
  34399. */
  34400. int isInit; /* True if initialized */
  34401. int szSlot; /* Size of each free slot */
  34402. int nSlot; /* The number of pcache slots */
  34403. int nReserve; /* Try to keep nFreeSlot above this */
  34404. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  34405. /* Above requires no mutex. Use mutex below for variable that follow. */
  34406. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  34407. PgFreeslot *pFree; /* Free page blocks */
  34408. int nFreeSlot; /* Number of unused pcache slots */
  34409. /* The following value requires a mutex to change. We skip the mutex on
  34410. ** reading because (1) most platforms read a 32-bit integer atomically and
  34411. ** (2) even if an incorrect value is read, no great harm is done since this
  34412. ** is really just an optimization. */
  34413. int bUnderPressure; /* True if low on PAGECACHE memory */
  34414. } pcache1_g;
  34415. /*
  34416. ** All code in this file should access the global structure above via the
  34417. ** alias "pcache1". This ensures that the WSD emulation is used when
  34418. ** compiling for systems that do not support real WSD.
  34419. */
  34420. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  34421. /*
  34422. ** Macros to enter and leave the PCache LRU mutex.
  34423. */
  34424. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  34425. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  34426. /******************************************************************************/
  34427. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  34428. /*
  34429. ** This function is called during initialization if a static buffer is
  34430. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  34431. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  34432. ** enough to contain 'n' buffers of 'sz' bytes each.
  34433. **
  34434. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  34435. ** to be serialized already. There is no need for further mutexing.
  34436. */
  34437. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  34438. if( pcache1.isInit ){
  34439. PgFreeslot *p;
  34440. sz = ROUNDDOWN8(sz);
  34441. pcache1.szSlot = sz;
  34442. pcache1.nSlot = pcache1.nFreeSlot = n;
  34443. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  34444. pcache1.pStart = pBuf;
  34445. pcache1.pFree = 0;
  34446. pcache1.bUnderPressure = 0;
  34447. while( n-- ){
  34448. p = (PgFreeslot*)pBuf;
  34449. p->pNext = pcache1.pFree;
  34450. pcache1.pFree = p;
  34451. pBuf = (void*)&((char*)pBuf)[sz];
  34452. }
  34453. pcache1.pEnd = pBuf;
  34454. }
  34455. }
  34456. /*
  34457. ** Malloc function used within this file to allocate space from the buffer
  34458. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  34459. ** such buffer exists or there is no space left in it, this function falls
  34460. ** back to sqlite3Malloc().
  34461. **
  34462. ** Multiple threads can run this routine at the same time. Global variables
  34463. ** in pcache1 need to be protected via mutex.
  34464. */
  34465. static void *pcache1Alloc(int nByte){
  34466. void *p = 0;
  34467. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  34468. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  34469. if( nByte<=pcache1.szSlot ){
  34470. sqlite3_mutex_enter(pcache1.mutex);
  34471. p = (PgHdr1 *)pcache1.pFree;
  34472. if( p ){
  34473. pcache1.pFree = pcache1.pFree->pNext;
  34474. pcache1.nFreeSlot--;
  34475. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  34476. assert( pcache1.nFreeSlot>=0 );
  34477. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  34478. }
  34479. sqlite3_mutex_leave(pcache1.mutex);
  34480. }
  34481. if( p==0 ){
  34482. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  34483. ** it from sqlite3Malloc instead.
  34484. */
  34485. p = sqlite3Malloc(nByte);
  34486. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  34487. if( p ){
  34488. int sz = sqlite3MallocSize(p);
  34489. sqlite3_mutex_enter(pcache1.mutex);
  34490. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  34491. sqlite3_mutex_leave(pcache1.mutex);
  34492. }
  34493. #endif
  34494. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  34495. }
  34496. return p;
  34497. }
  34498. /*
  34499. ** Free an allocated buffer obtained from pcache1Alloc().
  34500. */
  34501. static int pcache1Free(void *p){
  34502. int nFreed = 0;
  34503. if( p==0 ) return 0;
  34504. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  34505. PgFreeslot *pSlot;
  34506. sqlite3_mutex_enter(pcache1.mutex);
  34507. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  34508. pSlot = (PgFreeslot*)p;
  34509. pSlot->pNext = pcache1.pFree;
  34510. pcache1.pFree = pSlot;
  34511. pcache1.nFreeSlot++;
  34512. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  34513. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  34514. sqlite3_mutex_leave(pcache1.mutex);
  34515. }else{
  34516. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  34517. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  34518. nFreed = sqlite3MallocSize(p);
  34519. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  34520. sqlite3_mutex_enter(pcache1.mutex);
  34521. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  34522. sqlite3_mutex_leave(pcache1.mutex);
  34523. #endif
  34524. sqlite3_free(p);
  34525. }
  34526. return nFreed;
  34527. }
  34528. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  34529. /*
  34530. ** Return the size of a pcache allocation
  34531. */
  34532. static int pcache1MemSize(void *p){
  34533. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  34534. return pcache1.szSlot;
  34535. }else{
  34536. int iSize;
  34537. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  34538. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  34539. iSize = sqlite3MallocSize(p);
  34540. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  34541. return iSize;
  34542. }
  34543. }
  34544. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  34545. /*
  34546. ** Allocate a new page object initially associated with cache pCache.
  34547. */
  34548. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  34549. PgHdr1 *p = 0;
  34550. void *pPg;
  34551. /* The group mutex must be released before pcache1Alloc() is called. This
  34552. ** is because it may call sqlite3_release_memory(), which assumes that
  34553. ** this mutex is not held. */
  34554. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  34555. pcache1LeaveMutex(pCache->pGroup);
  34556. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  34557. pPg = pcache1Alloc(pCache->szPage);
  34558. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  34559. if( !pPg || !p ){
  34560. pcache1Free(pPg);
  34561. sqlite3_free(p);
  34562. pPg = 0;
  34563. }
  34564. #else
  34565. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  34566. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  34567. #endif
  34568. pcache1EnterMutex(pCache->pGroup);
  34569. if( pPg ){
  34570. p->page.pBuf = pPg;
  34571. p->page.pExtra = &p[1];
  34572. if( pCache->bPurgeable ){
  34573. pCache->pGroup->nCurrentPage++;
  34574. }
  34575. return p;
  34576. }
  34577. return 0;
  34578. }
  34579. /*
  34580. ** Free a page object allocated by pcache1AllocPage().
  34581. **
  34582. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  34583. ** that the current implementation happens to never call this routine
  34584. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  34585. */
  34586. static void pcache1FreePage(PgHdr1 *p){
  34587. if( ALWAYS(p) ){
  34588. PCache1 *pCache = p->pCache;
  34589. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  34590. pcache1Free(p->page.pBuf);
  34591. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  34592. sqlite3_free(p);
  34593. #endif
  34594. if( pCache->bPurgeable ){
  34595. pCache->pGroup->nCurrentPage--;
  34596. }
  34597. }
  34598. }
  34599. /*
  34600. ** Malloc function used by SQLite to obtain space from the buffer configured
  34601. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  34602. ** exists, this function falls back to sqlite3Malloc().
  34603. */
  34604. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  34605. return pcache1Alloc(sz);
  34606. }
  34607. /*
  34608. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  34609. */
  34610. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  34611. pcache1Free(p);
  34612. }
  34613. /*
  34614. ** Return true if it desirable to avoid allocating a new page cache
  34615. ** entry.
  34616. **
  34617. ** If memory was allocated specifically to the page cache using
  34618. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  34619. ** it is desirable to avoid allocating a new page cache entry because
  34620. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  34621. ** for all page cache needs and we should not need to spill the
  34622. ** allocation onto the heap.
  34623. **
  34624. ** Or, the heap is used for all page cache memory but the heap is
  34625. ** under memory pressure, then again it is desirable to avoid
  34626. ** allocating a new page cache entry in order to avoid stressing
  34627. ** the heap even further.
  34628. */
  34629. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  34630. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  34631. return pcache1.bUnderPressure;
  34632. }else{
  34633. return sqlite3HeapNearlyFull();
  34634. }
  34635. }
  34636. /******************************************************************************/
  34637. /******** General Implementation Functions ************************************/
  34638. /*
  34639. ** This function is used to resize the hash table used by the cache passed
  34640. ** as the first argument.
  34641. **
  34642. ** The PCache mutex must be held when this function is called.
  34643. */
  34644. static int pcache1ResizeHash(PCache1 *p){
  34645. PgHdr1 **apNew;
  34646. unsigned int nNew;
  34647. unsigned int i;
  34648. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  34649. nNew = p->nHash*2;
  34650. if( nNew<256 ){
  34651. nNew = 256;
  34652. }
  34653. pcache1LeaveMutex(p->pGroup);
  34654. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  34655. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  34656. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  34657. pcache1EnterMutex(p->pGroup);
  34658. if( apNew ){
  34659. for(i=0; i<p->nHash; i++){
  34660. PgHdr1 *pPage;
  34661. PgHdr1 *pNext = p->apHash[i];
  34662. while( (pPage = pNext)!=0 ){
  34663. unsigned int h = pPage->iKey % nNew;
  34664. pNext = pPage->pNext;
  34665. pPage->pNext = apNew[h];
  34666. apNew[h] = pPage;
  34667. }
  34668. }
  34669. sqlite3_free(p->apHash);
  34670. p->apHash = apNew;
  34671. p->nHash = nNew;
  34672. }
  34673. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  34674. }
  34675. /*
  34676. ** This function is used internally to remove the page pPage from the
  34677. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  34678. ** LRU list, then this function is a no-op.
  34679. **
  34680. ** The PGroup mutex must be held when this function is called.
  34681. **
  34682. ** If pPage is NULL then this routine is a no-op.
  34683. */
  34684. static void pcache1PinPage(PgHdr1 *pPage){
  34685. PCache1 *pCache;
  34686. PGroup *pGroup;
  34687. if( pPage==0 ) return;
  34688. pCache = pPage->pCache;
  34689. pGroup = pCache->pGroup;
  34690. assert( sqlite3_mutex_held(pGroup->mutex) );
  34691. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  34692. if( pPage->pLruPrev ){
  34693. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  34694. }
  34695. if( pPage->pLruNext ){
  34696. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  34697. }
  34698. if( pGroup->pLruHead==pPage ){
  34699. pGroup->pLruHead = pPage->pLruNext;
  34700. }
  34701. if( pGroup->pLruTail==pPage ){
  34702. pGroup->pLruTail = pPage->pLruPrev;
  34703. }
  34704. pPage->pLruNext = 0;
  34705. pPage->pLruPrev = 0;
  34706. pPage->pCache->nRecyclable--;
  34707. }
  34708. }
  34709. /*
  34710. ** Remove the page supplied as an argument from the hash table
  34711. ** (PCache1.apHash structure) that it is currently stored in.
  34712. **
  34713. ** The PGroup mutex must be held when this function is called.
  34714. */
  34715. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  34716. unsigned int h;
  34717. PCache1 *pCache = pPage->pCache;
  34718. PgHdr1 **pp;
  34719. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  34720. h = pPage->iKey % pCache->nHash;
  34721. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  34722. *pp = (*pp)->pNext;
  34723. pCache->nPage--;
  34724. }
  34725. /*
  34726. ** If there are currently more than nMaxPage pages allocated, try
  34727. ** to recycle pages to reduce the number allocated to nMaxPage.
  34728. */
  34729. static void pcache1EnforceMaxPage(PGroup *pGroup){
  34730. assert( sqlite3_mutex_held(pGroup->mutex) );
  34731. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  34732. PgHdr1 *p = pGroup->pLruTail;
  34733. assert( p->pCache->pGroup==pGroup );
  34734. pcache1PinPage(p);
  34735. pcache1RemoveFromHash(p);
  34736. pcache1FreePage(p);
  34737. }
  34738. }
  34739. /*
  34740. ** Discard all pages from cache pCache with a page number (key value)
  34741. ** greater than or equal to iLimit. Any pinned pages that meet this
  34742. ** criteria are unpinned before they are discarded.
  34743. **
  34744. ** The PCache mutex must be held when this function is called.
  34745. */
  34746. static void pcache1TruncateUnsafe(
  34747. PCache1 *pCache, /* The cache to truncate */
  34748. unsigned int iLimit /* Drop pages with this pgno or larger */
  34749. ){
  34750. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  34751. unsigned int h;
  34752. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  34753. for(h=0; h<pCache->nHash; h++){
  34754. PgHdr1 **pp = &pCache->apHash[h];
  34755. PgHdr1 *pPage;
  34756. while( (pPage = *pp)!=0 ){
  34757. if( pPage->iKey>=iLimit ){
  34758. pCache->nPage--;
  34759. *pp = pPage->pNext;
  34760. pcache1PinPage(pPage);
  34761. pcache1FreePage(pPage);
  34762. }else{
  34763. pp = &pPage->pNext;
  34764. TESTONLY( nPage++; )
  34765. }
  34766. }
  34767. }
  34768. assert( pCache->nPage==nPage );
  34769. }
  34770. /******************************************************************************/
  34771. /******** sqlite3_pcache Methods **********************************************/
  34772. /*
  34773. ** Implementation of the sqlite3_pcache.xInit method.
  34774. */
  34775. static int pcache1Init(void *NotUsed){
  34776. UNUSED_PARAMETER(NotUsed);
  34777. assert( pcache1.isInit==0 );
  34778. memset(&pcache1, 0, sizeof(pcache1));
  34779. if( sqlite3GlobalConfig.bCoreMutex ){
  34780. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  34781. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  34782. }
  34783. pcache1.grp.mxPinned = 10;
  34784. pcache1.isInit = 1;
  34785. return SQLITE_OK;
  34786. }
  34787. /*
  34788. ** Implementation of the sqlite3_pcache.xShutdown method.
  34789. ** Note that the static mutex allocated in xInit does
  34790. ** not need to be freed.
  34791. */
  34792. static void pcache1Shutdown(void *NotUsed){
  34793. UNUSED_PARAMETER(NotUsed);
  34794. assert( pcache1.isInit!=0 );
  34795. memset(&pcache1, 0, sizeof(pcache1));
  34796. }
  34797. /*
  34798. ** Implementation of the sqlite3_pcache.xCreate method.
  34799. **
  34800. ** Allocate a new cache.
  34801. */
  34802. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  34803. PCache1 *pCache; /* The newly created page cache */
  34804. PGroup *pGroup; /* The group the new page cache will belong to */
  34805. int sz; /* Bytes of memory required to allocate the new cache */
  34806. /*
  34807. ** The seperateCache variable is true if each PCache has its own private
  34808. ** PGroup. In other words, separateCache is true for mode (1) where no
  34809. ** mutexing is required.
  34810. **
  34811. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  34812. **
  34813. ** * Always use a unified cache in single-threaded applications
  34814. **
  34815. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  34816. ** use separate caches (mode-1)
  34817. */
  34818. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  34819. const int separateCache = 0;
  34820. #else
  34821. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  34822. #endif
  34823. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  34824. assert( szExtra < 300 );
  34825. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  34826. pCache = (PCache1 *)sqlite3MallocZero(sz);
  34827. if( pCache ){
  34828. if( separateCache ){
  34829. pGroup = (PGroup*)&pCache[1];
  34830. pGroup->mxPinned = 10;
  34831. }else{
  34832. pGroup = &pcache1.grp;
  34833. }
  34834. pCache->pGroup = pGroup;
  34835. pCache->szPage = szPage;
  34836. pCache->szExtra = szExtra;
  34837. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  34838. if( bPurgeable ){
  34839. pCache->nMin = 10;
  34840. pcache1EnterMutex(pGroup);
  34841. pGroup->nMinPage += pCache->nMin;
  34842. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  34843. pcache1LeaveMutex(pGroup);
  34844. }
  34845. }
  34846. return (sqlite3_pcache *)pCache;
  34847. }
  34848. /*
  34849. ** Implementation of the sqlite3_pcache.xCachesize method.
  34850. **
  34851. ** Configure the cache_size limit for a cache.
  34852. */
  34853. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  34854. PCache1 *pCache = (PCache1 *)p;
  34855. if( pCache->bPurgeable ){
  34856. PGroup *pGroup = pCache->pGroup;
  34857. pcache1EnterMutex(pGroup);
  34858. pGroup->nMaxPage += (nMax - pCache->nMax);
  34859. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  34860. pCache->nMax = nMax;
  34861. pCache->n90pct = pCache->nMax*9/10;
  34862. pcache1EnforceMaxPage(pGroup);
  34863. pcache1LeaveMutex(pGroup);
  34864. }
  34865. }
  34866. /*
  34867. ** Implementation of the sqlite3_pcache.xShrink method.
  34868. **
  34869. ** Free up as much memory as possible.
  34870. */
  34871. static void pcache1Shrink(sqlite3_pcache *p){
  34872. PCache1 *pCache = (PCache1*)p;
  34873. if( pCache->bPurgeable ){
  34874. PGroup *pGroup = pCache->pGroup;
  34875. int savedMaxPage;
  34876. pcache1EnterMutex(pGroup);
  34877. savedMaxPage = pGroup->nMaxPage;
  34878. pGroup->nMaxPage = 0;
  34879. pcache1EnforceMaxPage(pGroup);
  34880. pGroup->nMaxPage = savedMaxPage;
  34881. pcache1LeaveMutex(pGroup);
  34882. }
  34883. }
  34884. /*
  34885. ** Implementation of the sqlite3_pcache.xPagecount method.
  34886. */
  34887. static int pcache1Pagecount(sqlite3_pcache *p){
  34888. int n;
  34889. PCache1 *pCache = (PCache1*)p;
  34890. pcache1EnterMutex(pCache->pGroup);
  34891. n = pCache->nPage;
  34892. pcache1LeaveMutex(pCache->pGroup);
  34893. return n;
  34894. }
  34895. /*
  34896. ** Implementation of the sqlite3_pcache.xFetch method.
  34897. **
  34898. ** Fetch a page by key value.
  34899. **
  34900. ** Whether or not a new page may be allocated by this function depends on
  34901. ** the value of the createFlag argument. 0 means do not allocate a new
  34902. ** page. 1 means allocate a new page if space is easily available. 2
  34903. ** means to try really hard to allocate a new page.
  34904. **
  34905. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  34906. ** database) there is really no difference between createFlag 1 and 2. So
  34907. ** the calling function (pcache.c) will never have a createFlag of 1 on
  34908. ** a non-purgeable cache.
  34909. **
  34910. ** There are three different approaches to obtaining space for a page,
  34911. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  34912. **
  34913. ** 1. Regardless of the value of createFlag, the cache is searched for a
  34914. ** copy of the requested page. If one is found, it is returned.
  34915. **
  34916. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  34917. ** returned.
  34918. **
  34919. ** 3. If createFlag is 1, and the page is not already in the cache, then
  34920. ** return NULL (do not allocate a new page) if any of the following
  34921. ** conditions are true:
  34922. **
  34923. ** (a) the number of pages pinned by the cache is greater than
  34924. ** PCache1.nMax, or
  34925. **
  34926. ** (b) the number of pages pinned by the cache is greater than
  34927. ** the sum of nMax for all purgeable caches, less the sum of
  34928. ** nMin for all other purgeable caches, or
  34929. **
  34930. ** 4. If none of the first three conditions apply and the cache is marked
  34931. ** as purgeable, and if one of the following is true:
  34932. **
  34933. ** (a) The number of pages allocated for the cache is already
  34934. ** PCache1.nMax, or
  34935. **
  34936. ** (b) The number of pages allocated for all purgeable caches is
  34937. ** already equal to or greater than the sum of nMax for all
  34938. ** purgeable caches,
  34939. **
  34940. ** (c) The system is under memory pressure and wants to avoid
  34941. ** unnecessary pages cache entry allocations
  34942. **
  34943. ** then attempt to recycle a page from the LRU list. If it is the right
  34944. ** size, return the recycled buffer. Otherwise, free the buffer and
  34945. ** proceed to step 5.
  34946. **
  34947. ** 5. Otherwise, allocate and return a new page buffer.
  34948. */
  34949. static sqlite3_pcache_page *pcache1Fetch(
  34950. sqlite3_pcache *p,
  34951. unsigned int iKey,
  34952. int createFlag
  34953. ){
  34954. unsigned int nPinned;
  34955. PCache1 *pCache = (PCache1 *)p;
  34956. PGroup *pGroup;
  34957. PgHdr1 *pPage = 0;
  34958. assert( pCache->bPurgeable || createFlag!=1 );
  34959. assert( pCache->bPurgeable || pCache->nMin==0 );
  34960. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  34961. assert( pCache->nMin==0 || pCache->bPurgeable );
  34962. pcache1EnterMutex(pGroup = pCache->pGroup);
  34963. /* Step 1: Search the hash table for an existing entry. */
  34964. if( pCache->nHash>0 ){
  34965. unsigned int h = iKey % pCache->nHash;
  34966. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  34967. }
  34968. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  34969. if( pPage || createFlag==0 ){
  34970. pcache1PinPage(pPage);
  34971. goto fetch_out;
  34972. }
  34973. /* The pGroup local variable will normally be initialized by the
  34974. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  34975. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  34976. ** local variable here. Delaying the initialization of pGroup is an
  34977. ** optimization: The common case is to exit the module before reaching
  34978. ** this point.
  34979. */
  34980. #ifdef SQLITE_MUTEX_OMIT
  34981. pGroup = pCache->pGroup;
  34982. #endif
  34983. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  34984. assert( pCache->nPage >= pCache->nRecyclable );
  34985. nPinned = pCache->nPage - pCache->nRecyclable;
  34986. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  34987. assert( pCache->n90pct == pCache->nMax*9/10 );
  34988. if( createFlag==1 && (
  34989. nPinned>=pGroup->mxPinned
  34990. || nPinned>=pCache->n90pct
  34991. || pcache1UnderMemoryPressure(pCache)
  34992. )){
  34993. goto fetch_out;
  34994. }
  34995. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  34996. goto fetch_out;
  34997. }
  34998. /* Step 4. Try to recycle a page. */
  34999. if( pCache->bPurgeable && pGroup->pLruTail && (
  35000. (pCache->nPage+1>=pCache->nMax)
  35001. || pGroup->nCurrentPage>=pGroup->nMaxPage
  35002. || pcache1UnderMemoryPressure(pCache)
  35003. )){
  35004. PCache1 *pOther;
  35005. pPage = pGroup->pLruTail;
  35006. pcache1RemoveFromHash(pPage);
  35007. pcache1PinPage(pPage);
  35008. pOther = pPage->pCache;
  35009. /* We want to verify that szPage and szExtra are the same for pOther
  35010. ** and pCache. Assert that we can verify this by comparing sums. */
  35011. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  35012. assert( pCache->szExtra<512 );
  35013. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  35014. assert( pOther->szExtra<512 );
  35015. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  35016. pcache1FreePage(pPage);
  35017. pPage = 0;
  35018. }else{
  35019. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  35020. }
  35021. }
  35022. /* Step 5. If a usable page buffer has still not been found,
  35023. ** attempt to allocate a new one.
  35024. */
  35025. if( !pPage ){
  35026. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  35027. pPage = pcache1AllocPage(pCache);
  35028. if( createFlag==1 ) sqlite3EndBenignMalloc();
  35029. }
  35030. if( pPage ){
  35031. unsigned int h = iKey % pCache->nHash;
  35032. pCache->nPage++;
  35033. pPage->iKey = iKey;
  35034. pPage->pNext = pCache->apHash[h];
  35035. pPage->pCache = pCache;
  35036. pPage->pLruPrev = 0;
  35037. pPage->pLruNext = 0;
  35038. *(void **)pPage->page.pExtra = 0;
  35039. pCache->apHash[h] = pPage;
  35040. }
  35041. fetch_out:
  35042. if( pPage && iKey>pCache->iMaxKey ){
  35043. pCache->iMaxKey = iKey;
  35044. }
  35045. pcache1LeaveMutex(pGroup);
  35046. return &pPage->page;
  35047. }
  35048. /*
  35049. ** Implementation of the sqlite3_pcache.xUnpin method.
  35050. **
  35051. ** Mark a page as unpinned (eligible for asynchronous recycling).
  35052. */
  35053. static void pcache1Unpin(
  35054. sqlite3_pcache *p,
  35055. sqlite3_pcache_page *pPg,
  35056. int reuseUnlikely
  35057. ){
  35058. PCache1 *pCache = (PCache1 *)p;
  35059. PgHdr1 *pPage = (PgHdr1 *)pPg;
  35060. PGroup *pGroup = pCache->pGroup;
  35061. assert( pPage->pCache==pCache );
  35062. pcache1EnterMutex(pGroup);
  35063. /* It is an error to call this function if the page is already
  35064. ** part of the PGroup LRU list.
  35065. */
  35066. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  35067. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  35068. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  35069. pcache1RemoveFromHash(pPage);
  35070. pcache1FreePage(pPage);
  35071. }else{
  35072. /* Add the page to the PGroup LRU list. */
  35073. if( pGroup->pLruHead ){
  35074. pGroup->pLruHead->pLruPrev = pPage;
  35075. pPage->pLruNext = pGroup->pLruHead;
  35076. pGroup->pLruHead = pPage;
  35077. }else{
  35078. pGroup->pLruTail = pPage;
  35079. pGroup->pLruHead = pPage;
  35080. }
  35081. pCache->nRecyclable++;
  35082. }
  35083. pcache1LeaveMutex(pCache->pGroup);
  35084. }
  35085. /*
  35086. ** Implementation of the sqlite3_pcache.xRekey method.
  35087. */
  35088. static void pcache1Rekey(
  35089. sqlite3_pcache *p,
  35090. sqlite3_pcache_page *pPg,
  35091. unsigned int iOld,
  35092. unsigned int iNew
  35093. ){
  35094. PCache1 *pCache = (PCache1 *)p;
  35095. PgHdr1 *pPage = (PgHdr1 *)pPg;
  35096. PgHdr1 **pp;
  35097. unsigned int h;
  35098. assert( pPage->iKey==iOld );
  35099. assert( pPage->pCache==pCache );
  35100. pcache1EnterMutex(pCache->pGroup);
  35101. h = iOld%pCache->nHash;
  35102. pp = &pCache->apHash[h];
  35103. while( (*pp)!=pPage ){
  35104. pp = &(*pp)->pNext;
  35105. }
  35106. *pp = pPage->pNext;
  35107. h = iNew%pCache->nHash;
  35108. pPage->iKey = iNew;
  35109. pPage->pNext = pCache->apHash[h];
  35110. pCache->apHash[h] = pPage;
  35111. if( iNew>pCache->iMaxKey ){
  35112. pCache->iMaxKey = iNew;
  35113. }
  35114. pcache1LeaveMutex(pCache->pGroup);
  35115. }
  35116. /*
  35117. ** Implementation of the sqlite3_pcache.xTruncate method.
  35118. **
  35119. ** Discard all unpinned pages in the cache with a page number equal to
  35120. ** or greater than parameter iLimit. Any pinned pages with a page number
  35121. ** equal to or greater than iLimit are implicitly unpinned.
  35122. */
  35123. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  35124. PCache1 *pCache = (PCache1 *)p;
  35125. pcache1EnterMutex(pCache->pGroup);
  35126. if( iLimit<=pCache->iMaxKey ){
  35127. pcache1TruncateUnsafe(pCache, iLimit);
  35128. pCache->iMaxKey = iLimit-1;
  35129. }
  35130. pcache1LeaveMutex(pCache->pGroup);
  35131. }
  35132. /*
  35133. ** Implementation of the sqlite3_pcache.xDestroy method.
  35134. **
  35135. ** Destroy a cache allocated using pcache1Create().
  35136. */
  35137. static void pcache1Destroy(sqlite3_pcache *p){
  35138. PCache1 *pCache = (PCache1 *)p;
  35139. PGroup *pGroup = pCache->pGroup;
  35140. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  35141. pcache1EnterMutex(pGroup);
  35142. pcache1TruncateUnsafe(pCache, 0);
  35143. assert( pGroup->nMaxPage >= pCache->nMax );
  35144. pGroup->nMaxPage -= pCache->nMax;
  35145. assert( pGroup->nMinPage >= pCache->nMin );
  35146. pGroup->nMinPage -= pCache->nMin;
  35147. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  35148. pcache1EnforceMaxPage(pGroup);
  35149. pcache1LeaveMutex(pGroup);
  35150. sqlite3_free(pCache->apHash);
  35151. sqlite3_free(pCache);
  35152. }
  35153. /*
  35154. ** This function is called during initialization (sqlite3_initialize()) to
  35155. ** install the default pluggable cache module, assuming the user has not
  35156. ** already provided an alternative.
  35157. */
  35158. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  35159. static const sqlite3_pcache_methods2 defaultMethods = {
  35160. 1, /* iVersion */
  35161. 0, /* pArg */
  35162. pcache1Init, /* xInit */
  35163. pcache1Shutdown, /* xShutdown */
  35164. pcache1Create, /* xCreate */
  35165. pcache1Cachesize, /* xCachesize */
  35166. pcache1Pagecount, /* xPagecount */
  35167. pcache1Fetch, /* xFetch */
  35168. pcache1Unpin, /* xUnpin */
  35169. pcache1Rekey, /* xRekey */
  35170. pcache1Truncate, /* xTruncate */
  35171. pcache1Destroy, /* xDestroy */
  35172. pcache1Shrink /* xShrink */
  35173. };
  35174. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  35175. }
  35176. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  35177. /*
  35178. ** This function is called to free superfluous dynamically allocated memory
  35179. ** held by the pager system. Memory in use by any SQLite pager allocated
  35180. ** by the current thread may be sqlite3_free()ed.
  35181. **
  35182. ** nReq is the number of bytes of memory required. Once this much has
  35183. ** been released, the function returns. The return value is the total number
  35184. ** of bytes of memory released.
  35185. */
  35186. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  35187. int nFree = 0;
  35188. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  35189. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  35190. if( pcache1.pStart==0 ){
  35191. PgHdr1 *p;
  35192. pcache1EnterMutex(&pcache1.grp);
  35193. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  35194. nFree += pcache1MemSize(p->page.pBuf);
  35195. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  35196. nFree += sqlite3MemSize(p);
  35197. #endif
  35198. pcache1PinPage(p);
  35199. pcache1RemoveFromHash(p);
  35200. pcache1FreePage(p);
  35201. }
  35202. pcache1LeaveMutex(&pcache1.grp);
  35203. }
  35204. return nFree;
  35205. }
  35206. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  35207. #ifdef SQLITE_TEST
  35208. /*
  35209. ** This function is used by test procedures to inspect the internal state
  35210. ** of the global cache.
  35211. */
  35212. SQLITE_PRIVATE void sqlite3PcacheStats(
  35213. int *pnCurrent, /* OUT: Total number of pages cached */
  35214. int *pnMax, /* OUT: Global maximum cache size */
  35215. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  35216. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  35217. ){
  35218. PgHdr1 *p;
  35219. int nRecyclable = 0;
  35220. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  35221. nRecyclable++;
  35222. }
  35223. *pnCurrent = pcache1.grp.nCurrentPage;
  35224. *pnMax = (int)pcache1.grp.nMaxPage;
  35225. *pnMin = (int)pcache1.grp.nMinPage;
  35226. *pnRecyclable = nRecyclable;
  35227. }
  35228. #endif
  35229. /************** End of pcache1.c *********************************************/
  35230. /************** Begin file rowset.c ******************************************/
  35231. /*
  35232. ** 2008 December 3
  35233. **
  35234. ** The author disclaims copyright to this source code. In place of
  35235. ** a legal notice, here is a blessing:
  35236. **
  35237. ** May you do good and not evil.
  35238. ** May you find forgiveness for yourself and forgive others.
  35239. ** May you share freely, never taking more than you give.
  35240. **
  35241. *************************************************************************
  35242. **
  35243. ** This module implements an object we call a "RowSet".
  35244. **
  35245. ** The RowSet object is a collection of rowids. Rowids
  35246. ** are inserted into the RowSet in an arbitrary order. Inserts
  35247. ** can be intermixed with tests to see if a given rowid has been
  35248. ** previously inserted into the RowSet.
  35249. **
  35250. ** After all inserts are finished, it is possible to extract the
  35251. ** elements of the RowSet in sorted order. Once this extraction
  35252. ** process has started, no new elements may be inserted.
  35253. **
  35254. ** Hence, the primitive operations for a RowSet are:
  35255. **
  35256. ** CREATE
  35257. ** INSERT
  35258. ** TEST
  35259. ** SMALLEST
  35260. ** DESTROY
  35261. **
  35262. ** The CREATE and DESTROY primitives are the constructor and destructor,
  35263. ** obviously. The INSERT primitive adds a new element to the RowSet.
  35264. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  35265. ** extracts the least value from the RowSet.
  35266. **
  35267. ** The INSERT primitive might allocate additional memory. Memory is
  35268. ** allocated in chunks so most INSERTs do no allocation. There is an
  35269. ** upper bound on the size of allocated memory. No memory is freed
  35270. ** until DESTROY.
  35271. **
  35272. ** The TEST primitive includes a "batch" number. The TEST primitive
  35273. ** will only see elements that were inserted before the last change
  35274. ** in the batch number. In other words, if an INSERT occurs between
  35275. ** two TESTs where the TESTs have the same batch nubmer, then the
  35276. ** value added by the INSERT will not be visible to the second TEST.
  35277. ** The initial batch number is zero, so if the very first TEST contains
  35278. ** a non-zero batch number, it will see all prior INSERTs.
  35279. **
  35280. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  35281. ** that is attempted.
  35282. **
  35283. ** The cost of an INSERT is roughly constant. (Sometime new memory
  35284. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  35285. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  35286. ** The cost of a TEST using the same batch number is O(logN). The cost
  35287. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  35288. ** primitives are constant time. The cost of DESTROY is O(N).
  35289. **
  35290. ** There is an added cost of O(N) when switching between TEST and
  35291. ** SMALLEST primitives.
  35292. */
  35293. /*
  35294. ** Target size for allocation chunks.
  35295. */
  35296. #define ROWSET_ALLOCATION_SIZE 1024
  35297. /*
  35298. ** The number of rowset entries per allocation chunk.
  35299. */
  35300. #define ROWSET_ENTRY_PER_CHUNK \
  35301. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  35302. /*
  35303. ** Each entry in a RowSet is an instance of the following object.
  35304. **
  35305. ** This same object is reused to store a linked list of trees of RowSetEntry
  35306. ** objects. In that alternative use, pRight points to the next entry
  35307. ** in the list, pLeft points to the tree, and v is unused. The
  35308. ** RowSet.pForest value points to the head of this forest list.
  35309. */
  35310. struct RowSetEntry {
  35311. i64 v; /* ROWID value for this entry */
  35312. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  35313. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  35314. };
  35315. /*
  35316. ** RowSetEntry objects are allocated in large chunks (instances of the
  35317. ** following structure) to reduce memory allocation overhead. The
  35318. ** chunks are kept on a linked list so that they can be deallocated
  35319. ** when the RowSet is destroyed.
  35320. */
  35321. struct RowSetChunk {
  35322. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  35323. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  35324. };
  35325. /*
  35326. ** A RowSet in an instance of the following structure.
  35327. **
  35328. ** A typedef of this structure if found in sqliteInt.h.
  35329. */
  35330. struct RowSet {
  35331. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  35332. sqlite3 *db; /* The database connection */
  35333. struct RowSetEntry *pEntry; /* List of entries using pRight */
  35334. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  35335. struct RowSetEntry *pFresh; /* Source of new entry objects */
  35336. struct RowSetEntry *pForest; /* List of binary trees of entries */
  35337. u16 nFresh; /* Number of objects on pFresh */
  35338. u8 rsFlags; /* Various flags */
  35339. u8 iBatch; /* Current insert batch */
  35340. };
  35341. /*
  35342. ** Allowed values for RowSet.rsFlags
  35343. */
  35344. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  35345. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  35346. /*
  35347. ** Turn bulk memory into a RowSet object. N bytes of memory
  35348. ** are available at pSpace. The db pointer is used as a memory context
  35349. ** for any subsequent allocations that need to occur.
  35350. ** Return a pointer to the new RowSet object.
  35351. **
  35352. ** It must be the case that N is sufficient to make a Rowset. If not
  35353. ** an assertion fault occurs.
  35354. **
  35355. ** If N is larger than the minimum, use the surplus as an initial
  35356. ** allocation of entries available to be filled.
  35357. */
  35358. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  35359. RowSet *p;
  35360. assert( N >= ROUND8(sizeof(*p)) );
  35361. p = pSpace;
  35362. p->pChunk = 0;
  35363. p->db = db;
  35364. p->pEntry = 0;
  35365. p->pLast = 0;
  35366. p->pForest = 0;
  35367. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  35368. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  35369. p->rsFlags = ROWSET_SORTED;
  35370. p->iBatch = 0;
  35371. return p;
  35372. }
  35373. /*
  35374. ** Deallocate all chunks from a RowSet. This frees all memory that
  35375. ** the RowSet has allocated over its lifetime. This routine is
  35376. ** the destructor for the RowSet.
  35377. */
  35378. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  35379. struct RowSetChunk *pChunk, *pNextChunk;
  35380. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  35381. pNextChunk = pChunk->pNextChunk;
  35382. sqlite3DbFree(p->db, pChunk);
  35383. }
  35384. p->pChunk = 0;
  35385. p->nFresh = 0;
  35386. p->pEntry = 0;
  35387. p->pLast = 0;
  35388. p->pForest = 0;
  35389. p->rsFlags = ROWSET_SORTED;
  35390. }
  35391. /*
  35392. ** Allocate a new RowSetEntry object that is associated with the
  35393. ** given RowSet. Return a pointer to the new and completely uninitialized
  35394. ** objected.
  35395. **
  35396. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  35397. ** routine returns NULL.
  35398. */
  35399. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  35400. assert( p!=0 );
  35401. if( p->nFresh==0 ){
  35402. struct RowSetChunk *pNew;
  35403. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  35404. if( pNew==0 ){
  35405. return 0;
  35406. }
  35407. pNew->pNextChunk = p->pChunk;
  35408. p->pChunk = pNew;
  35409. p->pFresh = pNew->aEntry;
  35410. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  35411. }
  35412. p->nFresh--;
  35413. return p->pFresh++;
  35414. }
  35415. /*
  35416. ** Insert a new value into a RowSet.
  35417. **
  35418. ** The mallocFailed flag of the database connection is set if a
  35419. ** memory allocation fails.
  35420. */
  35421. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  35422. struct RowSetEntry *pEntry; /* The new entry */
  35423. struct RowSetEntry *pLast; /* The last prior entry */
  35424. /* This routine is never called after sqlite3RowSetNext() */
  35425. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  35426. pEntry = rowSetEntryAlloc(p);
  35427. if( pEntry==0 ) return;
  35428. pEntry->v = rowid;
  35429. pEntry->pRight = 0;
  35430. pLast = p->pLast;
  35431. if( pLast ){
  35432. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  35433. p->rsFlags &= ~ROWSET_SORTED;
  35434. }
  35435. pLast->pRight = pEntry;
  35436. }else{
  35437. p->pEntry = pEntry;
  35438. }
  35439. p->pLast = pEntry;
  35440. }
  35441. /*
  35442. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  35443. **
  35444. ** The input lists are connected via pRight pointers and are
  35445. ** assumed to each already be in sorted order.
  35446. */
  35447. static struct RowSetEntry *rowSetEntryMerge(
  35448. struct RowSetEntry *pA, /* First sorted list to be merged */
  35449. struct RowSetEntry *pB /* Second sorted list to be merged */
  35450. ){
  35451. struct RowSetEntry head;
  35452. struct RowSetEntry *pTail;
  35453. pTail = &head;
  35454. while( pA && pB ){
  35455. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  35456. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  35457. if( pA->v<pB->v ){
  35458. pTail->pRight = pA;
  35459. pA = pA->pRight;
  35460. pTail = pTail->pRight;
  35461. }else if( pB->v<pA->v ){
  35462. pTail->pRight = pB;
  35463. pB = pB->pRight;
  35464. pTail = pTail->pRight;
  35465. }else{
  35466. pA = pA->pRight;
  35467. }
  35468. }
  35469. if( pA ){
  35470. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  35471. pTail->pRight = pA;
  35472. }else{
  35473. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  35474. pTail->pRight = pB;
  35475. }
  35476. return head.pRight;
  35477. }
  35478. /*
  35479. ** Sort all elements on the list of RowSetEntry objects into order of
  35480. ** increasing v.
  35481. */
  35482. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  35483. unsigned int i;
  35484. struct RowSetEntry *pNext, *aBucket[40];
  35485. memset(aBucket, 0, sizeof(aBucket));
  35486. while( pIn ){
  35487. pNext = pIn->pRight;
  35488. pIn->pRight = 0;
  35489. for(i=0; aBucket[i]; i++){
  35490. pIn = rowSetEntryMerge(aBucket[i], pIn);
  35491. aBucket[i] = 0;
  35492. }
  35493. aBucket[i] = pIn;
  35494. pIn = pNext;
  35495. }
  35496. pIn = 0;
  35497. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  35498. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  35499. }
  35500. return pIn;
  35501. }
  35502. /*
  35503. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  35504. ** Convert this tree into a linked list connected by the pRight pointers
  35505. ** and return pointers to the first and last elements of the new list.
  35506. */
  35507. static void rowSetTreeToList(
  35508. struct RowSetEntry *pIn, /* Root of the input tree */
  35509. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  35510. struct RowSetEntry **ppLast /* Write tail of the output list here */
  35511. ){
  35512. assert( pIn!=0 );
  35513. if( pIn->pLeft ){
  35514. struct RowSetEntry *p;
  35515. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  35516. p->pRight = pIn;
  35517. }else{
  35518. *ppFirst = pIn;
  35519. }
  35520. if( pIn->pRight ){
  35521. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  35522. }else{
  35523. *ppLast = pIn;
  35524. }
  35525. assert( (*ppLast)->pRight==0 );
  35526. }
  35527. /*
  35528. ** Convert a sorted list of elements (connected by pRight) into a binary
  35529. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  35530. ** node taken from the head of *ppList. A depth of 2 means a tree with
  35531. ** three nodes. And so forth.
  35532. **
  35533. ** Use as many entries from the input list as required and update the
  35534. ** *ppList to point to the unused elements of the list. If the input
  35535. ** list contains too few elements, then construct an incomplete tree
  35536. ** and leave *ppList set to NULL.
  35537. **
  35538. ** Return a pointer to the root of the constructed binary tree.
  35539. */
  35540. static struct RowSetEntry *rowSetNDeepTree(
  35541. struct RowSetEntry **ppList,
  35542. int iDepth
  35543. ){
  35544. struct RowSetEntry *p; /* Root of the new tree */
  35545. struct RowSetEntry *pLeft; /* Left subtree */
  35546. if( *ppList==0 ){
  35547. return 0;
  35548. }
  35549. if( iDepth==1 ){
  35550. p = *ppList;
  35551. *ppList = p->pRight;
  35552. p->pLeft = p->pRight = 0;
  35553. return p;
  35554. }
  35555. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  35556. p = *ppList;
  35557. if( p==0 ){
  35558. return pLeft;
  35559. }
  35560. p->pLeft = pLeft;
  35561. *ppList = p->pRight;
  35562. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  35563. return p;
  35564. }
  35565. /*
  35566. ** Convert a sorted list of elements into a binary tree. Make the tree
  35567. ** as deep as it needs to be in order to contain the entire list.
  35568. */
  35569. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  35570. int iDepth; /* Depth of the tree so far */
  35571. struct RowSetEntry *p; /* Current tree root */
  35572. struct RowSetEntry *pLeft; /* Left subtree */
  35573. assert( pList!=0 );
  35574. p = pList;
  35575. pList = p->pRight;
  35576. p->pLeft = p->pRight = 0;
  35577. for(iDepth=1; pList; iDepth++){
  35578. pLeft = p;
  35579. p = pList;
  35580. pList = p->pRight;
  35581. p->pLeft = pLeft;
  35582. p->pRight = rowSetNDeepTree(&pList, iDepth);
  35583. }
  35584. return p;
  35585. }
  35586. /*
  35587. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  35588. ** sort them all together into one big ordered list on p->pEntry.
  35589. **
  35590. ** This routine should only be called once in the life of a RowSet.
  35591. */
  35592. static void rowSetToList(RowSet *p){
  35593. /* This routine is called only once */
  35594. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  35595. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  35596. p->pEntry = rowSetEntrySort(p->pEntry);
  35597. }
  35598. /* While this module could theoretically support it, sqlite3RowSetNext()
  35599. ** is never called after sqlite3RowSetText() for the same RowSet. So
  35600. ** there is never a forest to deal with. Should this change, simply
  35601. ** remove the assert() and the #if 0. */
  35602. assert( p->pForest==0 );
  35603. #if 0
  35604. while( p->pForest ){
  35605. struct RowSetEntry *pTree = p->pForest->pLeft;
  35606. if( pTree ){
  35607. struct RowSetEntry *pHead, *pTail;
  35608. rowSetTreeToList(pTree, &pHead, &pTail);
  35609. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  35610. }
  35611. p->pForest = p->pForest->pRight;
  35612. }
  35613. #endif
  35614. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  35615. }
  35616. /*
  35617. ** Extract the smallest element from the RowSet.
  35618. ** Write the element into *pRowid. Return 1 on success. Return
  35619. ** 0 if the RowSet is already empty.
  35620. **
  35621. ** After this routine has been called, the sqlite3RowSetInsert()
  35622. ** routine may not be called again.
  35623. */
  35624. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  35625. assert( p!=0 );
  35626. /* Merge the forest into a single sorted list on first call */
  35627. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  35628. /* Return the next entry on the list */
  35629. if( p->pEntry ){
  35630. *pRowid = p->pEntry->v;
  35631. p->pEntry = p->pEntry->pRight;
  35632. if( p->pEntry==0 ){
  35633. sqlite3RowSetClear(p);
  35634. }
  35635. return 1;
  35636. }else{
  35637. return 0;
  35638. }
  35639. }
  35640. /*
  35641. ** Check to see if element iRowid was inserted into the rowset as
  35642. ** part of any insert batch prior to iBatch. Return 1 or 0.
  35643. **
  35644. ** If this is the first test of a new batch and if there exist entires
  35645. ** on pRowSet->pEntry, then sort those entires into the forest at
  35646. ** pRowSet->pForest so that they can be tested.
  35647. */
  35648. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  35649. struct RowSetEntry *p, *pTree;
  35650. /* This routine is never called after sqlite3RowSetNext() */
  35651. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  35652. /* Sort entries into the forest on the first test of a new batch
  35653. */
  35654. if( iBatch!=pRowSet->iBatch ){
  35655. p = pRowSet->pEntry;
  35656. if( p ){
  35657. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  35658. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  35659. p = rowSetEntrySort(p);
  35660. }
  35661. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  35662. ppPrevTree = &pTree->pRight;
  35663. if( pTree->pLeft==0 ){
  35664. pTree->pLeft = rowSetListToTree(p);
  35665. break;
  35666. }else{
  35667. struct RowSetEntry *pAux, *pTail;
  35668. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  35669. pTree->pLeft = 0;
  35670. p = rowSetEntryMerge(pAux, p);
  35671. }
  35672. }
  35673. if( pTree==0 ){
  35674. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  35675. if( pTree ){
  35676. pTree->v = 0;
  35677. pTree->pRight = 0;
  35678. pTree->pLeft = rowSetListToTree(p);
  35679. }
  35680. }
  35681. pRowSet->pEntry = 0;
  35682. pRowSet->pLast = 0;
  35683. pRowSet->rsFlags |= ROWSET_SORTED;
  35684. }
  35685. pRowSet->iBatch = iBatch;
  35686. }
  35687. /* Test to see if the iRowid value appears anywhere in the forest.
  35688. ** Return 1 if it does and 0 if not.
  35689. */
  35690. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  35691. p = pTree->pLeft;
  35692. while( p ){
  35693. if( p->v<iRowid ){
  35694. p = p->pRight;
  35695. }else if( p->v>iRowid ){
  35696. p = p->pLeft;
  35697. }else{
  35698. return 1;
  35699. }
  35700. }
  35701. }
  35702. return 0;
  35703. }
  35704. /************** End of rowset.c **********************************************/
  35705. /************** Begin file pager.c *******************************************/
  35706. /*
  35707. ** 2001 September 15
  35708. **
  35709. ** The author disclaims copyright to this source code. In place of
  35710. ** a legal notice, here is a blessing:
  35711. **
  35712. ** May you do good and not evil.
  35713. ** May you find forgiveness for yourself and forgive others.
  35714. ** May you share freely, never taking more than you give.
  35715. **
  35716. *************************************************************************
  35717. ** This is the implementation of the page cache subsystem or "pager".
  35718. **
  35719. ** The pager is used to access a database disk file. It implements
  35720. ** atomic commit and rollback through the use of a journal file that
  35721. ** is separate from the database file. The pager also implements file
  35722. ** locking to prevent two processes from writing the same database
  35723. ** file simultaneously, or one process from reading the database while
  35724. ** another is writing.
  35725. */
  35726. #ifndef SQLITE_OMIT_DISKIO
  35727. /************** Include wal.h in the middle of pager.c ***********************/
  35728. /************** Begin file wal.h *********************************************/
  35729. /*
  35730. ** 2010 February 1
  35731. **
  35732. ** The author disclaims copyright to this source code. In place of
  35733. ** a legal notice, here is a blessing:
  35734. **
  35735. ** May you do good and not evil.
  35736. ** May you find forgiveness for yourself and forgive others.
  35737. ** May you share freely, never taking more than you give.
  35738. **
  35739. *************************************************************************
  35740. ** This header file defines the interface to the write-ahead logging
  35741. ** system. Refer to the comments below and the header comment attached to
  35742. ** the implementation of each function in log.c for further details.
  35743. */
  35744. #ifndef _WAL_H_
  35745. #define _WAL_H_
  35746. /* Additional values that can be added to the sync_flags argument of
  35747. ** sqlite3WalFrames():
  35748. */
  35749. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  35750. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  35751. #ifdef SQLITE_OMIT_WAL
  35752. # define sqlite3WalOpen(x,y,z) 0
  35753. # define sqlite3WalLimit(x,y)
  35754. # define sqlite3WalClose(w,x,y,z) 0
  35755. # define sqlite3WalBeginReadTransaction(y,z) 0
  35756. # define sqlite3WalEndReadTransaction(z)
  35757. # define sqlite3WalDbsize(y) 0
  35758. # define sqlite3WalBeginWriteTransaction(y) 0
  35759. # define sqlite3WalEndWriteTransaction(x) 0
  35760. # define sqlite3WalUndo(x,y,z) 0
  35761. # define sqlite3WalSavepoint(y,z)
  35762. # define sqlite3WalSavepointUndo(y,z) 0
  35763. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  35764. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  35765. # define sqlite3WalCallback(z) 0
  35766. # define sqlite3WalExclusiveMode(y,z) 0
  35767. # define sqlite3WalHeapMemory(z) 0
  35768. # define sqlite3WalFramesize(z) 0
  35769. # define sqlite3WalFindFrame(x,y,z) 0
  35770. #else
  35771. #define WAL_SAVEPOINT_NDATA 4
  35772. /* Connection to a write-ahead log (WAL) file.
  35773. ** There is one object of this type for each pager.
  35774. */
  35775. typedef struct Wal Wal;
  35776. /* Open and close a connection to a write-ahead log. */
  35777. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  35778. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  35779. /* Set the limiting size of a WAL file. */
  35780. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  35781. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  35782. ** snapshot is like a read-transaction. It is the state of the database
  35783. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  35784. ** preserves the current state even if the other threads or processes
  35785. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  35786. ** transaction and releases the lock.
  35787. */
  35788. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  35789. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  35790. /* Read a page from the write-ahead log, if it is present. */
  35791. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  35792. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  35793. /* If the WAL is not empty, return the size of the database. */
  35794. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  35795. /* Obtain or release the WRITER lock. */
  35796. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  35797. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  35798. /* Undo any frames written (but not committed) to the log */
  35799. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  35800. /* Return an integer that records the current (uncommitted) write
  35801. ** position in the WAL */
  35802. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  35803. /* Move the write position of the WAL back to iFrame. Called in
  35804. ** response to a ROLLBACK TO command. */
  35805. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  35806. /* Write a frame or frames to the log. */
  35807. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  35808. /* Copy pages from the log to the database file */
  35809. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  35810. Wal *pWal, /* Write-ahead log connection */
  35811. int eMode, /* One of PASSIVE, FULL and RESTART */
  35812. int (*xBusy)(void*), /* Function to call when busy */
  35813. void *pBusyArg, /* Context argument for xBusyHandler */
  35814. int sync_flags, /* Flags to sync db file with (or 0) */
  35815. int nBuf, /* Size of buffer nBuf */
  35816. u8 *zBuf, /* Temporary buffer to use */
  35817. int *pnLog, /* OUT: Number of frames in WAL */
  35818. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  35819. );
  35820. /* Return the value to pass to a sqlite3_wal_hook callback, the
  35821. ** number of frames in the WAL at the point of the last commit since
  35822. ** sqlite3WalCallback() was called. If no commits have occurred since
  35823. ** the last call, then return 0.
  35824. */
  35825. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  35826. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  35827. ** by the pager layer on the database file.
  35828. */
  35829. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  35830. /* Return true if the argument is non-NULL and the WAL module is using
  35831. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  35832. ** WAL module is using shared-memory, return false.
  35833. */
  35834. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  35835. #ifdef SQLITE_ENABLE_ZIPVFS
  35836. /* If the WAL file is not empty, return the number of bytes of content
  35837. ** stored in each frame (i.e. the db page-size when the WAL was created).
  35838. */
  35839. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  35840. #endif
  35841. #endif /* ifndef SQLITE_OMIT_WAL */
  35842. #endif /* _WAL_H_ */
  35843. /************** End of wal.h *************************************************/
  35844. /************** Continuing where we left off in pager.c **********************/
  35845. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  35846. **
  35847. ** This comment block describes invariants that hold when using a rollback
  35848. ** journal. These invariants do not apply for journal_mode=WAL,
  35849. ** journal_mode=MEMORY, or journal_mode=OFF.
  35850. **
  35851. ** Within this comment block, a page is deemed to have been synced
  35852. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  35853. ** Otherwise, the page is not synced until the xSync method of the VFS
  35854. ** is called successfully on the file containing the page.
  35855. **
  35856. ** Definition: A page of the database file is said to be "overwriteable" if
  35857. ** one or more of the following are true about the page:
  35858. **
  35859. ** (a) The original content of the page as it was at the beginning of
  35860. ** the transaction has been written into the rollback journal and
  35861. ** synced.
  35862. **
  35863. ** (b) The page was a freelist leaf page at the start of the transaction.
  35864. **
  35865. ** (c) The page number is greater than the largest page that existed in
  35866. ** the database file at the start of the transaction.
  35867. **
  35868. ** (1) A page of the database file is never overwritten unless one of the
  35869. ** following are true:
  35870. **
  35871. ** (a) The page and all other pages on the same sector are overwriteable.
  35872. **
  35873. ** (b) The atomic page write optimization is enabled, and the entire
  35874. ** transaction other than the update of the transaction sequence
  35875. ** number consists of a single page change.
  35876. **
  35877. ** (2) The content of a page written into the rollback journal exactly matches
  35878. ** both the content in the database when the rollback journal was written
  35879. ** and the content in the database at the beginning of the current
  35880. ** transaction.
  35881. **
  35882. ** (3) Writes to the database file are an integer multiple of the page size
  35883. ** in length and are aligned on a page boundary.
  35884. **
  35885. ** (4) Reads from the database file are either aligned on a page boundary and
  35886. ** an integer multiple of the page size in length or are taken from the
  35887. ** first 100 bytes of the database file.
  35888. **
  35889. ** (5) All writes to the database file are synced prior to the rollback journal
  35890. ** being deleted, truncated, or zeroed.
  35891. **
  35892. ** (6) If a master journal file is used, then all writes to the database file
  35893. ** are synced prior to the master journal being deleted.
  35894. **
  35895. ** Definition: Two databases (or the same database at two points it time)
  35896. ** are said to be "logically equivalent" if they give the same answer to
  35897. ** all queries. Note in particular the content of freelist leaf
  35898. ** pages can be changed arbitarily without effecting the logical equivalence
  35899. ** of the database.
  35900. **
  35901. ** (7) At any time, if any subset, including the empty set and the total set,
  35902. ** of the unsynced changes to a rollback journal are removed and the
  35903. ** journal is rolled back, the resulting database file will be logical
  35904. ** equivalent to the database file at the beginning of the transaction.
  35905. **
  35906. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  35907. ** is called to restore the database file to the same size it was at
  35908. ** the beginning of the transaction. (In some VFSes, the xTruncate
  35909. ** method is a no-op, but that does not change the fact the SQLite will
  35910. ** invoke it.)
  35911. **
  35912. ** (9) Whenever the database file is modified, at least one bit in the range
  35913. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  35914. ** the EXCLUSIVE lock, thus signaling other connections on the same
  35915. ** database to flush their caches.
  35916. **
  35917. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  35918. ** than one billion transactions.
  35919. **
  35920. ** (11) A database file is well-formed at the beginning and at the conclusion
  35921. ** of every transaction.
  35922. **
  35923. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  35924. ** the database file.
  35925. **
  35926. ** (13) A SHARED lock is held on the database file while reading any
  35927. ** content out of the database file.
  35928. **
  35929. ******************************************************************************/
  35930. /*
  35931. ** Macros for troubleshooting. Normally turned off
  35932. */
  35933. #if 0
  35934. int sqlite3PagerTrace=1; /* True to enable tracing */
  35935. #define sqlite3DebugPrintf printf
  35936. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  35937. #else
  35938. #define PAGERTRACE(X)
  35939. #endif
  35940. /*
  35941. ** The following two macros are used within the PAGERTRACE() macros above
  35942. ** to print out file-descriptors.
  35943. **
  35944. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  35945. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  35946. ** struct as its argument.
  35947. */
  35948. #define PAGERID(p) ((int)(p->fd))
  35949. #define FILEHANDLEID(fd) ((int)fd)
  35950. /*
  35951. ** The Pager.eState variable stores the current 'state' of a pager. A
  35952. ** pager may be in any one of the seven states shown in the following
  35953. ** state diagram.
  35954. **
  35955. ** OPEN <------+------+
  35956. ** | | |
  35957. ** V | |
  35958. ** +---------> READER-------+ |
  35959. ** | | |
  35960. ** | V |
  35961. ** |<-------WRITER_LOCKED------> ERROR
  35962. ** | | ^
  35963. ** | V |
  35964. ** |<------WRITER_CACHEMOD-------->|
  35965. ** | | |
  35966. ** | V |
  35967. ** |<-------WRITER_DBMOD---------->|
  35968. ** | | |
  35969. ** | V |
  35970. ** +<------WRITER_FINISHED-------->+
  35971. **
  35972. **
  35973. ** List of state transitions and the C [function] that performs each:
  35974. **
  35975. ** OPEN -> READER [sqlite3PagerSharedLock]
  35976. ** READER -> OPEN [pager_unlock]
  35977. **
  35978. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  35979. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  35980. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  35981. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  35982. ** WRITER_*** -> READER [pager_end_transaction]
  35983. **
  35984. ** WRITER_*** -> ERROR [pager_error]
  35985. ** ERROR -> OPEN [pager_unlock]
  35986. **
  35987. **
  35988. ** OPEN:
  35989. **
  35990. ** The pager starts up in this state. Nothing is guaranteed in this
  35991. ** state - the file may or may not be locked and the database size is
  35992. ** unknown. The database may not be read or written.
  35993. **
  35994. ** * No read or write transaction is active.
  35995. ** * Any lock, or no lock at all, may be held on the database file.
  35996. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  35997. **
  35998. ** READER:
  35999. **
  36000. ** In this state all the requirements for reading the database in
  36001. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  36002. ** was) in exclusive-locking mode, a user-level read transaction is
  36003. ** open. The database size is known in this state.
  36004. **
  36005. ** A connection running with locking_mode=normal enters this state when
  36006. ** it opens a read-transaction on the database and returns to state
  36007. ** OPEN after the read-transaction is completed. However a connection
  36008. ** running in locking_mode=exclusive (including temp databases) remains in
  36009. ** this state even after the read-transaction is closed. The only way
  36010. ** a locking_mode=exclusive connection can transition from READER to OPEN
  36011. ** is via the ERROR state (see below).
  36012. **
  36013. ** * A read transaction may be active (but a write-transaction cannot).
  36014. ** * A SHARED or greater lock is held on the database file.
  36015. ** * The dbSize variable may be trusted (even if a user-level read
  36016. ** transaction is not active). The dbOrigSize and dbFileSize variables
  36017. ** may not be trusted at this point.
  36018. ** * If the database is a WAL database, then the WAL connection is open.
  36019. ** * Even if a read-transaction is not open, it is guaranteed that
  36020. ** there is no hot-journal in the file-system.
  36021. **
  36022. ** WRITER_LOCKED:
  36023. **
  36024. ** The pager moves to this state from READER when a write-transaction
  36025. ** is first opened on the database. In WRITER_LOCKED state, all locks
  36026. ** required to start a write-transaction are held, but no actual
  36027. ** modifications to the cache or database have taken place.
  36028. **
  36029. ** In rollback mode, a RESERVED or (if the transaction was opened with
  36030. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  36031. ** moving to this state, but the journal file is not written to or opened
  36032. ** to in this state. If the transaction is committed or rolled back while
  36033. ** in WRITER_LOCKED state, all that is required is to unlock the database
  36034. ** file.
  36035. **
  36036. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  36037. ** If the connection is running with locking_mode=exclusive, an attempt
  36038. ** is made to obtain an EXCLUSIVE lock on the database file.
  36039. **
  36040. ** * A write transaction is active.
  36041. ** * If the connection is open in rollback-mode, a RESERVED or greater
  36042. ** lock is held on the database file.
  36043. ** * If the connection is open in WAL-mode, a WAL write transaction
  36044. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  36045. ** called).
  36046. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  36047. ** * The contents of the pager cache have not been modified.
  36048. ** * The journal file may or may not be open.
  36049. ** * Nothing (not even the first header) has been written to the journal.
  36050. **
  36051. ** WRITER_CACHEMOD:
  36052. **
  36053. ** A pager moves from WRITER_LOCKED state to this state when a page is
  36054. ** first modified by the upper layer. In rollback mode the journal file
  36055. ** is opened (if it is not already open) and a header written to the
  36056. ** start of it. The database file on disk has not been modified.
  36057. **
  36058. ** * A write transaction is active.
  36059. ** * A RESERVED or greater lock is held on the database file.
  36060. ** * The journal file is open and the first header has been written
  36061. ** to it, but the header has not been synced to disk.
  36062. ** * The contents of the page cache have been modified.
  36063. **
  36064. ** WRITER_DBMOD:
  36065. **
  36066. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  36067. ** when it modifies the contents of the database file. WAL connections
  36068. ** never enter this state (since they do not modify the database file,
  36069. ** just the log file).
  36070. **
  36071. ** * A write transaction is active.
  36072. ** * An EXCLUSIVE or greater lock is held on the database file.
  36073. ** * The journal file is open and the first header has been written
  36074. ** and synced to disk.
  36075. ** * The contents of the page cache have been modified (and possibly
  36076. ** written to disk).
  36077. **
  36078. ** WRITER_FINISHED:
  36079. **
  36080. ** It is not possible for a WAL connection to enter this state.
  36081. **
  36082. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  36083. ** state after the entire transaction has been successfully written into the
  36084. ** database file. In this state the transaction may be committed simply
  36085. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  36086. ** not possible to modify the database further. At this point, the upper
  36087. ** layer must either commit or rollback the transaction.
  36088. **
  36089. ** * A write transaction is active.
  36090. ** * An EXCLUSIVE or greater lock is held on the database file.
  36091. ** * All writing and syncing of journal and database data has finished.
  36092. ** If no error occurred, all that remains is to finalize the journal to
  36093. ** commit the transaction. If an error did occur, the caller will need
  36094. ** to rollback the transaction.
  36095. **
  36096. ** ERROR:
  36097. **
  36098. ** The ERROR state is entered when an IO or disk-full error (including
  36099. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  36100. ** difficult to be sure that the in-memory pager state (cache contents,
  36101. ** db size etc.) are consistent with the contents of the file-system.
  36102. **
  36103. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  36104. ** cannot.
  36105. **
  36106. ** For example, if an IO error occurs while performing a rollback,
  36107. ** the contents of the page-cache may be left in an inconsistent state.
  36108. ** At this point it would be dangerous to change back to READER state
  36109. ** (as usually happens after a rollback). Any subsequent readers might
  36110. ** report database corruption (due to the inconsistent cache), and if
  36111. ** they upgrade to writers, they may inadvertently corrupt the database
  36112. ** file. To avoid this hazard, the pager switches into the ERROR state
  36113. ** instead of READER following such an error.
  36114. **
  36115. ** Once it has entered the ERROR state, any attempt to use the pager
  36116. ** to read or write data returns an error. Eventually, once all
  36117. ** outstanding transactions have been abandoned, the pager is able to
  36118. ** transition back to OPEN state, discarding the contents of the
  36119. ** page-cache and any other in-memory state at the same time. Everything
  36120. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  36121. ** when a read-transaction is next opened on the pager (transitioning
  36122. ** the pager into READER state). At that point the system has recovered
  36123. ** from the error.
  36124. **
  36125. ** Specifically, the pager jumps into the ERROR state if:
  36126. **
  36127. ** 1. An error occurs while attempting a rollback. This happens in
  36128. ** function sqlite3PagerRollback().
  36129. **
  36130. ** 2. An error occurs while attempting to finalize a journal file
  36131. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  36132. **
  36133. ** 3. An error occurs while attempting to write to the journal or
  36134. ** database file in function pagerStress() in order to free up
  36135. ** memory.
  36136. **
  36137. ** In other cases, the error is returned to the b-tree layer. The b-tree
  36138. ** layer then attempts a rollback operation. If the error condition
  36139. ** persists, the pager enters the ERROR state via condition (1) above.
  36140. **
  36141. ** Condition (3) is necessary because it can be triggered by a read-only
  36142. ** statement executed within a transaction. In this case, if the error
  36143. ** code were simply returned to the user, the b-tree layer would not
  36144. ** automatically attempt a rollback, as it assumes that an error in a
  36145. ** read-only statement cannot leave the pager in an internally inconsistent
  36146. ** state.
  36147. **
  36148. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  36149. ** * There are one or more outstanding references to pages (after the
  36150. ** last reference is dropped the pager should move back to OPEN state).
  36151. ** * The pager is not an in-memory pager.
  36152. **
  36153. **
  36154. ** Notes:
  36155. **
  36156. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  36157. ** connection is open in WAL mode. A WAL connection is always in one
  36158. ** of the first four states.
  36159. **
  36160. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  36161. ** state. There are two exceptions: immediately after exclusive-mode has
  36162. ** been turned on (and before any read or write transactions are
  36163. ** executed), and when the pager is leaving the "error state".
  36164. **
  36165. ** * See also: assert_pager_state().
  36166. */
  36167. #define PAGER_OPEN 0
  36168. #define PAGER_READER 1
  36169. #define PAGER_WRITER_LOCKED 2
  36170. #define PAGER_WRITER_CACHEMOD 3
  36171. #define PAGER_WRITER_DBMOD 4
  36172. #define PAGER_WRITER_FINISHED 5
  36173. #define PAGER_ERROR 6
  36174. /*
  36175. ** The Pager.eLock variable is almost always set to one of the
  36176. ** following locking-states, according to the lock currently held on
  36177. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  36178. ** This variable is kept up to date as locks are taken and released by
  36179. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  36180. **
  36181. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  36182. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  36183. ** the operation was successful. In these circumstances pagerLockDb() and
  36184. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  36185. ** when unlocking the file, and only updated when locking the file if the
  36186. ** VFS call is successful. This way, the Pager.eLock variable may be set
  36187. ** to a less exclusive (lower) value than the lock that is actually held
  36188. ** at the system level, but it is never set to a more exclusive value.
  36189. **
  36190. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  36191. ** be a few redundant xLock() calls or a lock may be held for longer than
  36192. ** required, but nothing really goes wrong.
  36193. **
  36194. ** The exception is when the database file is unlocked as the pager moves
  36195. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  36196. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  36197. ** transition, by the same pager or any other). If the call to xUnlock()
  36198. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  36199. ** can confuse the call to xCheckReservedLock() call made later as part
  36200. ** of hot-journal detection.
  36201. **
  36202. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  36203. ** lock held by this process or any others". So xCheckReservedLock may
  36204. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  36205. ** doesn't know it because of a previous error in xUnlock). If this happens
  36206. ** a hot-journal may be mistaken for a journal being created by an active
  36207. ** transaction in another process, causing SQLite to read from the database
  36208. ** without rolling it back.
  36209. **
  36210. ** To work around this, if a call to xUnlock() fails when unlocking the
  36211. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  36212. ** is only changed back to a real locking state after a successful call
  36213. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  36214. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  36215. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  36216. ** lock on the database file before attempting to roll it back. See function
  36217. ** PagerSharedLock() for more detail.
  36218. **
  36219. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  36220. ** PAGER_OPEN state.
  36221. */
  36222. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  36223. /*
  36224. ** A macro used for invoking the codec if there is one
  36225. */
  36226. #ifdef SQLITE_HAS_CODEC
  36227. # define CODEC1(P,D,N,X,E) \
  36228. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  36229. # define CODEC2(P,D,N,X,E,O) \
  36230. if( P->xCodec==0 ){ O=(char*)D; }else \
  36231. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  36232. #else
  36233. # define CODEC1(P,D,N,X,E) /* NO-OP */
  36234. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  36235. #endif
  36236. /*
  36237. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  36238. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  36239. ** This could conceivably cause corruption following a power failure on
  36240. ** such a system. This is currently an undocumented limit.
  36241. */
  36242. #define MAX_SECTOR_SIZE 0x10000
  36243. /*
  36244. ** An instance of the following structure is allocated for each active
  36245. ** savepoint and statement transaction in the system. All such structures
  36246. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  36247. ** resized using sqlite3Realloc().
  36248. **
  36249. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  36250. ** set to 0. If a journal-header is written into the main journal while
  36251. ** the savepoint is active, then iHdrOffset is set to the byte offset
  36252. ** immediately following the last journal record written into the main
  36253. ** journal before the journal-header. This is required during savepoint
  36254. ** rollback (see pagerPlaybackSavepoint()).
  36255. */
  36256. typedef struct PagerSavepoint PagerSavepoint;
  36257. struct PagerSavepoint {
  36258. i64 iOffset; /* Starting offset in main journal */
  36259. i64 iHdrOffset; /* See above */
  36260. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  36261. Pgno nOrig; /* Original number of pages in file */
  36262. Pgno iSubRec; /* Index of first record in sub-journal */
  36263. #ifndef SQLITE_OMIT_WAL
  36264. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  36265. #endif
  36266. };
  36267. /*
  36268. ** A open page cache is an instance of struct Pager. A description of
  36269. ** some of the more important member variables follows:
  36270. **
  36271. ** eState
  36272. **
  36273. ** The current 'state' of the pager object. See the comment and state
  36274. ** diagram above for a description of the pager state.
  36275. **
  36276. ** eLock
  36277. **
  36278. ** For a real on-disk database, the current lock held on the database file -
  36279. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  36280. **
  36281. ** For a temporary or in-memory database (neither of which require any
  36282. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  36283. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  36284. ** logic into thinking that it already has all the locks it will ever
  36285. ** need (and no reason to release them).
  36286. **
  36287. ** In some (obscure) circumstances, this variable may also be set to
  36288. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  36289. ** details.
  36290. **
  36291. ** changeCountDone
  36292. **
  36293. ** This boolean variable is used to make sure that the change-counter
  36294. ** (the 4-byte header field at byte offset 24 of the database file) is
  36295. ** not updated more often than necessary.
  36296. **
  36297. ** It is set to true when the change-counter field is updated, which
  36298. ** can only happen if an exclusive lock is held on the database file.
  36299. ** It is cleared (set to false) whenever an exclusive lock is
  36300. ** relinquished on the database file. Each time a transaction is committed,
  36301. ** The changeCountDone flag is inspected. If it is true, the work of
  36302. ** updating the change-counter is omitted for the current transaction.
  36303. **
  36304. ** This mechanism means that when running in exclusive mode, a connection
  36305. ** need only update the change-counter once, for the first transaction
  36306. ** committed.
  36307. **
  36308. ** setMaster
  36309. **
  36310. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  36311. ** (or may not) specify a master-journal name to be written into the
  36312. ** journal file before it is synced to disk.
  36313. **
  36314. ** Whether or not a journal file contains a master-journal pointer affects
  36315. ** the way in which the journal file is finalized after the transaction is
  36316. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  36317. ** If a journal file does not contain a master-journal pointer, it is
  36318. ** finalized by overwriting the first journal header with zeroes. If
  36319. ** it does contain a master-journal pointer the journal file is finalized
  36320. ** by truncating it to zero bytes, just as if the connection were
  36321. ** running in "journal_mode=truncate" mode.
  36322. **
  36323. ** Journal files that contain master journal pointers cannot be finalized
  36324. ** simply by overwriting the first journal-header with zeroes, as the
  36325. ** master journal pointer could interfere with hot-journal rollback of any
  36326. ** subsequently interrupted transaction that reuses the journal file.
  36327. **
  36328. ** The flag is cleared as soon as the journal file is finalized (either
  36329. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  36330. ** journal file from being successfully finalized, the setMaster flag
  36331. ** is cleared anyway (and the pager will move to ERROR state).
  36332. **
  36333. ** doNotSpill, doNotSyncSpill
  36334. **
  36335. ** These two boolean variables control the behavior of cache-spills
  36336. ** (calls made by the pcache module to the pagerStress() routine to
  36337. ** write cached data to the file-system in order to free up memory).
  36338. **
  36339. ** When doNotSpill is non-zero, writing to the database from pagerStress()
  36340. ** is disabled altogether. This is done in a very obscure case that
  36341. ** comes up during savepoint rollback that requires the pcache module
  36342. ** to allocate a new page to prevent the journal file from being written
  36343. ** while it is being traversed by code in pager_playback().
  36344. **
  36345. ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
  36346. ** is permitted, but syncing the journal file is not. This flag is set
  36347. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  36348. ** the database page-size in order to prevent a journal sync from happening
  36349. ** in between the journalling of two pages on the same sector.
  36350. **
  36351. ** subjInMemory
  36352. **
  36353. ** This is a boolean variable. If true, then any required sub-journal
  36354. ** is opened as an in-memory journal file. If false, then in-memory
  36355. ** sub-journals are only used for in-memory pager files.
  36356. **
  36357. ** This variable is updated by the upper layer each time a new
  36358. ** write-transaction is opened.
  36359. **
  36360. ** dbSize, dbOrigSize, dbFileSize
  36361. **
  36362. ** Variable dbSize is set to the number of pages in the database file.
  36363. ** It is valid in PAGER_READER and higher states (all states except for
  36364. ** OPEN and ERROR).
  36365. **
  36366. ** dbSize is set based on the size of the database file, which may be
  36367. ** larger than the size of the database (the value stored at offset
  36368. ** 28 of the database header by the btree). If the size of the file
  36369. ** is not an integer multiple of the page-size, the value stored in
  36370. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  36371. ** Except, any file that is greater than 0 bytes in size is considered
  36372. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  36373. ** to dbSize==1).
  36374. **
  36375. ** During a write-transaction, if pages with page-numbers greater than
  36376. ** dbSize are modified in the cache, dbSize is updated accordingly.
  36377. ** Similarly, if the database is truncated using PagerTruncateImage(),
  36378. ** dbSize is updated.
  36379. **
  36380. ** Variables dbOrigSize and dbFileSize are valid in states
  36381. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  36382. ** variable at the start of the transaction. It is used during rollback,
  36383. ** and to determine whether or not pages need to be journalled before
  36384. ** being modified.
  36385. **
  36386. ** Throughout a write-transaction, dbFileSize contains the size of
  36387. ** the file on disk in pages. It is set to a copy of dbSize when the
  36388. ** write-transaction is first opened, and updated when VFS calls are made
  36389. ** to write or truncate the database file on disk.
  36390. **
  36391. ** The only reason the dbFileSize variable is required is to suppress
  36392. ** unnecessary calls to xTruncate() after committing a transaction. If,
  36393. ** when a transaction is committed, the dbFileSize variable indicates
  36394. ** that the database file is larger than the database image (Pager.dbSize),
  36395. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  36396. ** to measure the database file on disk, and then truncates it if required.
  36397. ** dbFileSize is not used when rolling back a transaction. In this case
  36398. ** pager_truncate() is called unconditionally (which means there may be
  36399. ** a call to xFilesize() that is not strictly required). In either case,
  36400. ** pager_truncate() may cause the file to become smaller or larger.
  36401. **
  36402. ** dbHintSize
  36403. **
  36404. ** The dbHintSize variable is used to limit the number of calls made to
  36405. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  36406. **
  36407. ** dbHintSize is set to a copy of the dbSize variable when a
  36408. ** write-transaction is opened (at the same time as dbFileSize and
  36409. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  36410. ** dbHintSize is increased to the number of pages that correspond to the
  36411. ** size-hint passed to the method call. See pager_write_pagelist() for
  36412. ** details.
  36413. **
  36414. ** errCode
  36415. **
  36416. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  36417. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  36418. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  36419. ** sub-codes.
  36420. */
  36421. struct Pager {
  36422. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  36423. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  36424. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  36425. u8 useJournal; /* Use a rollback journal on this file */
  36426. u8 noSync; /* Do not sync the journal if true */
  36427. u8 fullSync; /* Do extra syncs of the journal for robustness */
  36428. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  36429. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  36430. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  36431. u8 tempFile; /* zFilename is a temporary file */
  36432. u8 readOnly; /* True for a read-only database */
  36433. u8 memDb; /* True to inhibit all file I/O */
  36434. /**************************************************************************
  36435. ** The following block contains those class members that change during
  36436. ** routine opertion. Class members not in this block are either fixed
  36437. ** when the pager is first created or else only change when there is a
  36438. ** significant mode change (such as changing the page_size, locking_mode,
  36439. ** or the journal_mode). From another view, these class members describe
  36440. ** the "state" of the pager, while other class members describe the
  36441. ** "configuration" of the pager.
  36442. */
  36443. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  36444. u8 eLock; /* Current lock held on database file */
  36445. u8 changeCountDone; /* Set after incrementing the change-counter */
  36446. u8 setMaster; /* True if a m-j name has been written to jrnl */
  36447. u8 doNotSpill; /* Do not spill the cache when non-zero */
  36448. u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
  36449. u8 subjInMemory; /* True to use in-memory sub-journals */
  36450. Pgno dbSize; /* Number of pages in the database */
  36451. Pgno dbOrigSize; /* dbSize before the current transaction */
  36452. Pgno dbFileSize; /* Number of pages in the database file */
  36453. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  36454. int errCode; /* One of several kinds of errors */
  36455. int nRec; /* Pages journalled since last j-header written */
  36456. u32 cksumInit; /* Quasi-random value added to every checksum */
  36457. u32 nSubRec; /* Number of records written to sub-journal */
  36458. Bitvec *pInJournal; /* One bit for each page in the database file */
  36459. sqlite3_file *fd; /* File descriptor for database */
  36460. sqlite3_file *jfd; /* File descriptor for main journal */
  36461. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  36462. i64 journalOff; /* Current write offset in the journal file */
  36463. i64 journalHdr; /* Byte offset to previous journal header */
  36464. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  36465. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  36466. int nSavepoint; /* Number of elements in aSavepoint[] */
  36467. char dbFileVers[16]; /* Changes whenever database file changes */
  36468. u8 bUseFetch; /* True to use xFetch() */
  36469. int nMmapOut; /* Number of mmap pages currently outstanding */
  36470. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  36471. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  36472. /*
  36473. ** End of the routinely-changing class members
  36474. ***************************************************************************/
  36475. u16 nExtra; /* Add this many bytes to each in-memory page */
  36476. i16 nReserve; /* Number of unused bytes at end of each page */
  36477. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  36478. u32 sectorSize; /* Assumed sector size during rollback */
  36479. int pageSize; /* Number of bytes in a page */
  36480. Pgno mxPgno; /* Maximum allowed size of the database */
  36481. i64 journalSizeLimit; /* Size limit for persistent journal files */
  36482. char *zFilename; /* Name of the database file */
  36483. char *zJournal; /* Name of the journal file */
  36484. int (*xBusyHandler)(void*); /* Function to call when busy */
  36485. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  36486. int aStat[3]; /* Total cache hits, misses and writes */
  36487. #ifdef SQLITE_TEST
  36488. int nRead; /* Database pages read */
  36489. #endif
  36490. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  36491. #ifdef SQLITE_HAS_CODEC
  36492. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  36493. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  36494. void (*xCodecFree)(void*); /* Destructor for the codec */
  36495. void *pCodec; /* First argument to xCodec... methods */
  36496. #endif
  36497. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  36498. PCache *pPCache; /* Pointer to page cache object */
  36499. #ifndef SQLITE_OMIT_WAL
  36500. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  36501. char *zWal; /* File name for write-ahead log */
  36502. #endif
  36503. };
  36504. /*
  36505. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  36506. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  36507. ** or CACHE_WRITE to sqlite3_db_status().
  36508. */
  36509. #define PAGER_STAT_HIT 0
  36510. #define PAGER_STAT_MISS 1
  36511. #define PAGER_STAT_WRITE 2
  36512. /*
  36513. ** The following global variables hold counters used for
  36514. ** testing purposes only. These variables do not exist in
  36515. ** a non-testing build. These variables are not thread-safe.
  36516. */
  36517. #ifdef SQLITE_TEST
  36518. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  36519. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  36520. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  36521. # define PAGER_INCR(v) v++
  36522. #else
  36523. # define PAGER_INCR(v)
  36524. #endif
  36525. /*
  36526. ** Journal files begin with the following magic string. The data
  36527. ** was obtained from /dev/random. It is used only as a sanity check.
  36528. **
  36529. ** Since version 2.8.0, the journal format contains additional sanity
  36530. ** checking information. If the power fails while the journal is being
  36531. ** written, semi-random garbage data might appear in the journal
  36532. ** file after power is restored. If an attempt is then made
  36533. ** to roll the journal back, the database could be corrupted. The additional
  36534. ** sanity checking data is an attempt to discover the garbage in the
  36535. ** journal and ignore it.
  36536. **
  36537. ** The sanity checking information for the new journal format consists
  36538. ** of a 32-bit checksum on each page of data. The checksum covers both
  36539. ** the page number and the pPager->pageSize bytes of data for the page.
  36540. ** This cksum is initialized to a 32-bit random value that appears in the
  36541. ** journal file right after the header. The random initializer is important,
  36542. ** because garbage data that appears at the end of a journal is likely
  36543. ** data that was once in other files that have now been deleted. If the
  36544. ** garbage data came from an obsolete journal file, the checksums might
  36545. ** be correct. But by initializing the checksum to random value which
  36546. ** is different for every journal, we minimize that risk.
  36547. */
  36548. static const unsigned char aJournalMagic[] = {
  36549. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  36550. };
  36551. /*
  36552. ** The size of the of each page record in the journal is given by
  36553. ** the following macro.
  36554. */
  36555. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  36556. /*
  36557. ** The journal header size for this pager. This is usually the same
  36558. ** size as a single disk sector. See also setSectorSize().
  36559. */
  36560. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  36561. /*
  36562. ** The macro MEMDB is true if we are dealing with an in-memory database.
  36563. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  36564. ** the value of MEMDB will be a constant and the compiler will optimize
  36565. ** out code that would never execute.
  36566. */
  36567. #ifdef SQLITE_OMIT_MEMORYDB
  36568. # define MEMDB 0
  36569. #else
  36570. # define MEMDB pPager->memDb
  36571. #endif
  36572. /*
  36573. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  36574. ** interfaces to access the database using memory-mapped I/O.
  36575. */
  36576. #if SQLITE_MAX_MMAP_SIZE>0
  36577. # define USEFETCH(x) ((x)->bUseFetch)
  36578. #else
  36579. # define USEFETCH(x) 0
  36580. #endif
  36581. /*
  36582. ** The maximum legal page number is (2^31 - 1).
  36583. */
  36584. #define PAGER_MAX_PGNO 2147483647
  36585. /*
  36586. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  36587. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  36588. **
  36589. ** This is so that expressions can be written as:
  36590. **
  36591. ** if( isOpen(pPager->jfd) ){ ...
  36592. **
  36593. ** instead of
  36594. **
  36595. ** if( pPager->jfd->pMethods ){ ...
  36596. */
  36597. #define isOpen(pFd) ((pFd)->pMethods)
  36598. /*
  36599. ** Return true if this pager uses a write-ahead log instead of the usual
  36600. ** rollback journal. Otherwise false.
  36601. */
  36602. #ifndef SQLITE_OMIT_WAL
  36603. static int pagerUseWal(Pager *pPager){
  36604. return (pPager->pWal!=0);
  36605. }
  36606. #else
  36607. # define pagerUseWal(x) 0
  36608. # define pagerRollbackWal(x) 0
  36609. # define pagerWalFrames(v,w,x,y) 0
  36610. # define pagerOpenWalIfPresent(z) SQLITE_OK
  36611. # define pagerBeginReadTransaction(z) SQLITE_OK
  36612. #endif
  36613. #ifndef NDEBUG
  36614. /*
  36615. ** Usage:
  36616. **
  36617. ** assert( assert_pager_state(pPager) );
  36618. **
  36619. ** This function runs many asserts to try to find inconsistencies in
  36620. ** the internal state of the Pager object.
  36621. */
  36622. static int assert_pager_state(Pager *p){
  36623. Pager *pPager = p;
  36624. /* State must be valid. */
  36625. assert( p->eState==PAGER_OPEN
  36626. || p->eState==PAGER_READER
  36627. || p->eState==PAGER_WRITER_LOCKED
  36628. || p->eState==PAGER_WRITER_CACHEMOD
  36629. || p->eState==PAGER_WRITER_DBMOD
  36630. || p->eState==PAGER_WRITER_FINISHED
  36631. || p->eState==PAGER_ERROR
  36632. );
  36633. /* Regardless of the current state, a temp-file connection always behaves
  36634. ** as if it has an exclusive lock on the database file. It never updates
  36635. ** the change-counter field, so the changeCountDone flag is always set.
  36636. */
  36637. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  36638. assert( p->tempFile==0 || pPager->changeCountDone );
  36639. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  36640. ** And if the journal-mode is "OFF", the journal file must not be open.
  36641. */
  36642. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  36643. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  36644. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  36645. ** this means an in-memory pager performs no IO at all, it cannot encounter
  36646. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  36647. ** a journal file. (although the in-memory journal implementation may
  36648. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  36649. ** is therefore not possible for an in-memory pager to enter the ERROR
  36650. ** state.
  36651. */
  36652. if( MEMDB ){
  36653. assert( p->noSync );
  36654. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  36655. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  36656. );
  36657. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  36658. assert( pagerUseWal(p)==0 );
  36659. }
  36660. /* If changeCountDone is set, a RESERVED lock or greater must be held
  36661. ** on the file.
  36662. */
  36663. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  36664. assert( p->eLock!=PENDING_LOCK );
  36665. switch( p->eState ){
  36666. case PAGER_OPEN:
  36667. assert( !MEMDB );
  36668. assert( pPager->errCode==SQLITE_OK );
  36669. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  36670. break;
  36671. case PAGER_READER:
  36672. assert( pPager->errCode==SQLITE_OK );
  36673. assert( p->eLock!=UNKNOWN_LOCK );
  36674. assert( p->eLock>=SHARED_LOCK );
  36675. break;
  36676. case PAGER_WRITER_LOCKED:
  36677. assert( p->eLock!=UNKNOWN_LOCK );
  36678. assert( pPager->errCode==SQLITE_OK );
  36679. if( !pagerUseWal(pPager) ){
  36680. assert( p->eLock>=RESERVED_LOCK );
  36681. }
  36682. assert( pPager->dbSize==pPager->dbOrigSize );
  36683. assert( pPager->dbOrigSize==pPager->dbFileSize );
  36684. assert( pPager->dbOrigSize==pPager->dbHintSize );
  36685. assert( pPager->setMaster==0 );
  36686. break;
  36687. case PAGER_WRITER_CACHEMOD:
  36688. assert( p->eLock!=UNKNOWN_LOCK );
  36689. assert( pPager->errCode==SQLITE_OK );
  36690. if( !pagerUseWal(pPager) ){
  36691. /* It is possible that if journal_mode=wal here that neither the
  36692. ** journal file nor the WAL file are open. This happens during
  36693. ** a rollback transaction that switches from journal_mode=off
  36694. ** to journal_mode=wal.
  36695. */
  36696. assert( p->eLock>=RESERVED_LOCK );
  36697. assert( isOpen(p->jfd)
  36698. || p->journalMode==PAGER_JOURNALMODE_OFF
  36699. || p->journalMode==PAGER_JOURNALMODE_WAL
  36700. );
  36701. }
  36702. assert( pPager->dbOrigSize==pPager->dbFileSize );
  36703. assert( pPager->dbOrigSize==pPager->dbHintSize );
  36704. break;
  36705. case PAGER_WRITER_DBMOD:
  36706. assert( p->eLock==EXCLUSIVE_LOCK );
  36707. assert( pPager->errCode==SQLITE_OK );
  36708. assert( !pagerUseWal(pPager) );
  36709. assert( p->eLock>=EXCLUSIVE_LOCK );
  36710. assert( isOpen(p->jfd)
  36711. || p->journalMode==PAGER_JOURNALMODE_OFF
  36712. || p->journalMode==PAGER_JOURNALMODE_WAL
  36713. );
  36714. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  36715. break;
  36716. case PAGER_WRITER_FINISHED:
  36717. assert( p->eLock==EXCLUSIVE_LOCK );
  36718. assert( pPager->errCode==SQLITE_OK );
  36719. assert( !pagerUseWal(pPager) );
  36720. assert( isOpen(p->jfd)
  36721. || p->journalMode==PAGER_JOURNALMODE_OFF
  36722. || p->journalMode==PAGER_JOURNALMODE_WAL
  36723. );
  36724. break;
  36725. case PAGER_ERROR:
  36726. /* There must be at least one outstanding reference to the pager if
  36727. ** in ERROR state. Otherwise the pager should have already dropped
  36728. ** back to OPEN state.
  36729. */
  36730. assert( pPager->errCode!=SQLITE_OK );
  36731. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  36732. break;
  36733. }
  36734. return 1;
  36735. }
  36736. #endif /* ifndef NDEBUG */
  36737. #ifdef SQLITE_DEBUG
  36738. /*
  36739. ** Return a pointer to a human readable string in a static buffer
  36740. ** containing the state of the Pager object passed as an argument. This
  36741. ** is intended to be used within debuggers. For example, as an alternative
  36742. ** to "print *pPager" in gdb:
  36743. **
  36744. ** (gdb) printf "%s", print_pager_state(pPager)
  36745. */
  36746. static char *print_pager_state(Pager *p){
  36747. static char zRet[1024];
  36748. sqlite3_snprintf(1024, zRet,
  36749. "Filename: %s\n"
  36750. "State: %s errCode=%d\n"
  36751. "Lock: %s\n"
  36752. "Locking mode: locking_mode=%s\n"
  36753. "Journal mode: journal_mode=%s\n"
  36754. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  36755. "Journal: journalOff=%lld journalHdr=%lld\n"
  36756. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  36757. , p->zFilename
  36758. , p->eState==PAGER_OPEN ? "OPEN" :
  36759. p->eState==PAGER_READER ? "READER" :
  36760. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  36761. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  36762. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  36763. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  36764. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  36765. , (int)p->errCode
  36766. , p->eLock==NO_LOCK ? "NO_LOCK" :
  36767. p->eLock==RESERVED_LOCK ? "RESERVED" :
  36768. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  36769. p->eLock==SHARED_LOCK ? "SHARED" :
  36770. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  36771. , p->exclusiveMode ? "exclusive" : "normal"
  36772. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  36773. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  36774. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  36775. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  36776. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  36777. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  36778. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  36779. , p->journalOff, p->journalHdr
  36780. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  36781. );
  36782. return zRet;
  36783. }
  36784. #endif
  36785. /*
  36786. ** Return true if it is necessary to write page *pPg into the sub-journal.
  36787. ** A page needs to be written into the sub-journal if there exists one
  36788. ** or more open savepoints for which:
  36789. **
  36790. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  36791. ** * The bit corresponding to the page-number is not set in
  36792. ** PagerSavepoint.pInSavepoint.
  36793. */
  36794. static int subjRequiresPage(PgHdr *pPg){
  36795. Pgno pgno = pPg->pgno;
  36796. Pager *pPager = pPg->pPager;
  36797. int i;
  36798. for(i=0; i<pPager->nSavepoint; i++){
  36799. PagerSavepoint *p = &pPager->aSavepoint[i];
  36800. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  36801. return 1;
  36802. }
  36803. }
  36804. return 0;
  36805. }
  36806. /*
  36807. ** Return true if the page is already in the journal file.
  36808. */
  36809. static int pageInJournal(PgHdr *pPg){
  36810. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  36811. }
  36812. /*
  36813. ** Read a 32-bit integer from the given file descriptor. Store the integer
  36814. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  36815. ** error code is something goes wrong.
  36816. **
  36817. ** All values are stored on disk as big-endian.
  36818. */
  36819. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  36820. unsigned char ac[4];
  36821. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  36822. if( rc==SQLITE_OK ){
  36823. *pRes = sqlite3Get4byte(ac);
  36824. }
  36825. return rc;
  36826. }
  36827. /*
  36828. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  36829. */
  36830. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  36831. /*
  36832. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  36833. ** on success or an error code is something goes wrong.
  36834. */
  36835. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  36836. char ac[4];
  36837. put32bits(ac, val);
  36838. return sqlite3OsWrite(fd, ac, 4, offset);
  36839. }
  36840. /*
  36841. ** Unlock the database file to level eLock, which must be either NO_LOCK
  36842. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  36843. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  36844. **
  36845. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  36846. ** called, do not modify it. See the comment above the #define of
  36847. ** UNKNOWN_LOCK for an explanation of this.
  36848. */
  36849. static int pagerUnlockDb(Pager *pPager, int eLock){
  36850. int rc = SQLITE_OK;
  36851. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  36852. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  36853. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  36854. if( isOpen(pPager->fd) ){
  36855. assert( pPager->eLock>=eLock );
  36856. rc = sqlite3OsUnlock(pPager->fd, eLock);
  36857. if( pPager->eLock!=UNKNOWN_LOCK ){
  36858. pPager->eLock = (u8)eLock;
  36859. }
  36860. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  36861. }
  36862. return rc;
  36863. }
  36864. /*
  36865. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  36866. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  36867. ** Pager.eLock variable to the new locking state.
  36868. **
  36869. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  36870. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  36871. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  36872. ** of this.
  36873. */
  36874. static int pagerLockDb(Pager *pPager, int eLock){
  36875. int rc = SQLITE_OK;
  36876. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  36877. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  36878. rc = sqlite3OsLock(pPager->fd, eLock);
  36879. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  36880. pPager->eLock = (u8)eLock;
  36881. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  36882. }
  36883. }
  36884. return rc;
  36885. }
  36886. /*
  36887. ** This function determines whether or not the atomic-write optimization
  36888. ** can be used with this pager. The optimization can be used if:
  36889. **
  36890. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  36891. ** a database page may be written atomically, and
  36892. ** (b) the value returned by OsSectorSize() is less than or equal
  36893. ** to the page size.
  36894. **
  36895. ** The optimization is also always enabled for temporary files. It is
  36896. ** an error to call this function if pPager is opened on an in-memory
  36897. ** database.
  36898. **
  36899. ** If the optimization cannot be used, 0 is returned. If it can be used,
  36900. ** then the value returned is the size of the journal file when it
  36901. ** contains rollback data for exactly one page.
  36902. */
  36903. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  36904. static int jrnlBufferSize(Pager *pPager){
  36905. assert( !MEMDB );
  36906. if( !pPager->tempFile ){
  36907. int dc; /* Device characteristics */
  36908. int nSector; /* Sector size */
  36909. int szPage; /* Page size */
  36910. assert( isOpen(pPager->fd) );
  36911. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  36912. nSector = pPager->sectorSize;
  36913. szPage = pPager->pageSize;
  36914. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  36915. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  36916. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  36917. return 0;
  36918. }
  36919. }
  36920. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  36921. }
  36922. #endif
  36923. /*
  36924. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  36925. ** on the cache using a hash function. This is used for testing
  36926. ** and debugging only.
  36927. */
  36928. #ifdef SQLITE_CHECK_PAGES
  36929. /*
  36930. ** Return a 32-bit hash of the page data for pPage.
  36931. */
  36932. static u32 pager_datahash(int nByte, unsigned char *pData){
  36933. u32 hash = 0;
  36934. int i;
  36935. for(i=0; i<nByte; i++){
  36936. hash = (hash*1039) + pData[i];
  36937. }
  36938. return hash;
  36939. }
  36940. static u32 pager_pagehash(PgHdr *pPage){
  36941. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  36942. }
  36943. static void pager_set_pagehash(PgHdr *pPage){
  36944. pPage->pageHash = pager_pagehash(pPage);
  36945. }
  36946. /*
  36947. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  36948. ** is defined, and NDEBUG is not defined, an assert() statement checks
  36949. ** that the page is either dirty or still matches the calculated page-hash.
  36950. */
  36951. #define CHECK_PAGE(x) checkPage(x)
  36952. static void checkPage(PgHdr *pPg){
  36953. Pager *pPager = pPg->pPager;
  36954. assert( pPager->eState!=PAGER_ERROR );
  36955. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  36956. }
  36957. #else
  36958. #define pager_datahash(X,Y) 0
  36959. #define pager_pagehash(X) 0
  36960. #define pager_set_pagehash(X)
  36961. #define CHECK_PAGE(x)
  36962. #endif /* SQLITE_CHECK_PAGES */
  36963. /*
  36964. ** When this is called the journal file for pager pPager must be open.
  36965. ** This function attempts to read a master journal file name from the
  36966. ** end of the file and, if successful, copies it into memory supplied
  36967. ** by the caller. See comments above writeMasterJournal() for the format
  36968. ** used to store a master journal file name at the end of a journal file.
  36969. **
  36970. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  36971. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  36972. ** enough space to write the master journal name). If the master journal
  36973. ** name in the journal is longer than nMaster bytes (including a
  36974. ** nul-terminator), then this is handled as if no master journal name
  36975. ** were present in the journal.
  36976. **
  36977. ** If a master journal file name is present at the end of the journal
  36978. ** file, then it is copied into the buffer pointed to by zMaster. A
  36979. ** nul-terminator byte is appended to the buffer following the master
  36980. ** journal file name.
  36981. **
  36982. ** If it is determined that no master journal file name is present
  36983. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  36984. **
  36985. ** If an error occurs while reading from the journal file, an SQLite
  36986. ** error code is returned.
  36987. */
  36988. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  36989. int rc; /* Return code */
  36990. u32 len; /* Length in bytes of master journal name */
  36991. i64 szJ; /* Total size in bytes of journal file pJrnl */
  36992. u32 cksum; /* MJ checksum value read from journal */
  36993. u32 u; /* Unsigned loop counter */
  36994. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  36995. zMaster[0] = '\0';
  36996. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  36997. || szJ<16
  36998. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  36999. || len>=nMaster
  37000. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  37001. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  37002. || memcmp(aMagic, aJournalMagic, 8)
  37003. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  37004. ){
  37005. return rc;
  37006. }
  37007. /* See if the checksum matches the master journal name */
  37008. for(u=0; u<len; u++){
  37009. cksum -= zMaster[u];
  37010. }
  37011. if( cksum ){
  37012. /* If the checksum doesn't add up, then one or more of the disk sectors
  37013. ** containing the master journal filename is corrupted. This means
  37014. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  37015. ** master-journal filename.
  37016. */
  37017. len = 0;
  37018. }
  37019. zMaster[len] = '\0';
  37020. return SQLITE_OK;
  37021. }
  37022. /*
  37023. ** Return the offset of the sector boundary at or immediately
  37024. ** following the value in pPager->journalOff, assuming a sector
  37025. ** size of pPager->sectorSize bytes.
  37026. **
  37027. ** i.e for a sector size of 512:
  37028. **
  37029. ** Pager.journalOff Return value
  37030. ** ---------------------------------------
  37031. ** 0 0
  37032. ** 512 512
  37033. ** 100 512
  37034. ** 2000 2048
  37035. **
  37036. */
  37037. static i64 journalHdrOffset(Pager *pPager){
  37038. i64 offset = 0;
  37039. i64 c = pPager->journalOff;
  37040. if( c ){
  37041. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  37042. }
  37043. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  37044. assert( offset>=c );
  37045. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  37046. return offset;
  37047. }
  37048. /*
  37049. ** The journal file must be open when this function is called.
  37050. **
  37051. ** This function is a no-op if the journal file has not been written to
  37052. ** within the current transaction (i.e. if Pager.journalOff==0).
  37053. **
  37054. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  37055. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  37056. ** zero the 28-byte header at the start of the journal file. In either case,
  37057. ** if the pager is not in no-sync mode, sync the journal file immediately
  37058. ** after writing or truncating it.
  37059. **
  37060. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  37061. ** following the truncation or zeroing described above the size of the
  37062. ** journal file in bytes is larger than this value, then truncate the
  37063. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  37064. ** not need to be synced following this operation.
  37065. **
  37066. ** If an IO error occurs, abandon processing and return the IO error code.
  37067. ** Otherwise, return SQLITE_OK.
  37068. */
  37069. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  37070. int rc = SQLITE_OK; /* Return code */
  37071. assert( isOpen(pPager->jfd) );
  37072. if( pPager->journalOff ){
  37073. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  37074. IOTRACE(("JZEROHDR %p\n", pPager))
  37075. if( doTruncate || iLimit==0 ){
  37076. rc = sqlite3OsTruncate(pPager->jfd, 0);
  37077. }else{
  37078. static const char zeroHdr[28] = {0};
  37079. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  37080. }
  37081. if( rc==SQLITE_OK && !pPager->noSync ){
  37082. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  37083. }
  37084. /* At this point the transaction is committed but the write lock
  37085. ** is still held on the file. If there is a size limit configured for
  37086. ** the persistent journal and the journal file currently consumes more
  37087. ** space than that limit allows for, truncate it now. There is no need
  37088. ** to sync the file following this operation.
  37089. */
  37090. if( rc==SQLITE_OK && iLimit>0 ){
  37091. i64 sz;
  37092. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  37093. if( rc==SQLITE_OK && sz>iLimit ){
  37094. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  37095. }
  37096. }
  37097. }
  37098. return rc;
  37099. }
  37100. /*
  37101. ** The journal file must be open when this routine is called. A journal
  37102. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  37103. ** current location.
  37104. **
  37105. ** The format for the journal header is as follows:
  37106. ** - 8 bytes: Magic identifying journal format.
  37107. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  37108. ** - 4 bytes: Random number used for page hash.
  37109. ** - 4 bytes: Initial database page count.
  37110. ** - 4 bytes: Sector size used by the process that wrote this journal.
  37111. ** - 4 bytes: Database page size.
  37112. **
  37113. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  37114. */
  37115. static int writeJournalHdr(Pager *pPager){
  37116. int rc = SQLITE_OK; /* Return code */
  37117. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  37118. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  37119. u32 nWrite; /* Bytes of header sector written */
  37120. int ii; /* Loop counter */
  37121. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  37122. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  37123. nHeader = JOURNAL_HDR_SZ(pPager);
  37124. }
  37125. /* If there are active savepoints and any of them were created
  37126. ** since the most recent journal header was written, update the
  37127. ** PagerSavepoint.iHdrOffset fields now.
  37128. */
  37129. for(ii=0; ii<pPager->nSavepoint; ii++){
  37130. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  37131. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  37132. }
  37133. }
  37134. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  37135. /*
  37136. ** Write the nRec Field - the number of page records that follow this
  37137. ** journal header. Normally, zero is written to this value at this time.
  37138. ** After the records are added to the journal (and the journal synced,
  37139. ** if in full-sync mode), the zero is overwritten with the true number
  37140. ** of records (see syncJournal()).
  37141. **
  37142. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  37143. ** reading the journal this value tells SQLite to assume that the
  37144. ** rest of the journal file contains valid page records. This assumption
  37145. ** is dangerous, as if a failure occurred whilst writing to the journal
  37146. ** file it may contain some garbage data. There are two scenarios
  37147. ** where this risk can be ignored:
  37148. **
  37149. ** * When the pager is in no-sync mode. Corruption can follow a
  37150. ** power failure in this case anyway.
  37151. **
  37152. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  37153. ** that garbage data is never appended to the journal file.
  37154. */
  37155. assert( isOpen(pPager->fd) || pPager->noSync );
  37156. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  37157. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  37158. ){
  37159. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  37160. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  37161. }else{
  37162. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  37163. }
  37164. /* The random check-hash initializer */
  37165. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  37166. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  37167. /* The initial database size */
  37168. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  37169. /* The assumed sector size for this process */
  37170. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  37171. /* The page size */
  37172. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  37173. /* Initializing the tail of the buffer is not necessary. Everything
  37174. ** works find if the following memset() is omitted. But initializing
  37175. ** the memory prevents valgrind from complaining, so we are willing to
  37176. ** take the performance hit.
  37177. */
  37178. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  37179. nHeader-(sizeof(aJournalMagic)+20));
  37180. /* In theory, it is only necessary to write the 28 bytes that the
  37181. ** journal header consumes to the journal file here. Then increment the
  37182. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  37183. ** record is written to the following sector (leaving a gap in the file
  37184. ** that will be implicitly filled in by the OS).
  37185. **
  37186. ** However it has been discovered that on some systems this pattern can
  37187. ** be significantly slower than contiguously writing data to the file,
  37188. ** even if that means explicitly writing data to the block of
  37189. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  37190. ** is done.
  37191. **
  37192. ** The loop is required here in case the sector-size is larger than the
  37193. ** database page size. Since the zHeader buffer is only Pager.pageSize
  37194. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  37195. ** to populate the entire journal header sector.
  37196. */
  37197. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  37198. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  37199. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  37200. assert( pPager->journalHdr <= pPager->journalOff );
  37201. pPager->journalOff += nHeader;
  37202. }
  37203. return rc;
  37204. }
  37205. /*
  37206. ** The journal file must be open when this is called. A journal header file
  37207. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  37208. ** file. The current location in the journal file is given by
  37209. ** pPager->journalOff. See comments above function writeJournalHdr() for
  37210. ** a description of the journal header format.
  37211. **
  37212. ** If the header is read successfully, *pNRec is set to the number of
  37213. ** page records following this header and *pDbSize is set to the size of the
  37214. ** database before the transaction began, in pages. Also, pPager->cksumInit
  37215. ** is set to the value read from the journal header. SQLITE_OK is returned
  37216. ** in this case.
  37217. **
  37218. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  37219. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  37220. ** cannot be read from the journal file an error code is returned.
  37221. */
  37222. static int readJournalHdr(
  37223. Pager *pPager, /* Pager object */
  37224. int isHot,
  37225. i64 journalSize, /* Size of the open journal file in bytes */
  37226. u32 *pNRec, /* OUT: Value read from the nRec field */
  37227. u32 *pDbSize /* OUT: Value of original database size field */
  37228. ){
  37229. int rc; /* Return code */
  37230. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  37231. i64 iHdrOff; /* Offset of journal header being read */
  37232. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  37233. /* Advance Pager.journalOff to the start of the next sector. If the
  37234. ** journal file is too small for there to be a header stored at this
  37235. ** point, return SQLITE_DONE.
  37236. */
  37237. pPager->journalOff = journalHdrOffset(pPager);
  37238. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  37239. return SQLITE_DONE;
  37240. }
  37241. iHdrOff = pPager->journalOff;
  37242. /* Read in the first 8 bytes of the journal header. If they do not match
  37243. ** the magic string found at the start of each journal header, return
  37244. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  37245. ** proceed.
  37246. */
  37247. if( isHot || iHdrOff!=pPager->journalHdr ){
  37248. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  37249. if( rc ){
  37250. return rc;
  37251. }
  37252. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  37253. return SQLITE_DONE;
  37254. }
  37255. }
  37256. /* Read the first three 32-bit fields of the journal header: The nRec
  37257. ** field, the checksum-initializer and the database size at the start
  37258. ** of the transaction. Return an error code if anything goes wrong.
  37259. */
  37260. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  37261. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  37262. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  37263. ){
  37264. return rc;
  37265. }
  37266. if( pPager->journalOff==0 ){
  37267. u32 iPageSize; /* Page-size field of journal header */
  37268. u32 iSectorSize; /* Sector-size field of journal header */
  37269. /* Read the page-size and sector-size journal header fields. */
  37270. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  37271. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  37272. ){
  37273. return rc;
  37274. }
  37275. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  37276. ** journal header to zero. In this case, assume that the Pager.pageSize
  37277. ** variable is already set to the correct page size.
  37278. */
  37279. if( iPageSize==0 ){
  37280. iPageSize = pPager->pageSize;
  37281. }
  37282. /* Check that the values read from the page-size and sector-size fields
  37283. ** are within range. To be 'in range', both values need to be a power
  37284. ** of two greater than or equal to 512 or 32, and not greater than their
  37285. ** respective compile time maximum limits.
  37286. */
  37287. if( iPageSize<512 || iSectorSize<32
  37288. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  37289. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  37290. ){
  37291. /* If the either the page-size or sector-size in the journal-header is
  37292. ** invalid, then the process that wrote the journal-header must have
  37293. ** crashed before the header was synced. In this case stop reading
  37294. ** the journal file here.
  37295. */
  37296. return SQLITE_DONE;
  37297. }
  37298. /* Update the page-size to match the value read from the journal.
  37299. ** Use a testcase() macro to make sure that malloc failure within
  37300. ** PagerSetPagesize() is tested.
  37301. */
  37302. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  37303. testcase( rc!=SQLITE_OK );
  37304. /* Update the assumed sector-size to match the value used by
  37305. ** the process that created this journal. If this journal was
  37306. ** created by a process other than this one, then this routine
  37307. ** is being called from within pager_playback(). The local value
  37308. ** of Pager.sectorSize is restored at the end of that routine.
  37309. */
  37310. pPager->sectorSize = iSectorSize;
  37311. }
  37312. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  37313. return rc;
  37314. }
  37315. /*
  37316. ** Write the supplied master journal name into the journal file for pager
  37317. ** pPager at the current location. The master journal name must be the last
  37318. ** thing written to a journal file. If the pager is in full-sync mode, the
  37319. ** journal file descriptor is advanced to the next sector boundary before
  37320. ** anything is written. The format is:
  37321. **
  37322. ** + 4 bytes: PAGER_MJ_PGNO.
  37323. ** + N bytes: Master journal filename in utf-8.
  37324. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  37325. ** + 4 bytes: Master journal name checksum.
  37326. ** + 8 bytes: aJournalMagic[].
  37327. **
  37328. ** The master journal page checksum is the sum of the bytes in the master
  37329. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  37330. **
  37331. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  37332. ** this call is a no-op.
  37333. */
  37334. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  37335. int rc; /* Return code */
  37336. int nMaster; /* Length of string zMaster */
  37337. i64 iHdrOff; /* Offset of header in journal file */
  37338. i64 jrnlSize; /* Size of journal file on disk */
  37339. u32 cksum = 0; /* Checksum of string zMaster */
  37340. assert( pPager->setMaster==0 );
  37341. assert( !pagerUseWal(pPager) );
  37342. if( !zMaster
  37343. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  37344. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  37345. ){
  37346. return SQLITE_OK;
  37347. }
  37348. pPager->setMaster = 1;
  37349. assert( isOpen(pPager->jfd) );
  37350. assert( pPager->journalHdr <= pPager->journalOff );
  37351. /* Calculate the length in bytes and the checksum of zMaster */
  37352. for(nMaster=0; zMaster[nMaster]; nMaster++){
  37353. cksum += zMaster[nMaster];
  37354. }
  37355. /* If in full-sync mode, advance to the next disk sector before writing
  37356. ** the master journal name. This is in case the previous page written to
  37357. ** the journal has already been synced.
  37358. */
  37359. if( pPager->fullSync ){
  37360. pPager->journalOff = journalHdrOffset(pPager);
  37361. }
  37362. iHdrOff = pPager->journalOff;
  37363. /* Write the master journal data to the end of the journal file. If
  37364. ** an error occurs, return the error code to the caller.
  37365. */
  37366. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  37367. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  37368. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  37369. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  37370. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  37371. ){
  37372. return rc;
  37373. }
  37374. pPager->journalOff += (nMaster+20);
  37375. /* If the pager is in peristent-journal mode, then the physical
  37376. ** journal-file may extend past the end of the master-journal name
  37377. ** and 8 bytes of magic data just written to the file. This is
  37378. ** dangerous because the code to rollback a hot-journal file
  37379. ** will not be able to find the master-journal name to determine
  37380. ** whether or not the journal is hot.
  37381. **
  37382. ** Easiest thing to do in this scenario is to truncate the journal
  37383. ** file to the required size.
  37384. */
  37385. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  37386. && jrnlSize>pPager->journalOff
  37387. ){
  37388. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  37389. }
  37390. return rc;
  37391. }
  37392. /*
  37393. ** Find a page in the hash table given its page number. Return
  37394. ** a pointer to the page or NULL if the requested page is not
  37395. ** already in memory.
  37396. */
  37397. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  37398. PgHdr *p; /* Return value */
  37399. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  37400. ** fail, since no attempt to allocate dynamic memory will be made.
  37401. */
  37402. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  37403. return p;
  37404. }
  37405. /*
  37406. ** Discard the entire contents of the in-memory page-cache.
  37407. */
  37408. static void pager_reset(Pager *pPager){
  37409. sqlite3BackupRestart(pPager->pBackup);
  37410. sqlite3PcacheClear(pPager->pPCache);
  37411. }
  37412. /*
  37413. ** Free all structures in the Pager.aSavepoint[] array and set both
  37414. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  37415. ** if it is open and the pager is not in exclusive mode.
  37416. */
  37417. static void releaseAllSavepoints(Pager *pPager){
  37418. int ii; /* Iterator for looping through Pager.aSavepoint */
  37419. for(ii=0; ii<pPager->nSavepoint; ii++){
  37420. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  37421. }
  37422. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  37423. sqlite3OsClose(pPager->sjfd);
  37424. }
  37425. sqlite3_free(pPager->aSavepoint);
  37426. pPager->aSavepoint = 0;
  37427. pPager->nSavepoint = 0;
  37428. pPager->nSubRec = 0;
  37429. }
  37430. /*
  37431. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  37432. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  37433. ** or SQLITE_NOMEM if a malloc failure occurs.
  37434. */
  37435. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  37436. int ii; /* Loop counter */
  37437. int rc = SQLITE_OK; /* Result code */
  37438. for(ii=0; ii<pPager->nSavepoint; ii++){
  37439. PagerSavepoint *p = &pPager->aSavepoint[ii];
  37440. if( pgno<=p->nOrig ){
  37441. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  37442. testcase( rc==SQLITE_NOMEM );
  37443. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  37444. }
  37445. }
  37446. return rc;
  37447. }
  37448. /*
  37449. ** This function is a no-op if the pager is in exclusive mode and not
  37450. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  37451. ** state.
  37452. **
  37453. ** If the pager is not in exclusive-access mode, the database file is
  37454. ** completely unlocked. If the file is unlocked and the file-system does
  37455. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  37456. ** closed (if it is open).
  37457. **
  37458. ** If the pager is in ERROR state when this function is called, the
  37459. ** contents of the pager cache are discarded before switching back to
  37460. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  37461. ** or not, any journal file left in the file-system will be treated
  37462. ** as a hot-journal and rolled back the next time a read-transaction
  37463. ** is opened (by this or by any other connection).
  37464. */
  37465. static void pager_unlock(Pager *pPager){
  37466. assert( pPager->eState==PAGER_READER
  37467. || pPager->eState==PAGER_OPEN
  37468. || pPager->eState==PAGER_ERROR
  37469. );
  37470. sqlite3BitvecDestroy(pPager->pInJournal);
  37471. pPager->pInJournal = 0;
  37472. releaseAllSavepoints(pPager);
  37473. if( pagerUseWal(pPager) ){
  37474. assert( !isOpen(pPager->jfd) );
  37475. sqlite3WalEndReadTransaction(pPager->pWal);
  37476. pPager->eState = PAGER_OPEN;
  37477. }else if( !pPager->exclusiveMode ){
  37478. int rc; /* Error code returned by pagerUnlockDb() */
  37479. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  37480. /* If the operating system support deletion of open files, then
  37481. ** close the journal file when dropping the database lock. Otherwise
  37482. ** another connection with journal_mode=delete might delete the file
  37483. ** out from under us.
  37484. */
  37485. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  37486. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  37487. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  37488. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  37489. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  37490. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  37491. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  37492. || 1!=(pPager->journalMode & 5)
  37493. ){
  37494. sqlite3OsClose(pPager->jfd);
  37495. }
  37496. /* If the pager is in the ERROR state and the call to unlock the database
  37497. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  37498. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  37499. ** is necessary.
  37500. */
  37501. rc = pagerUnlockDb(pPager, NO_LOCK);
  37502. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  37503. pPager->eLock = UNKNOWN_LOCK;
  37504. }
  37505. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  37506. ** without clearing the error code. This is intentional - the error
  37507. ** code is cleared and the cache reset in the block below.
  37508. */
  37509. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  37510. pPager->changeCountDone = 0;
  37511. pPager->eState = PAGER_OPEN;
  37512. }
  37513. /* If Pager.errCode is set, the contents of the pager cache cannot be
  37514. ** trusted. Now that there are no outstanding references to the pager,
  37515. ** it can safely move back to PAGER_OPEN state. This happens in both
  37516. ** normal and exclusive-locking mode.
  37517. */
  37518. if( pPager->errCode ){
  37519. assert( !MEMDB );
  37520. pager_reset(pPager);
  37521. pPager->changeCountDone = pPager->tempFile;
  37522. pPager->eState = PAGER_OPEN;
  37523. pPager->errCode = SQLITE_OK;
  37524. }
  37525. pPager->journalOff = 0;
  37526. pPager->journalHdr = 0;
  37527. pPager->setMaster = 0;
  37528. }
  37529. /*
  37530. ** This function is called whenever an IOERR or FULL error that requires
  37531. ** the pager to transition into the ERROR state may ahve occurred.
  37532. ** The first argument is a pointer to the pager structure, the second
  37533. ** the error-code about to be returned by a pager API function. The
  37534. ** value returned is a copy of the second argument to this function.
  37535. **
  37536. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  37537. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  37538. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  37539. ** all major API calls on the Pager will immediately return Pager.errCode.
  37540. **
  37541. ** The ERROR state indicates that the contents of the pager-cache
  37542. ** cannot be trusted. This state can be cleared by completely discarding
  37543. ** the contents of the pager-cache. If a transaction was active when
  37544. ** the persistent error occurred, then the rollback journal may need
  37545. ** to be replayed to restore the contents of the database file (as if
  37546. ** it were a hot-journal).
  37547. */
  37548. static int pager_error(Pager *pPager, int rc){
  37549. int rc2 = rc & 0xff;
  37550. assert( rc==SQLITE_OK || !MEMDB );
  37551. assert(
  37552. pPager->errCode==SQLITE_FULL ||
  37553. pPager->errCode==SQLITE_OK ||
  37554. (pPager->errCode & 0xff)==SQLITE_IOERR
  37555. );
  37556. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  37557. pPager->errCode = rc;
  37558. pPager->eState = PAGER_ERROR;
  37559. }
  37560. return rc;
  37561. }
  37562. static int pager_truncate(Pager *pPager, Pgno nPage);
  37563. /*
  37564. ** This routine ends a transaction. A transaction is usually ended by
  37565. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  37566. ** after rollback of a hot-journal, or if an error occurs while opening
  37567. ** the journal file or writing the very first journal-header of a
  37568. ** database transaction.
  37569. **
  37570. ** This routine is never called in PAGER_ERROR state. If it is called
  37571. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  37572. ** exclusive than a RESERVED lock, it is a no-op.
  37573. **
  37574. ** Otherwise, any active savepoints are released.
  37575. **
  37576. ** If the journal file is open, then it is "finalized". Once a journal
  37577. ** file has been finalized it is not possible to use it to roll back a
  37578. ** transaction. Nor will it be considered to be a hot-journal by this
  37579. ** or any other database connection. Exactly how a journal is finalized
  37580. ** depends on whether or not the pager is running in exclusive mode and
  37581. ** the current journal-mode (Pager.journalMode value), as follows:
  37582. **
  37583. ** journalMode==MEMORY
  37584. ** Journal file descriptor is simply closed. This destroys an
  37585. ** in-memory journal.
  37586. **
  37587. ** journalMode==TRUNCATE
  37588. ** Journal file is truncated to zero bytes in size.
  37589. **
  37590. ** journalMode==PERSIST
  37591. ** The first 28 bytes of the journal file are zeroed. This invalidates
  37592. ** the first journal header in the file, and hence the entire journal
  37593. ** file. An invalid journal file cannot be rolled back.
  37594. **
  37595. ** journalMode==DELETE
  37596. ** The journal file is closed and deleted using sqlite3OsDelete().
  37597. **
  37598. ** If the pager is running in exclusive mode, this method of finalizing
  37599. ** the journal file is never used. Instead, if the journalMode is
  37600. ** DELETE and the pager is in exclusive mode, the method described under
  37601. ** journalMode==PERSIST is used instead.
  37602. **
  37603. ** After the journal is finalized, the pager moves to PAGER_READER state.
  37604. ** If running in non-exclusive rollback mode, the lock on the file is
  37605. ** downgraded to a SHARED_LOCK.
  37606. **
  37607. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  37608. ** any of the IO operations to finalize the journal file or unlock the
  37609. ** database then the IO error code is returned to the user. If the
  37610. ** operation to finalize the journal file fails, then the code still
  37611. ** tries to unlock the database file if not in exclusive mode. If the
  37612. ** unlock operation fails as well, then the first error code related
  37613. ** to the first error encountered (the journal finalization one) is
  37614. ** returned.
  37615. */
  37616. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  37617. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  37618. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  37619. /* Do nothing if the pager does not have an open write transaction
  37620. ** or at least a RESERVED lock. This function may be called when there
  37621. ** is no write-transaction active but a RESERVED or greater lock is
  37622. ** held under two circumstances:
  37623. **
  37624. ** 1. After a successful hot-journal rollback, it is called with
  37625. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  37626. **
  37627. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  37628. ** lock switches back to locking_mode=normal and then executes a
  37629. ** read-transaction, this function is called with eState==PAGER_READER
  37630. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  37631. */
  37632. assert( assert_pager_state(pPager) );
  37633. assert( pPager->eState!=PAGER_ERROR );
  37634. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  37635. return SQLITE_OK;
  37636. }
  37637. releaseAllSavepoints(pPager);
  37638. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  37639. if( isOpen(pPager->jfd) ){
  37640. assert( !pagerUseWal(pPager) );
  37641. /* Finalize the journal file. */
  37642. if( sqlite3IsMemJournal(pPager->jfd) ){
  37643. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  37644. sqlite3OsClose(pPager->jfd);
  37645. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  37646. if( pPager->journalOff==0 ){
  37647. rc = SQLITE_OK;
  37648. }else{
  37649. rc = sqlite3OsTruncate(pPager->jfd, 0);
  37650. }
  37651. pPager->journalOff = 0;
  37652. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  37653. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  37654. ){
  37655. rc = zeroJournalHdr(pPager, hasMaster);
  37656. pPager->journalOff = 0;
  37657. }else{
  37658. /* This branch may be executed with Pager.journalMode==MEMORY if
  37659. ** a hot-journal was just rolled back. In this case the journal
  37660. ** file should be closed and deleted. If this connection writes to
  37661. ** the database file, it will do so using an in-memory journal.
  37662. */
  37663. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  37664. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  37665. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  37666. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  37667. );
  37668. sqlite3OsClose(pPager->jfd);
  37669. if( bDelete ){
  37670. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  37671. }
  37672. }
  37673. }
  37674. #ifdef SQLITE_CHECK_PAGES
  37675. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  37676. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  37677. PgHdr *p = pager_lookup(pPager, 1);
  37678. if( p ){
  37679. p->pageHash = 0;
  37680. sqlite3PagerUnref(p);
  37681. }
  37682. }
  37683. #endif
  37684. sqlite3BitvecDestroy(pPager->pInJournal);
  37685. pPager->pInJournal = 0;
  37686. pPager->nRec = 0;
  37687. sqlite3PcacheCleanAll(pPager->pPCache);
  37688. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  37689. if( pagerUseWal(pPager) ){
  37690. /* Drop the WAL write-lock, if any. Also, if the connection was in
  37691. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  37692. ** lock held on the database file.
  37693. */
  37694. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  37695. assert( rc2==SQLITE_OK );
  37696. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  37697. /* This branch is taken when committing a transaction in rollback-journal
  37698. ** mode if the database file on disk is larger than the database image.
  37699. ** At this point the journal has been finalized and the transaction
  37700. ** successfully committed, but the EXCLUSIVE lock is still held on the
  37701. ** file. So it is safe to truncate the database file to its minimum
  37702. ** required size. */
  37703. assert( pPager->eLock==EXCLUSIVE_LOCK );
  37704. rc = pager_truncate(pPager, pPager->dbSize);
  37705. }
  37706. if( !pPager->exclusiveMode
  37707. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  37708. ){
  37709. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  37710. pPager->changeCountDone = 0;
  37711. }
  37712. pPager->eState = PAGER_READER;
  37713. pPager->setMaster = 0;
  37714. return (rc==SQLITE_OK?rc2:rc);
  37715. }
  37716. /*
  37717. ** Execute a rollback if a transaction is active and unlock the
  37718. ** database file.
  37719. **
  37720. ** If the pager has already entered the ERROR state, do not attempt
  37721. ** the rollback at this time. Instead, pager_unlock() is called. The
  37722. ** call to pager_unlock() will discard all in-memory pages, unlock
  37723. ** the database file and move the pager back to OPEN state. If this
  37724. ** means that there is a hot-journal left in the file-system, the next
  37725. ** connection to obtain a shared lock on the pager (which may be this one)
  37726. ** will roll it back.
  37727. **
  37728. ** If the pager has not already entered the ERROR state, but an IO or
  37729. ** malloc error occurs during a rollback, then this will itself cause
  37730. ** the pager to enter the ERROR state. Which will be cleared by the
  37731. ** call to pager_unlock(), as described above.
  37732. */
  37733. static void pagerUnlockAndRollback(Pager *pPager){
  37734. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  37735. assert( assert_pager_state(pPager) );
  37736. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  37737. sqlite3BeginBenignMalloc();
  37738. sqlite3PagerRollback(pPager);
  37739. sqlite3EndBenignMalloc();
  37740. }else if( !pPager->exclusiveMode ){
  37741. assert( pPager->eState==PAGER_READER );
  37742. pager_end_transaction(pPager, 0, 0);
  37743. }
  37744. }
  37745. pager_unlock(pPager);
  37746. }
  37747. /*
  37748. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  37749. ** of data. Compute and return a checksum based ont the contents of the
  37750. ** page of data and the current value of pPager->cksumInit.
  37751. **
  37752. ** This is not a real checksum. It is really just the sum of the
  37753. ** random initial value (pPager->cksumInit) and every 200th byte
  37754. ** of the page data, starting with byte offset (pPager->pageSize%200).
  37755. ** Each byte is interpreted as an 8-bit unsigned integer.
  37756. **
  37757. ** Changing the formula used to compute this checksum results in an
  37758. ** incompatible journal file format.
  37759. **
  37760. ** If journal corruption occurs due to a power failure, the most likely
  37761. ** scenario is that one end or the other of the record will be changed.
  37762. ** It is much less likely that the two ends of the journal record will be
  37763. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  37764. ** though fast and simple, catches the mostly likely kind of corruption.
  37765. */
  37766. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  37767. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  37768. int i = pPager->pageSize-200; /* Loop counter */
  37769. while( i>0 ){
  37770. cksum += aData[i];
  37771. i -= 200;
  37772. }
  37773. return cksum;
  37774. }
  37775. /*
  37776. ** Report the current page size and number of reserved bytes back
  37777. ** to the codec.
  37778. */
  37779. #ifdef SQLITE_HAS_CODEC
  37780. static void pagerReportSize(Pager *pPager){
  37781. if( pPager->xCodecSizeChng ){
  37782. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  37783. (int)pPager->nReserve);
  37784. }
  37785. }
  37786. #else
  37787. # define pagerReportSize(X) /* No-op if we do not support a codec */
  37788. #endif
  37789. /*
  37790. ** Read a single page from either the journal file (if isMainJrnl==1) or
  37791. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  37792. ** The page begins at offset *pOffset into the file. The *pOffset
  37793. ** value is increased to the start of the next page in the journal.
  37794. **
  37795. ** The main rollback journal uses checksums - the statement journal does
  37796. ** not.
  37797. **
  37798. ** If the page number of the page record read from the (sub-)journal file
  37799. ** is greater than the current value of Pager.dbSize, then playback is
  37800. ** skipped and SQLITE_OK is returned.
  37801. **
  37802. ** If pDone is not NULL, then it is a record of pages that have already
  37803. ** been played back. If the page at *pOffset has already been played back
  37804. ** (if the corresponding pDone bit is set) then skip the playback.
  37805. ** Make sure the pDone bit corresponding to the *pOffset page is set
  37806. ** prior to returning.
  37807. **
  37808. ** If the page record is successfully read from the (sub-)journal file
  37809. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  37810. ** while reading the record from the (sub-)journal file or while writing
  37811. ** to the database file, then the IO error code is returned. If data
  37812. ** is successfully read from the (sub-)journal file but appears to be
  37813. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  37814. ** two circumstances:
  37815. **
  37816. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  37817. ** * If the record is being rolled back from the main journal file
  37818. ** and the checksum field does not match the record content.
  37819. **
  37820. ** Neither of these two scenarios are possible during a savepoint rollback.
  37821. **
  37822. ** If this is a savepoint rollback, then memory may have to be dynamically
  37823. ** allocated by this function. If this is the case and an allocation fails,
  37824. ** SQLITE_NOMEM is returned.
  37825. */
  37826. static int pager_playback_one_page(
  37827. Pager *pPager, /* The pager being played back */
  37828. i64 *pOffset, /* Offset of record to playback */
  37829. Bitvec *pDone, /* Bitvec of pages already played back */
  37830. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  37831. int isSavepnt /* True for a savepoint rollback */
  37832. ){
  37833. int rc;
  37834. PgHdr *pPg; /* An existing page in the cache */
  37835. Pgno pgno; /* The page number of a page in journal */
  37836. u32 cksum; /* Checksum used for sanity checking */
  37837. char *aData; /* Temporary storage for the page */
  37838. sqlite3_file *jfd; /* The file descriptor for the journal file */
  37839. int isSynced; /* True if journal page is synced */
  37840. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  37841. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  37842. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  37843. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  37844. aData = pPager->pTmpSpace;
  37845. assert( aData ); /* Temp storage must have already been allocated */
  37846. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  37847. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  37848. ** or savepoint rollback done at the request of the caller) or this is
  37849. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  37850. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  37851. ** only reads from the main journal, not the sub-journal.
  37852. */
  37853. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  37854. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  37855. );
  37856. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  37857. /* Read the page number and page data from the journal or sub-journal
  37858. ** file. Return an error code to the caller if an IO error occurs.
  37859. */
  37860. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  37861. rc = read32bits(jfd, *pOffset, &pgno);
  37862. if( rc!=SQLITE_OK ) return rc;
  37863. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  37864. if( rc!=SQLITE_OK ) return rc;
  37865. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  37866. /* Sanity checking on the page. This is more important that I originally
  37867. ** thought. If a power failure occurs while the journal is being written,
  37868. ** it could cause invalid data to be written into the journal. We need to
  37869. ** detect this invalid data (with high probability) and ignore it.
  37870. */
  37871. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  37872. assert( !isSavepnt );
  37873. return SQLITE_DONE;
  37874. }
  37875. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  37876. return SQLITE_OK;
  37877. }
  37878. if( isMainJrnl ){
  37879. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  37880. if( rc ) return rc;
  37881. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  37882. return SQLITE_DONE;
  37883. }
  37884. }
  37885. /* If this page has already been played by before during the current
  37886. ** rollback, then don't bother to play it back again.
  37887. */
  37888. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  37889. return rc;
  37890. }
  37891. /* When playing back page 1, restore the nReserve setting
  37892. */
  37893. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  37894. pPager->nReserve = ((u8*)aData)[20];
  37895. pagerReportSize(pPager);
  37896. }
  37897. /* If the pager is in CACHEMOD state, then there must be a copy of this
  37898. ** page in the pager cache. In this case just update the pager cache,
  37899. ** not the database file. The page is left marked dirty in this case.
  37900. **
  37901. ** An exception to the above rule: If the database is in no-sync mode
  37902. ** and a page is moved during an incremental vacuum then the page may
  37903. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  37904. ** during a Movepage() call, then the page may not be in the cache
  37905. ** either. So the condition described in the above paragraph is not
  37906. ** assert()able.
  37907. **
  37908. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  37909. ** pager cache if it exists and the main file. The page is then marked
  37910. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  37911. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  37912. ** if the pager is in OPEN state.
  37913. **
  37914. ** Ticket #1171: The statement journal might contain page content that is
  37915. ** different from the page content at the start of the transaction.
  37916. ** This occurs when a page is changed prior to the start of a statement
  37917. ** then changed again within the statement. When rolling back such a
  37918. ** statement we must not write to the original database unless we know
  37919. ** for certain that original page contents are synced into the main rollback
  37920. ** journal. Otherwise, a power loss might leave modified data in the
  37921. ** database file without an entry in the rollback journal that can
  37922. ** restore the database to its original form. Two conditions must be
  37923. ** met before writing to the database files. (1) the database must be
  37924. ** locked. (2) we know that the original page content is fully synced
  37925. ** in the main journal either because the page is not in cache or else
  37926. ** the page is marked as needSync==0.
  37927. **
  37928. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  37929. ** is possible to fail a statement on a database that does not yet exist.
  37930. ** Do not attempt to write if database file has never been opened.
  37931. */
  37932. if( pagerUseWal(pPager) ){
  37933. pPg = 0;
  37934. }else{
  37935. pPg = pager_lookup(pPager, pgno);
  37936. }
  37937. assert( pPg || !MEMDB );
  37938. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  37939. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  37940. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  37941. (isMainJrnl?"main-journal":"sub-journal")
  37942. ));
  37943. if( isMainJrnl ){
  37944. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  37945. }else{
  37946. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  37947. }
  37948. if( isOpen(pPager->fd)
  37949. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  37950. && isSynced
  37951. ){
  37952. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  37953. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  37954. assert( !pagerUseWal(pPager) );
  37955. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  37956. if( pgno>pPager->dbFileSize ){
  37957. pPager->dbFileSize = pgno;
  37958. }
  37959. if( pPager->pBackup ){
  37960. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  37961. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  37962. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  37963. }
  37964. }else if( !isMainJrnl && pPg==0 ){
  37965. /* If this is a rollback of a savepoint and data was not written to
  37966. ** the database and the page is not in-memory, there is a potential
  37967. ** problem. When the page is next fetched by the b-tree layer, it
  37968. ** will be read from the database file, which may or may not be
  37969. ** current.
  37970. **
  37971. ** There are a couple of different ways this can happen. All are quite
  37972. ** obscure. When running in synchronous mode, this can only happen
  37973. ** if the page is on the free-list at the start of the transaction, then
  37974. ** populated, then moved using sqlite3PagerMovepage().
  37975. **
  37976. ** The solution is to add an in-memory page to the cache containing
  37977. ** the data just read from the sub-journal. Mark the page as dirty
  37978. ** and if the pager requires a journal-sync, then mark the page as
  37979. ** requiring a journal-sync before it is written.
  37980. */
  37981. assert( isSavepnt );
  37982. assert( pPager->doNotSpill==0 );
  37983. pPager->doNotSpill++;
  37984. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  37985. assert( pPager->doNotSpill==1 );
  37986. pPager->doNotSpill--;
  37987. if( rc!=SQLITE_OK ) return rc;
  37988. pPg->flags &= ~PGHDR_NEED_READ;
  37989. sqlite3PcacheMakeDirty(pPg);
  37990. }
  37991. if( pPg ){
  37992. /* No page should ever be explicitly rolled back that is in use, except
  37993. ** for page 1 which is held in use in order to keep the lock on the
  37994. ** database active. However such a page may be rolled back as a result
  37995. ** of an internal error resulting in an automatic call to
  37996. ** sqlite3PagerRollback().
  37997. */
  37998. void *pData;
  37999. pData = pPg->pData;
  38000. memcpy(pData, (u8*)aData, pPager->pageSize);
  38001. pPager->xReiniter(pPg);
  38002. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  38003. /* If the contents of this page were just restored from the main
  38004. ** journal file, then its content must be as they were when the
  38005. ** transaction was first opened. In this case we can mark the page
  38006. ** as clean, since there will be no need to write it out to the
  38007. ** database.
  38008. **
  38009. ** There is one exception to this rule. If the page is being rolled
  38010. ** back as part of a savepoint (or statement) rollback from an
  38011. ** unsynced portion of the main journal file, then it is not safe
  38012. ** to mark the page as clean. This is because marking the page as
  38013. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  38014. ** already in the journal file (recorded in Pager.pInJournal) and
  38015. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  38016. ** again within this transaction, it will be marked as dirty but
  38017. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  38018. ** be written out into the database file before its journal file
  38019. ** segment is synced. If a crash occurs during or following this,
  38020. ** database corruption may ensue.
  38021. */
  38022. assert( !pagerUseWal(pPager) );
  38023. sqlite3PcacheMakeClean(pPg);
  38024. }
  38025. pager_set_pagehash(pPg);
  38026. /* If this was page 1, then restore the value of Pager.dbFileVers.
  38027. ** Do this before any decoding. */
  38028. if( pgno==1 ){
  38029. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  38030. }
  38031. /* Decode the page just read from disk */
  38032. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  38033. sqlite3PcacheRelease(pPg);
  38034. }
  38035. return rc;
  38036. }
  38037. /*
  38038. ** Parameter zMaster is the name of a master journal file. A single journal
  38039. ** file that referred to the master journal file has just been rolled back.
  38040. ** This routine checks if it is possible to delete the master journal file,
  38041. ** and does so if it is.
  38042. **
  38043. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  38044. ** available for use within this function.
  38045. **
  38046. ** When a master journal file is created, it is populated with the names
  38047. ** of all of its child journals, one after another, formatted as utf-8
  38048. ** encoded text. The end of each child journal file is marked with a
  38049. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  38050. ** file for a transaction involving two databases might be:
  38051. **
  38052. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  38053. **
  38054. ** A master journal file may only be deleted once all of its child
  38055. ** journals have been rolled back.
  38056. **
  38057. ** This function reads the contents of the master-journal file into
  38058. ** memory and loops through each of the child journal names. For
  38059. ** each child journal, it checks if:
  38060. **
  38061. ** * if the child journal exists, and if so
  38062. ** * if the child journal contains a reference to master journal
  38063. ** file zMaster
  38064. **
  38065. ** If a child journal can be found that matches both of the criteria
  38066. ** above, this function returns without doing anything. Otherwise, if
  38067. ** no such child journal can be found, file zMaster is deleted from
  38068. ** the file-system using sqlite3OsDelete().
  38069. **
  38070. ** If an IO error within this function, an error code is returned. This
  38071. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  38072. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  38073. ** occur, SQLITE_OK is returned.
  38074. **
  38075. ** TODO: This function allocates a single block of memory to load
  38076. ** the entire contents of the master journal file. This could be
  38077. ** a couple of kilobytes or so - potentially larger than the page
  38078. ** size.
  38079. */
  38080. static int pager_delmaster(Pager *pPager, const char *zMaster){
  38081. sqlite3_vfs *pVfs = pPager->pVfs;
  38082. int rc; /* Return code */
  38083. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  38084. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  38085. char *zMasterJournal = 0; /* Contents of master journal file */
  38086. i64 nMasterJournal; /* Size of master journal file */
  38087. char *zJournal; /* Pointer to one journal within MJ file */
  38088. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  38089. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  38090. /* Allocate space for both the pJournal and pMaster file descriptors.
  38091. ** If successful, open the master journal file for reading.
  38092. */
  38093. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  38094. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  38095. if( !pMaster ){
  38096. rc = SQLITE_NOMEM;
  38097. }else{
  38098. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  38099. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  38100. }
  38101. if( rc!=SQLITE_OK ) goto delmaster_out;
  38102. /* Load the entire master journal file into space obtained from
  38103. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  38104. ** sufficient space (in zMasterPtr) to hold the names of master
  38105. ** journal files extracted from regular rollback-journals.
  38106. */
  38107. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  38108. if( rc!=SQLITE_OK ) goto delmaster_out;
  38109. nMasterPtr = pVfs->mxPathname+1;
  38110. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  38111. if( !zMasterJournal ){
  38112. rc = SQLITE_NOMEM;
  38113. goto delmaster_out;
  38114. }
  38115. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  38116. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  38117. if( rc!=SQLITE_OK ) goto delmaster_out;
  38118. zMasterJournal[nMasterJournal] = 0;
  38119. zJournal = zMasterJournal;
  38120. while( (zJournal-zMasterJournal)<nMasterJournal ){
  38121. int exists;
  38122. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  38123. if( rc!=SQLITE_OK ){
  38124. goto delmaster_out;
  38125. }
  38126. if( exists ){
  38127. /* One of the journals pointed to by the master journal exists.
  38128. ** Open it and check if it points at the master journal. If
  38129. ** so, return without deleting the master journal file.
  38130. */
  38131. int c;
  38132. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  38133. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  38134. if( rc!=SQLITE_OK ){
  38135. goto delmaster_out;
  38136. }
  38137. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  38138. sqlite3OsClose(pJournal);
  38139. if( rc!=SQLITE_OK ){
  38140. goto delmaster_out;
  38141. }
  38142. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  38143. if( c ){
  38144. /* We have a match. Do not delete the master journal file. */
  38145. goto delmaster_out;
  38146. }
  38147. }
  38148. zJournal += (sqlite3Strlen30(zJournal)+1);
  38149. }
  38150. sqlite3OsClose(pMaster);
  38151. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  38152. delmaster_out:
  38153. sqlite3_free(zMasterJournal);
  38154. if( pMaster ){
  38155. sqlite3OsClose(pMaster);
  38156. assert( !isOpen(pJournal) );
  38157. sqlite3_free(pMaster);
  38158. }
  38159. return rc;
  38160. }
  38161. /*
  38162. ** This function is used to change the actual size of the database
  38163. ** file in the file-system. This only happens when committing a transaction,
  38164. ** or rolling back a transaction (including rolling back a hot-journal).
  38165. **
  38166. ** If the main database file is not open, or the pager is not in either
  38167. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  38168. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  38169. ** If the file on disk is currently larger than nPage pages, then use the VFS
  38170. ** xTruncate() method to truncate it.
  38171. **
  38172. ** Or, it might might be the case that the file on disk is smaller than
  38173. ** nPage pages. Some operating system implementations can get confused if
  38174. ** you try to truncate a file to some size that is larger than it
  38175. ** currently is, so detect this case and write a single zero byte to
  38176. ** the end of the new file instead.
  38177. **
  38178. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  38179. ** the database file, return the error code to the caller.
  38180. */
  38181. static int pager_truncate(Pager *pPager, Pgno nPage){
  38182. int rc = SQLITE_OK;
  38183. assert( pPager->eState!=PAGER_ERROR );
  38184. assert( pPager->eState!=PAGER_READER );
  38185. if( isOpen(pPager->fd)
  38186. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  38187. ){
  38188. i64 currentSize, newSize;
  38189. int szPage = pPager->pageSize;
  38190. assert( pPager->eLock==EXCLUSIVE_LOCK );
  38191. /* TODO: Is it safe to use Pager.dbFileSize here? */
  38192. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  38193. newSize = szPage*(i64)nPage;
  38194. if( rc==SQLITE_OK && currentSize!=newSize ){
  38195. if( currentSize>newSize ){
  38196. rc = sqlite3OsTruncate(pPager->fd, newSize);
  38197. }else if( (currentSize+szPage)<=newSize ){
  38198. char *pTmp = pPager->pTmpSpace;
  38199. memset(pTmp, 0, szPage);
  38200. testcase( (newSize-szPage) == currentSize );
  38201. testcase( (newSize-szPage) > currentSize );
  38202. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  38203. }
  38204. if( rc==SQLITE_OK ){
  38205. pPager->dbFileSize = nPage;
  38206. }
  38207. }
  38208. }
  38209. return rc;
  38210. }
  38211. /*
  38212. ** Return a sanitized version of the sector-size of OS file pFile. The
  38213. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  38214. */
  38215. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  38216. int iRet = sqlite3OsSectorSize(pFile);
  38217. if( iRet<32 ){
  38218. iRet = 512;
  38219. }else if( iRet>MAX_SECTOR_SIZE ){
  38220. assert( MAX_SECTOR_SIZE>=512 );
  38221. iRet = MAX_SECTOR_SIZE;
  38222. }
  38223. return iRet;
  38224. }
  38225. /*
  38226. ** Set the value of the Pager.sectorSize variable for the given
  38227. ** pager based on the value returned by the xSectorSize method
  38228. ** of the open database file. The sector size will be used used
  38229. ** to determine the size and alignment of journal header and
  38230. ** master journal pointers within created journal files.
  38231. **
  38232. ** For temporary files the effective sector size is always 512 bytes.
  38233. **
  38234. ** Otherwise, for non-temporary files, the effective sector size is
  38235. ** the value returned by the xSectorSize() method rounded up to 32 if
  38236. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  38237. ** is greater than MAX_SECTOR_SIZE.
  38238. **
  38239. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  38240. ** the effective sector size to its minimum value (512). The purpose of
  38241. ** pPager->sectorSize is to define the "blast radius" of bytes that
  38242. ** might change if a crash occurs while writing to a single byte in
  38243. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  38244. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  38245. ** size. For backwards compatibility of the rollback journal file format,
  38246. ** we cannot reduce the effective sector size below 512.
  38247. */
  38248. static void setSectorSize(Pager *pPager){
  38249. assert( isOpen(pPager->fd) || pPager->tempFile );
  38250. if( pPager->tempFile
  38251. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  38252. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  38253. ){
  38254. /* Sector size doesn't matter for temporary files. Also, the file
  38255. ** may not have been opened yet, in which case the OsSectorSize()
  38256. ** call will segfault. */
  38257. pPager->sectorSize = 512;
  38258. }else{
  38259. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  38260. }
  38261. }
  38262. /*
  38263. ** Playback the journal and thus restore the database file to
  38264. ** the state it was in before we started making changes.
  38265. **
  38266. ** The journal file format is as follows:
  38267. **
  38268. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  38269. ** (2) 4 byte big-endian integer which is the number of valid page records
  38270. ** in the journal. If this value is 0xffffffff, then compute the
  38271. ** number of page records from the journal size.
  38272. ** (3) 4 byte big-endian integer which is the initial value for the
  38273. ** sanity checksum.
  38274. ** (4) 4 byte integer which is the number of pages to truncate the
  38275. ** database to during a rollback.
  38276. ** (5) 4 byte big-endian integer which is the sector size. The header
  38277. ** is this many bytes in size.
  38278. ** (6) 4 byte big-endian integer which is the page size.
  38279. ** (7) zero padding out to the next sector size.
  38280. ** (8) Zero or more pages instances, each as follows:
  38281. ** + 4 byte page number.
  38282. ** + pPager->pageSize bytes of data.
  38283. ** + 4 byte checksum
  38284. **
  38285. ** When we speak of the journal header, we mean the first 7 items above.
  38286. ** Each entry in the journal is an instance of the 8th item.
  38287. **
  38288. ** Call the value from the second bullet "nRec". nRec is the number of
  38289. ** valid page entries in the journal. In most cases, you can compute the
  38290. ** value of nRec from the size of the journal file. But if a power
  38291. ** failure occurred while the journal was being written, it could be the
  38292. ** case that the size of the journal file had already been increased but
  38293. ** the extra entries had not yet made it safely to disk. In such a case,
  38294. ** the value of nRec computed from the file size would be too large. For
  38295. ** that reason, we always use the nRec value in the header.
  38296. **
  38297. ** If the nRec value is 0xffffffff it means that nRec should be computed
  38298. ** from the file size. This value is used when the user selects the
  38299. ** no-sync option for the journal. A power failure could lead to corruption
  38300. ** in this case. But for things like temporary table (which will be
  38301. ** deleted when the power is restored) we don't care.
  38302. **
  38303. ** If the file opened as the journal file is not a well-formed
  38304. ** journal file then all pages up to the first corrupted page are rolled
  38305. ** back (or no pages if the journal header is corrupted). The journal file
  38306. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  38307. ** been encountered.
  38308. **
  38309. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  38310. ** and an error code is returned.
  38311. **
  38312. ** The isHot parameter indicates that we are trying to rollback a journal
  38313. ** that might be a hot journal. Or, it could be that the journal is
  38314. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  38315. ** If the journal really is hot, reset the pager cache prior rolling
  38316. ** back any content. If the journal is merely persistent, no reset is
  38317. ** needed.
  38318. */
  38319. static int pager_playback(Pager *pPager, int isHot){
  38320. sqlite3_vfs *pVfs = pPager->pVfs;
  38321. i64 szJ; /* Size of the journal file in bytes */
  38322. u32 nRec; /* Number of Records in the journal */
  38323. u32 u; /* Unsigned loop counter */
  38324. Pgno mxPg = 0; /* Size of the original file in pages */
  38325. int rc; /* Result code of a subroutine */
  38326. int res = 1; /* Value returned by sqlite3OsAccess() */
  38327. char *zMaster = 0; /* Name of master journal file if any */
  38328. int needPagerReset; /* True to reset page prior to first page rollback */
  38329. int nPlayback = 0; /* Total number of pages restored from journal */
  38330. /* Figure out how many records are in the journal. Abort early if
  38331. ** the journal is empty.
  38332. */
  38333. assert( isOpen(pPager->jfd) );
  38334. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  38335. if( rc!=SQLITE_OK ){
  38336. goto end_playback;
  38337. }
  38338. /* Read the master journal name from the journal, if it is present.
  38339. ** If a master journal file name is specified, but the file is not
  38340. ** present on disk, then the journal is not hot and does not need to be
  38341. ** played back.
  38342. **
  38343. ** TODO: Technically the following is an error because it assumes that
  38344. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  38345. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  38346. ** mxPathname is 512, which is the same as the minimum allowable value
  38347. ** for pageSize.
  38348. */
  38349. zMaster = pPager->pTmpSpace;
  38350. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  38351. if( rc==SQLITE_OK && zMaster[0] ){
  38352. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  38353. }
  38354. zMaster = 0;
  38355. if( rc!=SQLITE_OK || !res ){
  38356. goto end_playback;
  38357. }
  38358. pPager->journalOff = 0;
  38359. needPagerReset = isHot;
  38360. /* This loop terminates either when a readJournalHdr() or
  38361. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  38362. ** occurs.
  38363. */
  38364. while( 1 ){
  38365. /* Read the next journal header from the journal file. If there are
  38366. ** not enough bytes left in the journal file for a complete header, or
  38367. ** it is corrupted, then a process must have failed while writing it.
  38368. ** This indicates nothing more needs to be rolled back.
  38369. */
  38370. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  38371. if( rc!=SQLITE_OK ){
  38372. if( rc==SQLITE_DONE ){
  38373. rc = SQLITE_OK;
  38374. }
  38375. goto end_playback;
  38376. }
  38377. /* If nRec is 0xffffffff, then this journal was created by a process
  38378. ** working in no-sync mode. This means that the rest of the journal
  38379. ** file consists of pages, there are no more journal headers. Compute
  38380. ** the value of nRec based on this assumption.
  38381. */
  38382. if( nRec==0xffffffff ){
  38383. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  38384. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  38385. }
  38386. /* If nRec is 0 and this rollback is of a transaction created by this
  38387. ** process and if this is the final header in the journal, then it means
  38388. ** that this part of the journal was being filled but has not yet been
  38389. ** synced to disk. Compute the number of pages based on the remaining
  38390. ** size of the file.
  38391. **
  38392. ** The third term of the test was added to fix ticket #2565.
  38393. ** When rolling back a hot journal, nRec==0 always means that the next
  38394. ** chunk of the journal contains zero pages to be rolled back. But
  38395. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  38396. ** the journal, it means that the journal might contain additional
  38397. ** pages that need to be rolled back and that the number of pages
  38398. ** should be computed based on the journal file size.
  38399. */
  38400. if( nRec==0 && !isHot &&
  38401. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  38402. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  38403. }
  38404. /* If this is the first header read from the journal, truncate the
  38405. ** database file back to its original size.
  38406. */
  38407. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  38408. rc = pager_truncate(pPager, mxPg);
  38409. if( rc!=SQLITE_OK ){
  38410. goto end_playback;
  38411. }
  38412. pPager->dbSize = mxPg;
  38413. }
  38414. /* Copy original pages out of the journal and back into the
  38415. ** database file and/or page cache.
  38416. */
  38417. for(u=0; u<nRec; u++){
  38418. if( needPagerReset ){
  38419. pager_reset(pPager);
  38420. needPagerReset = 0;
  38421. }
  38422. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  38423. if( rc==SQLITE_OK ){
  38424. nPlayback++;
  38425. }else{
  38426. if( rc==SQLITE_DONE ){
  38427. pPager->journalOff = szJ;
  38428. break;
  38429. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  38430. /* If the journal has been truncated, simply stop reading and
  38431. ** processing the journal. This might happen if the journal was
  38432. ** not completely written and synced prior to a crash. In that
  38433. ** case, the database should have never been written in the
  38434. ** first place so it is OK to simply abandon the rollback. */
  38435. rc = SQLITE_OK;
  38436. goto end_playback;
  38437. }else{
  38438. /* If we are unable to rollback, quit and return the error
  38439. ** code. This will cause the pager to enter the error state
  38440. ** so that no further harm will be done. Perhaps the next
  38441. ** process to come along will be able to rollback the database.
  38442. */
  38443. goto end_playback;
  38444. }
  38445. }
  38446. }
  38447. }
  38448. /*NOTREACHED*/
  38449. assert( 0 );
  38450. end_playback:
  38451. /* Following a rollback, the database file should be back in its original
  38452. ** state prior to the start of the transaction, so invoke the
  38453. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  38454. ** assertion that the transaction counter was modified.
  38455. */
  38456. #ifdef SQLITE_DEBUG
  38457. if( pPager->fd->pMethods ){
  38458. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  38459. }
  38460. #endif
  38461. /* If this playback is happening automatically as a result of an IO or
  38462. ** malloc error that occurred after the change-counter was updated but
  38463. ** before the transaction was committed, then the change-counter
  38464. ** modification may just have been reverted. If this happens in exclusive
  38465. ** mode, then subsequent transactions performed by the connection will not
  38466. ** update the change-counter at all. This may lead to cache inconsistency
  38467. ** problems for other processes at some point in the future. So, just
  38468. ** in case this has happened, clear the changeCountDone flag now.
  38469. */
  38470. pPager->changeCountDone = pPager->tempFile;
  38471. if( rc==SQLITE_OK ){
  38472. zMaster = pPager->pTmpSpace;
  38473. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  38474. testcase( rc!=SQLITE_OK );
  38475. }
  38476. if( rc==SQLITE_OK
  38477. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  38478. ){
  38479. rc = sqlite3PagerSync(pPager);
  38480. }
  38481. if( rc==SQLITE_OK ){
  38482. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  38483. testcase( rc!=SQLITE_OK );
  38484. }
  38485. if( rc==SQLITE_OK && zMaster[0] && res ){
  38486. /* If there was a master journal and this routine will return success,
  38487. ** see if it is possible to delete the master journal.
  38488. */
  38489. rc = pager_delmaster(pPager, zMaster);
  38490. testcase( rc!=SQLITE_OK );
  38491. }
  38492. if( isHot && nPlayback ){
  38493. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  38494. nPlayback, pPager->zJournal);
  38495. }
  38496. /* The Pager.sectorSize variable may have been updated while rolling
  38497. ** back a journal created by a process with a different sector size
  38498. ** value. Reset it to the correct value for this process.
  38499. */
  38500. setSectorSize(pPager);
  38501. return rc;
  38502. }
  38503. /*
  38504. ** Read the content for page pPg out of the database file and into
  38505. ** pPg->pData. A shared lock or greater must be held on the database
  38506. ** file before this function is called.
  38507. **
  38508. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  38509. ** the value read from the database file.
  38510. **
  38511. ** If an IO error occurs, then the IO error is returned to the caller.
  38512. ** Otherwise, SQLITE_OK is returned.
  38513. */
  38514. static int readDbPage(PgHdr *pPg, u32 iFrame){
  38515. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  38516. Pgno pgno = pPg->pgno; /* Page number to read */
  38517. int rc = SQLITE_OK; /* Return code */
  38518. int pgsz = pPager->pageSize; /* Number of bytes to read */
  38519. assert( pPager->eState>=PAGER_READER && !MEMDB );
  38520. assert( isOpen(pPager->fd) );
  38521. if( NEVER(!isOpen(pPager->fd)) ){
  38522. assert( pPager->tempFile );
  38523. memset(pPg->pData, 0, pPager->pageSize);
  38524. return SQLITE_OK;
  38525. }
  38526. #ifndef SQLITE_OMIT_WAL
  38527. if( iFrame ){
  38528. /* Try to pull the page from the write-ahead log. */
  38529. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  38530. }else
  38531. #endif
  38532. {
  38533. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  38534. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  38535. if( rc==SQLITE_IOERR_SHORT_READ ){
  38536. rc = SQLITE_OK;
  38537. }
  38538. }
  38539. if( pgno==1 ){
  38540. if( rc ){
  38541. /* If the read is unsuccessful, set the dbFileVers[] to something
  38542. ** that will never be a valid file version. dbFileVers[] is a copy
  38543. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  38544. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  38545. ** should be page numbers which are never 0xffffffff. So filling
  38546. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  38547. **
  38548. ** For an encrypted database, the situation is more complex: bytes
  38549. ** 24..39 of the database are white noise. But the probability of
  38550. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  38551. ** we should still be ok.
  38552. */
  38553. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  38554. }else{
  38555. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  38556. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  38557. }
  38558. }
  38559. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  38560. PAGER_INCR(sqlite3_pager_readdb_count);
  38561. PAGER_INCR(pPager->nRead);
  38562. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  38563. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  38564. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  38565. return rc;
  38566. }
  38567. /*
  38568. ** Update the value of the change-counter at offsets 24 and 92 in
  38569. ** the header and the sqlite version number at offset 96.
  38570. **
  38571. ** This is an unconditional update. See also the pager_incr_changecounter()
  38572. ** routine which only updates the change-counter if the update is actually
  38573. ** needed, as determined by the pPager->changeCountDone state variable.
  38574. */
  38575. static void pager_write_changecounter(PgHdr *pPg){
  38576. u32 change_counter;
  38577. /* Increment the value just read and write it back to byte 24. */
  38578. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  38579. put32bits(((char*)pPg->pData)+24, change_counter);
  38580. /* Also store the SQLite version number in bytes 96..99 and in
  38581. ** bytes 92..95 store the change counter for which the version number
  38582. ** is valid. */
  38583. put32bits(((char*)pPg->pData)+92, change_counter);
  38584. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  38585. }
  38586. #ifndef SQLITE_OMIT_WAL
  38587. /*
  38588. ** This function is invoked once for each page that has already been
  38589. ** written into the log file when a WAL transaction is rolled back.
  38590. ** Parameter iPg is the page number of said page. The pCtx argument
  38591. ** is actually a pointer to the Pager structure.
  38592. **
  38593. ** If page iPg is present in the cache, and has no outstanding references,
  38594. ** it is discarded. Otherwise, if there are one or more outstanding
  38595. ** references, the page content is reloaded from the database. If the
  38596. ** attempt to reload content from the database is required and fails,
  38597. ** return an SQLite error code. Otherwise, SQLITE_OK.
  38598. */
  38599. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  38600. int rc = SQLITE_OK;
  38601. Pager *pPager = (Pager *)pCtx;
  38602. PgHdr *pPg;
  38603. assert( pagerUseWal(pPager) );
  38604. pPg = sqlite3PagerLookup(pPager, iPg);
  38605. if( pPg ){
  38606. if( sqlite3PcachePageRefcount(pPg)==1 ){
  38607. sqlite3PcacheDrop(pPg);
  38608. }else{
  38609. u32 iFrame = 0;
  38610. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  38611. if( rc==SQLITE_OK ){
  38612. rc = readDbPage(pPg, iFrame);
  38613. }
  38614. if( rc==SQLITE_OK ){
  38615. pPager->xReiniter(pPg);
  38616. }
  38617. sqlite3PagerUnref(pPg);
  38618. }
  38619. }
  38620. /* Normally, if a transaction is rolled back, any backup processes are
  38621. ** updated as data is copied out of the rollback journal and into the
  38622. ** database. This is not generally possible with a WAL database, as
  38623. ** rollback involves simply truncating the log file. Therefore, if one
  38624. ** or more frames have already been written to the log (and therefore
  38625. ** also copied into the backup databases) as part of this transaction,
  38626. ** the backups must be restarted.
  38627. */
  38628. sqlite3BackupRestart(pPager->pBackup);
  38629. return rc;
  38630. }
  38631. /*
  38632. ** This function is called to rollback a transaction on a WAL database.
  38633. */
  38634. static int pagerRollbackWal(Pager *pPager){
  38635. int rc; /* Return Code */
  38636. PgHdr *pList; /* List of dirty pages to revert */
  38637. /* For all pages in the cache that are currently dirty or have already
  38638. ** been written (but not committed) to the log file, do one of the
  38639. ** following:
  38640. **
  38641. ** + Discard the cached page (if refcount==0), or
  38642. ** + Reload page content from the database (if refcount>0).
  38643. */
  38644. pPager->dbSize = pPager->dbOrigSize;
  38645. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  38646. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  38647. while( pList && rc==SQLITE_OK ){
  38648. PgHdr *pNext = pList->pDirty;
  38649. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  38650. pList = pNext;
  38651. }
  38652. return rc;
  38653. }
  38654. /*
  38655. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  38656. ** the contents of the list of pages headed by pList (connected by pDirty),
  38657. ** this function notifies any active backup processes that the pages have
  38658. ** changed.
  38659. **
  38660. ** The list of pages passed into this routine is always sorted by page number.
  38661. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  38662. */
  38663. static int pagerWalFrames(
  38664. Pager *pPager, /* Pager object */
  38665. PgHdr *pList, /* List of frames to log */
  38666. Pgno nTruncate, /* Database size after this commit */
  38667. int isCommit /* True if this is a commit */
  38668. ){
  38669. int rc; /* Return code */
  38670. int nList; /* Number of pages in pList */
  38671. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  38672. PgHdr *p; /* For looping over pages */
  38673. #endif
  38674. assert( pPager->pWal );
  38675. assert( pList );
  38676. #ifdef SQLITE_DEBUG
  38677. /* Verify that the page list is in accending order */
  38678. for(p=pList; p && p->pDirty; p=p->pDirty){
  38679. assert( p->pgno < p->pDirty->pgno );
  38680. }
  38681. #endif
  38682. assert( pList->pDirty==0 || isCommit );
  38683. if( isCommit ){
  38684. /* If a WAL transaction is being committed, there is no point in writing
  38685. ** any pages with page numbers greater than nTruncate into the WAL file.
  38686. ** They will never be read by any client. So remove them from the pDirty
  38687. ** list here. */
  38688. PgHdr *p;
  38689. PgHdr **ppNext = &pList;
  38690. nList = 0;
  38691. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  38692. if( p->pgno<=nTruncate ){
  38693. ppNext = &p->pDirty;
  38694. nList++;
  38695. }
  38696. }
  38697. assert( pList );
  38698. }else{
  38699. nList = 1;
  38700. }
  38701. pPager->aStat[PAGER_STAT_WRITE] += nList;
  38702. if( pList->pgno==1 ) pager_write_changecounter(pList);
  38703. rc = sqlite3WalFrames(pPager->pWal,
  38704. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  38705. );
  38706. if( rc==SQLITE_OK && pPager->pBackup ){
  38707. PgHdr *p;
  38708. for(p=pList; p; p=p->pDirty){
  38709. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  38710. }
  38711. }
  38712. #ifdef SQLITE_CHECK_PAGES
  38713. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  38714. for(p=pList; p; p=p->pDirty){
  38715. pager_set_pagehash(p);
  38716. }
  38717. #endif
  38718. return rc;
  38719. }
  38720. /*
  38721. ** Begin a read transaction on the WAL.
  38722. **
  38723. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  38724. ** makes a snapshot of the database at the current point in time and preserves
  38725. ** that snapshot for use by the reader in spite of concurrently changes by
  38726. ** other writers or checkpointers.
  38727. */
  38728. static int pagerBeginReadTransaction(Pager *pPager){
  38729. int rc; /* Return code */
  38730. int changed = 0; /* True if cache must be reset */
  38731. assert( pagerUseWal(pPager) );
  38732. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  38733. /* sqlite3WalEndReadTransaction() was not called for the previous
  38734. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  38735. ** are in locking_mode=NORMAL and EndRead() was previously called,
  38736. ** the duplicate call is harmless.
  38737. */
  38738. sqlite3WalEndReadTransaction(pPager->pWal);
  38739. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  38740. if( rc!=SQLITE_OK || changed ){
  38741. pager_reset(pPager);
  38742. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  38743. }
  38744. return rc;
  38745. }
  38746. #endif
  38747. /*
  38748. ** This function is called as part of the transition from PAGER_OPEN
  38749. ** to PAGER_READER state to determine the size of the database file
  38750. ** in pages (assuming the page size currently stored in Pager.pageSize).
  38751. **
  38752. ** If no error occurs, SQLITE_OK is returned and the size of the database
  38753. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  38754. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  38755. */
  38756. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  38757. Pgno nPage; /* Value to return via *pnPage */
  38758. /* Query the WAL sub-system for the database size. The WalDbsize()
  38759. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  38760. ** if the database size is not available. The database size is not
  38761. ** available from the WAL sub-system if the log file is empty or
  38762. ** contains no valid committed transactions.
  38763. */
  38764. assert( pPager->eState==PAGER_OPEN );
  38765. assert( pPager->eLock>=SHARED_LOCK );
  38766. nPage = sqlite3WalDbsize(pPager->pWal);
  38767. /* If the database size was not available from the WAL sub-system,
  38768. ** determine it based on the size of the database file. If the size
  38769. ** of the database file is not an integer multiple of the page-size,
  38770. ** round down to the nearest page. Except, any file larger than 0
  38771. ** bytes in size is considered to contain at least one page.
  38772. */
  38773. if( nPage==0 ){
  38774. i64 n = 0; /* Size of db file in bytes */
  38775. assert( isOpen(pPager->fd) || pPager->tempFile );
  38776. if( isOpen(pPager->fd) ){
  38777. int rc = sqlite3OsFileSize(pPager->fd, &n);
  38778. if( rc!=SQLITE_OK ){
  38779. return rc;
  38780. }
  38781. }
  38782. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  38783. }
  38784. /* If the current number of pages in the file is greater than the
  38785. ** configured maximum pager number, increase the allowed limit so
  38786. ** that the file can be read.
  38787. */
  38788. if( nPage>pPager->mxPgno ){
  38789. pPager->mxPgno = (Pgno)nPage;
  38790. }
  38791. *pnPage = nPage;
  38792. return SQLITE_OK;
  38793. }
  38794. #ifndef SQLITE_OMIT_WAL
  38795. /*
  38796. ** Check if the *-wal file that corresponds to the database opened by pPager
  38797. ** exists if the database is not empy, or verify that the *-wal file does
  38798. ** not exist (by deleting it) if the database file is empty.
  38799. **
  38800. ** If the database is not empty and the *-wal file exists, open the pager
  38801. ** in WAL mode. If the database is empty or if no *-wal file exists and
  38802. ** if no error occurs, make sure Pager.journalMode is not set to
  38803. ** PAGER_JOURNALMODE_WAL.
  38804. **
  38805. ** Return SQLITE_OK or an error code.
  38806. **
  38807. ** The caller must hold a SHARED lock on the database file to call this
  38808. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  38809. ** a WAL on a none-empty database, this ensures there is no race condition
  38810. ** between the xAccess() below and an xDelete() being executed by some
  38811. ** other connection.
  38812. */
  38813. static int pagerOpenWalIfPresent(Pager *pPager){
  38814. int rc = SQLITE_OK;
  38815. assert( pPager->eState==PAGER_OPEN );
  38816. assert( pPager->eLock>=SHARED_LOCK );
  38817. if( !pPager->tempFile ){
  38818. int isWal; /* True if WAL file exists */
  38819. Pgno nPage; /* Size of the database file */
  38820. rc = pagerPagecount(pPager, &nPage);
  38821. if( rc ) return rc;
  38822. if( nPage==0 ){
  38823. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  38824. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  38825. isWal = 0;
  38826. }else{
  38827. rc = sqlite3OsAccess(
  38828. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  38829. );
  38830. }
  38831. if( rc==SQLITE_OK ){
  38832. if( isWal ){
  38833. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  38834. rc = sqlite3PagerOpenWal(pPager, 0);
  38835. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  38836. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  38837. }
  38838. }
  38839. }
  38840. return rc;
  38841. }
  38842. #endif
  38843. /*
  38844. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  38845. ** the entire master journal file. The case pSavepoint==NULL occurs when
  38846. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  38847. ** savepoint.
  38848. **
  38849. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  38850. ** being rolled back), then the rollback consists of up to three stages,
  38851. ** performed in the order specified:
  38852. **
  38853. ** * Pages are played back from the main journal starting at byte
  38854. ** offset PagerSavepoint.iOffset and continuing to
  38855. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  38856. ** file if PagerSavepoint.iHdrOffset is zero.
  38857. **
  38858. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  38859. ** back starting from the journal header immediately following
  38860. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  38861. **
  38862. ** * Pages are then played back from the sub-journal file, starting
  38863. ** with the PagerSavepoint.iSubRec and continuing to the end of
  38864. ** the journal file.
  38865. **
  38866. ** Throughout the rollback process, each time a page is rolled back, the
  38867. ** corresponding bit is set in a bitvec structure (variable pDone in the
  38868. ** implementation below). This is used to ensure that a page is only
  38869. ** rolled back the first time it is encountered in either journal.
  38870. **
  38871. ** If pSavepoint is NULL, then pages are only played back from the main
  38872. ** journal file. There is no need for a bitvec in this case.
  38873. **
  38874. ** In either case, before playback commences the Pager.dbSize variable
  38875. ** is reset to the value that it held at the start of the savepoint
  38876. ** (or transaction). No page with a page-number greater than this value
  38877. ** is played back. If one is encountered it is simply skipped.
  38878. */
  38879. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  38880. i64 szJ; /* Effective size of the main journal */
  38881. i64 iHdrOff; /* End of first segment of main-journal records */
  38882. int rc = SQLITE_OK; /* Return code */
  38883. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  38884. assert( pPager->eState!=PAGER_ERROR );
  38885. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  38886. /* Allocate a bitvec to use to store the set of pages rolled back */
  38887. if( pSavepoint ){
  38888. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  38889. if( !pDone ){
  38890. return SQLITE_NOMEM;
  38891. }
  38892. }
  38893. /* Set the database size back to the value it was before the savepoint
  38894. ** being reverted was opened.
  38895. */
  38896. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  38897. pPager->changeCountDone = pPager->tempFile;
  38898. if( !pSavepoint && pagerUseWal(pPager) ){
  38899. return pagerRollbackWal(pPager);
  38900. }
  38901. /* Use pPager->journalOff as the effective size of the main rollback
  38902. ** journal. The actual file might be larger than this in
  38903. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  38904. ** past pPager->journalOff is off-limits to us.
  38905. */
  38906. szJ = pPager->journalOff;
  38907. assert( pagerUseWal(pPager)==0 || szJ==0 );
  38908. /* Begin by rolling back records from the main journal starting at
  38909. ** PagerSavepoint.iOffset and continuing to the next journal header.
  38910. ** There might be records in the main journal that have a page number
  38911. ** greater than the current database size (pPager->dbSize) but those
  38912. ** will be skipped automatically. Pages are added to pDone as they
  38913. ** are played back.
  38914. */
  38915. if( pSavepoint && !pagerUseWal(pPager) ){
  38916. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  38917. pPager->journalOff = pSavepoint->iOffset;
  38918. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  38919. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  38920. }
  38921. assert( rc!=SQLITE_DONE );
  38922. }else{
  38923. pPager->journalOff = 0;
  38924. }
  38925. /* Continue rolling back records out of the main journal starting at
  38926. ** the first journal header seen and continuing until the effective end
  38927. ** of the main journal file. Continue to skip out-of-range pages and
  38928. ** continue adding pages rolled back to pDone.
  38929. */
  38930. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  38931. u32 ii; /* Loop counter */
  38932. u32 nJRec = 0; /* Number of Journal Records */
  38933. u32 dummy;
  38934. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  38935. assert( rc!=SQLITE_DONE );
  38936. /*
  38937. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  38938. ** test is related to ticket #2565. See the discussion in the
  38939. ** pager_playback() function for additional information.
  38940. */
  38941. if( nJRec==0
  38942. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  38943. ){
  38944. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  38945. }
  38946. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  38947. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  38948. }
  38949. assert( rc!=SQLITE_DONE );
  38950. }
  38951. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  38952. /* Finally, rollback pages from the sub-journal. Page that were
  38953. ** previously rolled back out of the main journal (and are hence in pDone)
  38954. ** will be skipped. Out-of-range pages are also skipped.
  38955. */
  38956. if( pSavepoint ){
  38957. u32 ii; /* Loop counter */
  38958. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  38959. if( pagerUseWal(pPager) ){
  38960. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  38961. }
  38962. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  38963. assert( offset==(i64)ii*(4+pPager->pageSize) );
  38964. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  38965. }
  38966. assert( rc!=SQLITE_DONE );
  38967. }
  38968. sqlite3BitvecDestroy(pDone);
  38969. if( rc==SQLITE_OK ){
  38970. pPager->journalOff = szJ;
  38971. }
  38972. return rc;
  38973. }
  38974. /*
  38975. ** Change the maximum number of in-memory pages that are allowed.
  38976. */
  38977. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  38978. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  38979. }
  38980. /*
  38981. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  38982. */
  38983. static void pagerFixMaplimit(Pager *pPager){
  38984. #if SQLITE_MAX_MMAP_SIZE>0
  38985. sqlite3_file *fd = pPager->fd;
  38986. if( isOpen(fd) ){
  38987. sqlite3_int64 sz;
  38988. pPager->bUseFetch = (fd->pMethods->iVersion>=3) && pPager->szMmap>0;
  38989. sz = pPager->szMmap;
  38990. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  38991. }
  38992. #endif
  38993. }
  38994. /*
  38995. ** Change the maximum size of any memory mapping made of the database file.
  38996. */
  38997. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  38998. pPager->szMmap = szMmap;
  38999. pagerFixMaplimit(pPager);
  39000. }
  39001. /*
  39002. ** Free as much memory as possible from the pager.
  39003. */
  39004. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  39005. sqlite3PcacheShrink(pPager->pPCache);
  39006. }
  39007. /*
  39008. ** Adjust the robustness of the database to damage due to OS crashes
  39009. ** or power failures by changing the number of syncs()s when writing
  39010. ** the rollback journal. There are three levels:
  39011. **
  39012. ** OFF sqlite3OsSync() is never called. This is the default
  39013. ** for temporary and transient files.
  39014. **
  39015. ** NORMAL The journal is synced once before writes begin on the
  39016. ** database. This is normally adequate protection, but
  39017. ** it is theoretically possible, though very unlikely,
  39018. ** that an inopertune power failure could leave the journal
  39019. ** in a state which would cause damage to the database
  39020. ** when it is rolled back.
  39021. **
  39022. ** FULL The journal is synced twice before writes begin on the
  39023. ** database (with some additional information - the nRec field
  39024. ** of the journal header - being written in between the two
  39025. ** syncs). If we assume that writing a
  39026. ** single disk sector is atomic, then this mode provides
  39027. ** assurance that the journal will not be corrupted to the
  39028. ** point of causing damage to the database during rollback.
  39029. **
  39030. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  39031. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  39032. ** prior to the start of checkpoint and that the database file is synced
  39033. ** at the conclusion of the checkpoint if the entire content of the WAL
  39034. ** was written back into the database. But no sync operations occur for
  39035. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  39036. ** file is synced following each commit operation, in addition to the
  39037. ** syncs associated with NORMAL.
  39038. **
  39039. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  39040. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  39041. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  39042. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  39043. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  39044. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  39045. ** the xSync primitive is called and is relevant to all platforms.
  39046. **
  39047. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  39048. ** and FULL=3.
  39049. */
  39050. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  39051. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
  39052. Pager *pPager, /* The pager to set safety level for */
  39053. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  39054. int bFullFsync, /* PRAGMA fullfsync */
  39055. int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
  39056. ){
  39057. assert( level>=1 && level<=3 );
  39058. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  39059. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  39060. if( pPager->noSync ){
  39061. pPager->syncFlags = 0;
  39062. pPager->ckptSyncFlags = 0;
  39063. }else if( bFullFsync ){
  39064. pPager->syncFlags = SQLITE_SYNC_FULL;
  39065. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  39066. }else if( bCkptFullFsync ){
  39067. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  39068. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  39069. }else{
  39070. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  39071. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  39072. }
  39073. pPager->walSyncFlags = pPager->syncFlags;
  39074. if( pPager->fullSync ){
  39075. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  39076. }
  39077. }
  39078. #endif
  39079. /*
  39080. ** The following global variable is incremented whenever the library
  39081. ** attempts to open a temporary file. This information is used for
  39082. ** testing and analysis only.
  39083. */
  39084. #ifdef SQLITE_TEST
  39085. SQLITE_API int sqlite3_opentemp_count = 0;
  39086. #endif
  39087. /*
  39088. ** Open a temporary file.
  39089. **
  39090. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  39091. ** or some other error code if we fail. The OS will automatically
  39092. ** delete the temporary file when it is closed.
  39093. **
  39094. ** The flags passed to the VFS layer xOpen() call are those specified
  39095. ** by parameter vfsFlags ORed with the following:
  39096. **
  39097. ** SQLITE_OPEN_READWRITE
  39098. ** SQLITE_OPEN_CREATE
  39099. ** SQLITE_OPEN_EXCLUSIVE
  39100. ** SQLITE_OPEN_DELETEONCLOSE
  39101. */
  39102. static int pagerOpentemp(
  39103. Pager *pPager, /* The pager object */
  39104. sqlite3_file *pFile, /* Write the file descriptor here */
  39105. int vfsFlags /* Flags passed through to the VFS */
  39106. ){
  39107. int rc; /* Return code */
  39108. #ifdef SQLITE_TEST
  39109. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  39110. #endif
  39111. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  39112. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  39113. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  39114. assert( rc!=SQLITE_OK || isOpen(pFile) );
  39115. return rc;
  39116. }
  39117. /*
  39118. ** Set the busy handler function.
  39119. **
  39120. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  39121. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  39122. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  39123. ** lock. It does *not* invoke the busy handler when upgrading from
  39124. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  39125. ** (which occurs during hot-journal rollback). Summary:
  39126. **
  39127. ** Transition | Invokes xBusyHandler
  39128. ** --------------------------------------------------------
  39129. ** NO_LOCK -> SHARED_LOCK | Yes
  39130. ** SHARED_LOCK -> RESERVED_LOCK | No
  39131. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  39132. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  39133. **
  39134. ** If the busy-handler callback returns non-zero, the lock is
  39135. ** retried. If it returns zero, then the SQLITE_BUSY error is
  39136. ** returned to the caller of the pager API function.
  39137. */
  39138. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  39139. Pager *pPager, /* Pager object */
  39140. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  39141. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  39142. ){
  39143. pPager->xBusyHandler = xBusyHandler;
  39144. pPager->pBusyHandlerArg = pBusyHandlerArg;
  39145. if( isOpen(pPager->fd) ){
  39146. void **ap = (void **)&pPager->xBusyHandler;
  39147. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  39148. assert( ap[1]==pBusyHandlerArg );
  39149. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  39150. }
  39151. }
  39152. /*
  39153. ** Change the page size used by the Pager object. The new page size
  39154. ** is passed in *pPageSize.
  39155. **
  39156. ** If the pager is in the error state when this function is called, it
  39157. ** is a no-op. The value returned is the error state error code (i.e.
  39158. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  39159. **
  39160. ** Otherwise, if all of the following are true:
  39161. **
  39162. ** * the new page size (value of *pPageSize) is valid (a power
  39163. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  39164. **
  39165. ** * there are no outstanding page references, and
  39166. **
  39167. ** * the database is either not an in-memory database or it is
  39168. ** an in-memory database that currently consists of zero pages.
  39169. **
  39170. ** then the pager object page size is set to *pPageSize.
  39171. **
  39172. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  39173. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  39174. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  39175. ** In all other cases, SQLITE_OK is returned.
  39176. **
  39177. ** If the page size is not changed, either because one of the enumerated
  39178. ** conditions above is not true, the pager was in error state when this
  39179. ** function was called, or because the memory allocation attempt failed,
  39180. ** then *pPageSize is set to the old, retained page size before returning.
  39181. */
  39182. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  39183. int rc = SQLITE_OK;
  39184. /* It is not possible to do a full assert_pager_state() here, as this
  39185. ** function may be called from within PagerOpen(), before the state
  39186. ** of the Pager object is internally consistent.
  39187. **
  39188. ** At one point this function returned an error if the pager was in
  39189. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  39190. ** there is at least one outstanding page reference, this function
  39191. ** is a no-op for that case anyhow.
  39192. */
  39193. u32 pageSize = *pPageSize;
  39194. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  39195. if( (pPager->memDb==0 || pPager->dbSize==0)
  39196. && sqlite3PcacheRefCount(pPager->pPCache)==0
  39197. && pageSize && pageSize!=(u32)pPager->pageSize
  39198. ){
  39199. char *pNew = NULL; /* New temp space */
  39200. i64 nByte = 0;
  39201. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  39202. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  39203. }
  39204. if( rc==SQLITE_OK ){
  39205. pNew = (char *)sqlite3PageMalloc(pageSize);
  39206. if( !pNew ) rc = SQLITE_NOMEM;
  39207. }
  39208. if( rc==SQLITE_OK ){
  39209. pager_reset(pPager);
  39210. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  39211. pPager->pageSize = pageSize;
  39212. sqlite3PageFree(pPager->pTmpSpace);
  39213. pPager->pTmpSpace = pNew;
  39214. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  39215. }
  39216. }
  39217. *pPageSize = pPager->pageSize;
  39218. if( rc==SQLITE_OK ){
  39219. if( nReserve<0 ) nReserve = pPager->nReserve;
  39220. assert( nReserve>=0 && nReserve<1000 );
  39221. pPager->nReserve = (i16)nReserve;
  39222. pagerReportSize(pPager);
  39223. pagerFixMaplimit(pPager);
  39224. }
  39225. return rc;
  39226. }
  39227. /*
  39228. ** Return a pointer to the "temporary page" buffer held internally
  39229. ** by the pager. This is a buffer that is big enough to hold the
  39230. ** entire content of a database page. This buffer is used internally
  39231. ** during rollback and will be overwritten whenever a rollback
  39232. ** occurs. But other modules are free to use it too, as long as
  39233. ** no rollbacks are happening.
  39234. */
  39235. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  39236. return pPager->pTmpSpace;
  39237. }
  39238. /*
  39239. ** Attempt to set the maximum database page count if mxPage is positive.
  39240. ** Make no changes if mxPage is zero or negative. And never reduce the
  39241. ** maximum page count below the current size of the database.
  39242. **
  39243. ** Regardless of mxPage, return the current maximum page count.
  39244. */
  39245. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  39246. if( mxPage>0 ){
  39247. pPager->mxPgno = mxPage;
  39248. }
  39249. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  39250. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  39251. return pPager->mxPgno;
  39252. }
  39253. /*
  39254. ** The following set of routines are used to disable the simulated
  39255. ** I/O error mechanism. These routines are used to avoid simulated
  39256. ** errors in places where we do not care about errors.
  39257. **
  39258. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  39259. ** and generate no code.
  39260. */
  39261. #ifdef SQLITE_TEST
  39262. SQLITE_API extern int sqlite3_io_error_pending;
  39263. SQLITE_API extern int sqlite3_io_error_hit;
  39264. static int saved_cnt;
  39265. void disable_simulated_io_errors(void){
  39266. saved_cnt = sqlite3_io_error_pending;
  39267. sqlite3_io_error_pending = -1;
  39268. }
  39269. void enable_simulated_io_errors(void){
  39270. sqlite3_io_error_pending = saved_cnt;
  39271. }
  39272. #else
  39273. # define disable_simulated_io_errors()
  39274. # define enable_simulated_io_errors()
  39275. #endif
  39276. /*
  39277. ** Read the first N bytes from the beginning of the file into memory
  39278. ** that pDest points to.
  39279. **
  39280. ** If the pager was opened on a transient file (zFilename==""), or
  39281. ** opened on a file less than N bytes in size, the output buffer is
  39282. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  39283. ** function is used to read database headers, and a new transient or
  39284. ** zero sized database has a header than consists entirely of zeroes.
  39285. **
  39286. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  39287. ** the error code is returned to the caller and the contents of the
  39288. ** output buffer undefined.
  39289. */
  39290. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  39291. int rc = SQLITE_OK;
  39292. memset(pDest, 0, N);
  39293. assert( isOpen(pPager->fd) || pPager->tempFile );
  39294. /* This routine is only called by btree immediately after creating
  39295. ** the Pager object. There has not been an opportunity to transition
  39296. ** to WAL mode yet.
  39297. */
  39298. assert( !pagerUseWal(pPager) );
  39299. if( isOpen(pPager->fd) ){
  39300. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  39301. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  39302. if( rc==SQLITE_IOERR_SHORT_READ ){
  39303. rc = SQLITE_OK;
  39304. }
  39305. }
  39306. return rc;
  39307. }
  39308. /*
  39309. ** This function may only be called when a read-transaction is open on
  39310. ** the pager. It returns the total number of pages in the database.
  39311. **
  39312. ** However, if the file is between 1 and <page-size> bytes in size, then
  39313. ** this is considered a 1 page file.
  39314. */
  39315. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  39316. assert( pPager->eState>=PAGER_READER );
  39317. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  39318. *pnPage = (int)pPager->dbSize;
  39319. }
  39320. /*
  39321. ** Try to obtain a lock of type locktype on the database file. If
  39322. ** a similar or greater lock is already held, this function is a no-op
  39323. ** (returning SQLITE_OK immediately).
  39324. **
  39325. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  39326. ** the busy callback if the lock is currently not available. Repeat
  39327. ** until the busy callback returns false or until the attempt to
  39328. ** obtain the lock succeeds.
  39329. **
  39330. ** Return SQLITE_OK on success and an error code if we cannot obtain
  39331. ** the lock. If the lock is obtained successfully, set the Pager.state
  39332. ** variable to locktype before returning.
  39333. */
  39334. static int pager_wait_on_lock(Pager *pPager, int locktype){
  39335. int rc; /* Return code */
  39336. /* Check that this is either a no-op (because the requested lock is
  39337. ** already held, or one of the transistions that the busy-handler
  39338. ** may be invoked during, according to the comment above
  39339. ** sqlite3PagerSetBusyhandler().
  39340. */
  39341. assert( (pPager->eLock>=locktype)
  39342. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  39343. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  39344. );
  39345. do {
  39346. rc = pagerLockDb(pPager, locktype);
  39347. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  39348. return rc;
  39349. }
  39350. /*
  39351. ** Function assertTruncateConstraint(pPager) checks that one of the
  39352. ** following is true for all dirty pages currently in the page-cache:
  39353. **
  39354. ** a) The page number is less than or equal to the size of the
  39355. ** current database image, in pages, OR
  39356. **
  39357. ** b) if the page content were written at this time, it would not
  39358. ** be necessary to write the current content out to the sub-journal
  39359. ** (as determined by function subjRequiresPage()).
  39360. **
  39361. ** If the condition asserted by this function were not true, and the
  39362. ** dirty page were to be discarded from the cache via the pagerStress()
  39363. ** routine, pagerStress() would not write the current page content to
  39364. ** the database file. If a savepoint transaction were rolled back after
  39365. ** this happened, the correct behavior would be to restore the current
  39366. ** content of the page. However, since this content is not present in either
  39367. ** the database file or the portion of the rollback journal and
  39368. ** sub-journal rolled back the content could not be restored and the
  39369. ** database image would become corrupt. It is therefore fortunate that
  39370. ** this circumstance cannot arise.
  39371. */
  39372. #if defined(SQLITE_DEBUG)
  39373. static void assertTruncateConstraintCb(PgHdr *pPg){
  39374. assert( pPg->flags&PGHDR_DIRTY );
  39375. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  39376. }
  39377. static void assertTruncateConstraint(Pager *pPager){
  39378. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  39379. }
  39380. #else
  39381. # define assertTruncateConstraint(pPager)
  39382. #endif
  39383. /*
  39384. ** Truncate the in-memory database file image to nPage pages. This
  39385. ** function does not actually modify the database file on disk. It
  39386. ** just sets the internal state of the pager object so that the
  39387. ** truncation will be done when the current transaction is committed.
  39388. **
  39389. ** This function is only called right before committing a transaction.
  39390. ** Once this function has been called, the transaction must either be
  39391. ** rolled back or committed. It is not safe to call this function and
  39392. ** then continue writing to the database.
  39393. */
  39394. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  39395. assert( pPager->dbSize>=nPage );
  39396. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  39397. pPager->dbSize = nPage;
  39398. /* At one point the code here called assertTruncateConstraint() to
  39399. ** ensure that all pages being truncated away by this operation are,
  39400. ** if one or more savepoints are open, present in the savepoint
  39401. ** journal so that they can be restored if the savepoint is rolled
  39402. ** back. This is no longer necessary as this function is now only
  39403. ** called right before committing a transaction. So although the
  39404. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  39405. ** they cannot be rolled back. So the assertTruncateConstraint() call
  39406. ** is no longer correct. */
  39407. }
  39408. /*
  39409. ** This function is called before attempting a hot-journal rollback. It
  39410. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  39411. ** size of the journal file so that the pager_playback() routine knows
  39412. ** that the entire journal file has been synced.
  39413. **
  39414. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  39415. ** that if a power-failure occurs during the rollback, the process that
  39416. ** attempts rollback following system recovery sees the same journal
  39417. ** content as this process.
  39418. **
  39419. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  39420. ** an SQLite error code.
  39421. */
  39422. static int pagerSyncHotJournal(Pager *pPager){
  39423. int rc = SQLITE_OK;
  39424. if( !pPager->noSync ){
  39425. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  39426. }
  39427. if( rc==SQLITE_OK ){
  39428. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  39429. }
  39430. return rc;
  39431. }
  39432. /*
  39433. ** Obtain a reference to a memory mapped page object for page number pgno.
  39434. ** The new object will use the pointer pData, obtained from xFetch().
  39435. ** If successful, set *ppPage to point to the new page reference
  39436. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  39437. ** *ppPage to zero.
  39438. **
  39439. ** Page references obtained by calling this function should be released
  39440. ** by calling pagerReleaseMapPage().
  39441. */
  39442. static int pagerAcquireMapPage(
  39443. Pager *pPager, /* Pager object */
  39444. Pgno pgno, /* Page number */
  39445. void *pData, /* xFetch()'d data for this page */
  39446. PgHdr **ppPage /* OUT: Acquired page object */
  39447. ){
  39448. PgHdr *p; /* Memory mapped page to return */
  39449. if( pPager->pMmapFreelist ){
  39450. *ppPage = p = pPager->pMmapFreelist;
  39451. pPager->pMmapFreelist = p->pDirty;
  39452. p->pDirty = 0;
  39453. memset(p->pExtra, 0, pPager->nExtra);
  39454. }else{
  39455. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  39456. if( p==0 ){
  39457. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  39458. return SQLITE_NOMEM;
  39459. }
  39460. p->pExtra = (void *)&p[1];
  39461. p->flags = PGHDR_MMAP;
  39462. p->nRef = 1;
  39463. p->pPager = pPager;
  39464. }
  39465. assert( p->pExtra==(void *)&p[1] );
  39466. assert( p->pPage==0 );
  39467. assert( p->flags==PGHDR_MMAP );
  39468. assert( p->pPager==pPager );
  39469. assert( p->nRef==1 );
  39470. p->pgno = pgno;
  39471. p->pData = pData;
  39472. pPager->nMmapOut++;
  39473. return SQLITE_OK;
  39474. }
  39475. /*
  39476. ** Release a reference to page pPg. pPg must have been returned by an
  39477. ** earlier call to pagerAcquireMapPage().
  39478. */
  39479. static void pagerReleaseMapPage(PgHdr *pPg){
  39480. Pager *pPager = pPg->pPager;
  39481. pPager->nMmapOut--;
  39482. pPg->pDirty = pPager->pMmapFreelist;
  39483. pPager->pMmapFreelist = pPg;
  39484. assert( pPager->fd->pMethods->iVersion>=3 );
  39485. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  39486. }
  39487. /*
  39488. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  39489. */
  39490. static void pagerFreeMapHdrs(Pager *pPager){
  39491. PgHdr *p;
  39492. PgHdr *pNext;
  39493. for(p=pPager->pMmapFreelist; p; p=pNext){
  39494. pNext = p->pDirty;
  39495. sqlite3_free(p);
  39496. }
  39497. }
  39498. /*
  39499. ** Shutdown the page cache. Free all memory and close all files.
  39500. **
  39501. ** If a transaction was in progress when this routine is called, that
  39502. ** transaction is rolled back. All outstanding pages are invalidated
  39503. ** and their memory is freed. Any attempt to use a page associated
  39504. ** with this page cache after this function returns will likely
  39505. ** result in a coredump.
  39506. **
  39507. ** This function always succeeds. If a transaction is active an attempt
  39508. ** is made to roll it back. If an error occurs during the rollback
  39509. ** a hot journal may be left in the filesystem but no error is returned
  39510. ** to the caller.
  39511. */
  39512. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  39513. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  39514. assert( assert_pager_state(pPager) );
  39515. disable_simulated_io_errors();
  39516. sqlite3BeginBenignMalloc();
  39517. pagerFreeMapHdrs(pPager);
  39518. /* pPager->errCode = 0; */
  39519. pPager->exclusiveMode = 0;
  39520. #ifndef SQLITE_OMIT_WAL
  39521. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  39522. pPager->pWal = 0;
  39523. #endif
  39524. pager_reset(pPager);
  39525. if( MEMDB ){
  39526. pager_unlock(pPager);
  39527. }else{
  39528. /* If it is open, sync the journal file before calling UnlockAndRollback.
  39529. ** If this is not done, then an unsynced portion of the open journal
  39530. ** file may be played back into the database. If a power failure occurs
  39531. ** while this is happening, the database could become corrupt.
  39532. **
  39533. ** If an error occurs while trying to sync the journal, shift the pager
  39534. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  39535. ** database and close the journal file without attempting to roll it
  39536. ** back or finalize it. The next database user will have to do hot-journal
  39537. ** rollback before accessing the database file.
  39538. */
  39539. if( isOpen(pPager->jfd) ){
  39540. pager_error(pPager, pagerSyncHotJournal(pPager));
  39541. }
  39542. pagerUnlockAndRollback(pPager);
  39543. }
  39544. sqlite3EndBenignMalloc();
  39545. enable_simulated_io_errors();
  39546. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  39547. IOTRACE(("CLOSE %p\n", pPager))
  39548. sqlite3OsClose(pPager->jfd);
  39549. sqlite3OsClose(pPager->fd);
  39550. sqlite3PageFree(pTmp);
  39551. sqlite3PcacheClose(pPager->pPCache);
  39552. #ifdef SQLITE_HAS_CODEC
  39553. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  39554. #endif
  39555. assert( !pPager->aSavepoint && !pPager->pInJournal );
  39556. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  39557. sqlite3_free(pPager);
  39558. return SQLITE_OK;
  39559. }
  39560. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  39561. /*
  39562. ** Return the page number for page pPg.
  39563. */
  39564. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  39565. return pPg->pgno;
  39566. }
  39567. #endif
  39568. /*
  39569. ** Increment the reference count for page pPg.
  39570. */
  39571. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  39572. sqlite3PcacheRef(pPg);
  39573. }
  39574. /*
  39575. ** Sync the journal. In other words, make sure all the pages that have
  39576. ** been written to the journal have actually reached the surface of the
  39577. ** disk and can be restored in the event of a hot-journal rollback.
  39578. **
  39579. ** If the Pager.noSync flag is set, then this function is a no-op.
  39580. ** Otherwise, the actions required depend on the journal-mode and the
  39581. ** device characteristics of the file-system, as follows:
  39582. **
  39583. ** * If the journal file is an in-memory journal file, no action need
  39584. ** be taken.
  39585. **
  39586. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  39587. ** then the nRec field of the most recently written journal header
  39588. ** is updated to contain the number of journal records that have
  39589. ** been written following it. If the pager is operating in full-sync
  39590. ** mode, then the journal file is synced before this field is updated.
  39591. **
  39592. ** * If the device does not support the SEQUENTIAL property, then
  39593. ** journal file is synced.
  39594. **
  39595. ** Or, in pseudo-code:
  39596. **
  39597. ** if( NOT <in-memory journal> ){
  39598. ** if( NOT SAFE_APPEND ){
  39599. ** if( <full-sync mode> ) xSync(<journal file>);
  39600. ** <update nRec field>
  39601. ** }
  39602. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  39603. ** }
  39604. **
  39605. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  39606. ** page currently held in memory before returning SQLITE_OK. If an IO
  39607. ** error is encountered, then the IO error code is returned to the caller.
  39608. */
  39609. static int syncJournal(Pager *pPager, int newHdr){
  39610. int rc; /* Return code */
  39611. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  39612. || pPager->eState==PAGER_WRITER_DBMOD
  39613. );
  39614. assert( assert_pager_state(pPager) );
  39615. assert( !pagerUseWal(pPager) );
  39616. rc = sqlite3PagerExclusiveLock(pPager);
  39617. if( rc!=SQLITE_OK ) return rc;
  39618. if( !pPager->noSync ){
  39619. assert( !pPager->tempFile );
  39620. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  39621. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  39622. assert( isOpen(pPager->jfd) );
  39623. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  39624. /* This block deals with an obscure problem. If the last connection
  39625. ** that wrote to this database was operating in persistent-journal
  39626. ** mode, then the journal file may at this point actually be larger
  39627. ** than Pager.journalOff bytes. If the next thing in the journal
  39628. ** file happens to be a journal-header (written as part of the
  39629. ** previous connection's transaction), and a crash or power-failure
  39630. ** occurs after nRec is updated but before this connection writes
  39631. ** anything else to the journal file (or commits/rolls back its
  39632. ** transaction), then SQLite may become confused when doing the
  39633. ** hot-journal rollback following recovery. It may roll back all
  39634. ** of this connections data, then proceed to rolling back the old,
  39635. ** out-of-date data that follows it. Database corruption.
  39636. **
  39637. ** To work around this, if the journal file does appear to contain
  39638. ** a valid header following Pager.journalOff, then write a 0x00
  39639. ** byte to the start of it to prevent it from being recognized.
  39640. **
  39641. ** Variable iNextHdrOffset is set to the offset at which this
  39642. ** problematic header will occur, if it exists. aMagic is used
  39643. ** as a temporary buffer to inspect the first couple of bytes of
  39644. ** the potential journal header.
  39645. */
  39646. i64 iNextHdrOffset;
  39647. u8 aMagic[8];
  39648. u8 zHeader[sizeof(aJournalMagic)+4];
  39649. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  39650. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  39651. iNextHdrOffset = journalHdrOffset(pPager);
  39652. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  39653. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  39654. static const u8 zerobyte = 0;
  39655. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  39656. }
  39657. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  39658. return rc;
  39659. }
  39660. /* Write the nRec value into the journal file header. If in
  39661. ** full-synchronous mode, sync the journal first. This ensures that
  39662. ** all data has really hit the disk before nRec is updated to mark
  39663. ** it as a candidate for rollback.
  39664. **
  39665. ** This is not required if the persistent media supports the
  39666. ** SAFE_APPEND property. Because in this case it is not possible
  39667. ** for garbage data to be appended to the file, the nRec field
  39668. ** is populated with 0xFFFFFFFF when the journal header is written
  39669. ** and never needs to be updated.
  39670. */
  39671. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  39672. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  39673. IOTRACE(("JSYNC %p\n", pPager))
  39674. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  39675. if( rc!=SQLITE_OK ) return rc;
  39676. }
  39677. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  39678. rc = sqlite3OsWrite(
  39679. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  39680. );
  39681. if( rc!=SQLITE_OK ) return rc;
  39682. }
  39683. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  39684. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  39685. IOTRACE(("JSYNC %p\n", pPager))
  39686. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  39687. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  39688. );
  39689. if( rc!=SQLITE_OK ) return rc;
  39690. }
  39691. pPager->journalHdr = pPager->journalOff;
  39692. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  39693. pPager->nRec = 0;
  39694. rc = writeJournalHdr(pPager);
  39695. if( rc!=SQLITE_OK ) return rc;
  39696. }
  39697. }else{
  39698. pPager->journalHdr = pPager->journalOff;
  39699. }
  39700. }
  39701. /* Unless the pager is in noSync mode, the journal file was just
  39702. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  39703. ** all pages.
  39704. */
  39705. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  39706. pPager->eState = PAGER_WRITER_DBMOD;
  39707. assert( assert_pager_state(pPager) );
  39708. return SQLITE_OK;
  39709. }
  39710. /*
  39711. ** The argument is the first in a linked list of dirty pages connected
  39712. ** by the PgHdr.pDirty pointer. This function writes each one of the
  39713. ** in-memory pages in the list to the database file. The argument may
  39714. ** be NULL, representing an empty list. In this case this function is
  39715. ** a no-op.
  39716. **
  39717. ** The pager must hold at least a RESERVED lock when this function
  39718. ** is called. Before writing anything to the database file, this lock
  39719. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  39720. ** SQLITE_BUSY is returned and no data is written to the database file.
  39721. **
  39722. ** If the pager is a temp-file pager and the actual file-system file
  39723. ** is not yet open, it is created and opened before any data is
  39724. ** written out.
  39725. **
  39726. ** Once the lock has been upgraded and, if necessary, the file opened,
  39727. ** the pages are written out to the database file in list order. Writing
  39728. ** a page is skipped if it meets either of the following criteria:
  39729. **
  39730. ** * The page number is greater than Pager.dbSize, or
  39731. ** * The PGHDR_DONT_WRITE flag is set on the page.
  39732. **
  39733. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  39734. ** is updated accordingly. If page 1 is written out, then the value cached
  39735. ** in Pager.dbFileVers[] is updated to match the new value stored in
  39736. ** the database file.
  39737. **
  39738. ** If everything is successful, SQLITE_OK is returned. If an IO error
  39739. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  39740. ** be obtained, SQLITE_BUSY is returned.
  39741. */
  39742. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  39743. int rc = SQLITE_OK; /* Return code */
  39744. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  39745. assert( !pagerUseWal(pPager) );
  39746. assert( pPager->eState==PAGER_WRITER_DBMOD );
  39747. assert( pPager->eLock==EXCLUSIVE_LOCK );
  39748. /* If the file is a temp-file has not yet been opened, open it now. It
  39749. ** is not possible for rc to be other than SQLITE_OK if this branch
  39750. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  39751. */
  39752. if( !isOpen(pPager->fd) ){
  39753. assert( pPager->tempFile && rc==SQLITE_OK );
  39754. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  39755. }
  39756. /* Before the first write, give the VFS a hint of what the final
  39757. ** file size will be.
  39758. */
  39759. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  39760. if( rc==SQLITE_OK
  39761. && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize
  39762. ){
  39763. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  39764. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  39765. pPager->dbHintSize = pPager->dbSize;
  39766. }
  39767. while( rc==SQLITE_OK && pList ){
  39768. Pgno pgno = pList->pgno;
  39769. /* If there are dirty pages in the page cache with page numbers greater
  39770. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  39771. ** make the file smaller (presumably by auto-vacuum code). Do not write
  39772. ** any such pages to the file.
  39773. **
  39774. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  39775. ** set (set by sqlite3PagerDontWrite()).
  39776. */
  39777. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  39778. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  39779. char *pData; /* Data to write */
  39780. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  39781. if( pList->pgno==1 ) pager_write_changecounter(pList);
  39782. /* Encode the database */
  39783. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  39784. /* Write out the page data. */
  39785. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  39786. /* If page 1 was just written, update Pager.dbFileVers to match
  39787. ** the value now stored in the database file. If writing this
  39788. ** page caused the database file to grow, update dbFileSize.
  39789. */
  39790. if( pgno==1 ){
  39791. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  39792. }
  39793. if( pgno>pPager->dbFileSize ){
  39794. pPager->dbFileSize = pgno;
  39795. }
  39796. pPager->aStat[PAGER_STAT_WRITE]++;
  39797. /* Update any backup objects copying the contents of this pager. */
  39798. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  39799. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  39800. PAGERID(pPager), pgno, pager_pagehash(pList)));
  39801. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  39802. PAGER_INCR(sqlite3_pager_writedb_count);
  39803. }else{
  39804. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  39805. }
  39806. pager_set_pagehash(pList);
  39807. pList = pList->pDirty;
  39808. }
  39809. return rc;
  39810. }
  39811. /*
  39812. ** Ensure that the sub-journal file is open. If it is already open, this
  39813. ** function is a no-op.
  39814. **
  39815. ** SQLITE_OK is returned if everything goes according to plan. An
  39816. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  39817. ** fails.
  39818. */
  39819. static int openSubJournal(Pager *pPager){
  39820. int rc = SQLITE_OK;
  39821. if( !isOpen(pPager->sjfd) ){
  39822. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  39823. sqlite3MemJournalOpen(pPager->sjfd);
  39824. }else{
  39825. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  39826. }
  39827. }
  39828. return rc;
  39829. }
  39830. /*
  39831. ** Append a record of the current state of page pPg to the sub-journal.
  39832. ** It is the callers responsibility to use subjRequiresPage() to check
  39833. ** that it is really required before calling this function.
  39834. **
  39835. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  39836. ** for all open savepoints before returning.
  39837. **
  39838. ** This function returns SQLITE_OK if everything is successful, an IO
  39839. ** error code if the attempt to write to the sub-journal fails, or
  39840. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  39841. ** bitvec.
  39842. */
  39843. static int subjournalPage(PgHdr *pPg){
  39844. int rc = SQLITE_OK;
  39845. Pager *pPager = pPg->pPager;
  39846. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  39847. /* Open the sub-journal, if it has not already been opened */
  39848. assert( pPager->useJournal );
  39849. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  39850. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  39851. assert( pagerUseWal(pPager)
  39852. || pageInJournal(pPg)
  39853. || pPg->pgno>pPager->dbOrigSize
  39854. );
  39855. rc = openSubJournal(pPager);
  39856. /* If the sub-journal was opened successfully (or was already open),
  39857. ** write the journal record into the file. */
  39858. if( rc==SQLITE_OK ){
  39859. void *pData = pPg->pData;
  39860. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  39861. char *pData2;
  39862. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  39863. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  39864. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  39865. if( rc==SQLITE_OK ){
  39866. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  39867. }
  39868. }
  39869. }
  39870. if( rc==SQLITE_OK ){
  39871. pPager->nSubRec++;
  39872. assert( pPager->nSavepoint>0 );
  39873. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  39874. }
  39875. return rc;
  39876. }
  39877. /*
  39878. ** This function is called by the pcache layer when it has reached some
  39879. ** soft memory limit. The first argument is a pointer to a Pager object
  39880. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  39881. ** database). The second argument is a reference to a page that is
  39882. ** currently dirty but has no outstanding references. The page
  39883. ** is always associated with the Pager object passed as the first
  39884. ** argument.
  39885. **
  39886. ** The job of this function is to make pPg clean by writing its contents
  39887. ** out to the database file, if possible. This may involve syncing the
  39888. ** journal file.
  39889. **
  39890. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  39891. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  39892. ** page clean, the IO error code is returned. If the page cannot be
  39893. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  39894. ** is returned by sqlite3PcacheMakeClean() is not called.
  39895. */
  39896. static int pagerStress(void *p, PgHdr *pPg){
  39897. Pager *pPager = (Pager *)p;
  39898. int rc = SQLITE_OK;
  39899. assert( pPg->pPager==pPager );
  39900. assert( pPg->flags&PGHDR_DIRTY );
  39901. /* The doNotSyncSpill flag is set during times when doing a sync of
  39902. ** journal (and adding a new header) is not allowed. This occurs
  39903. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  39904. ** pages belonging to the same sector.
  39905. **
  39906. ** The doNotSpill flag inhibits all cache spilling regardless of whether
  39907. ** or not a sync is required. This is set during a rollback.
  39908. **
  39909. ** Spilling is also prohibited when in an error state since that could
  39910. ** lead to database corruption. In the current implementaton it
  39911. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  39912. ** while in the error state, hence it is impossible for this routine to
  39913. ** be called in the error state. Nevertheless, we include a NEVER()
  39914. ** test for the error state as a safeguard against future changes.
  39915. */
  39916. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  39917. if( pPager->doNotSpill ) return SQLITE_OK;
  39918. if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
  39919. return SQLITE_OK;
  39920. }
  39921. pPg->pDirty = 0;
  39922. if( pagerUseWal(pPager) ){
  39923. /* Write a single frame for this page to the log. */
  39924. if( subjRequiresPage(pPg) ){
  39925. rc = subjournalPage(pPg);
  39926. }
  39927. if( rc==SQLITE_OK ){
  39928. rc = pagerWalFrames(pPager, pPg, 0, 0);
  39929. }
  39930. }else{
  39931. /* Sync the journal file if required. */
  39932. if( pPg->flags&PGHDR_NEED_SYNC
  39933. || pPager->eState==PAGER_WRITER_CACHEMOD
  39934. ){
  39935. rc = syncJournal(pPager, 1);
  39936. }
  39937. /* If the page number of this page is larger than the current size of
  39938. ** the database image, it may need to be written to the sub-journal.
  39939. ** This is because the call to pager_write_pagelist() below will not
  39940. ** actually write data to the file in this case.
  39941. **
  39942. ** Consider the following sequence of events:
  39943. **
  39944. ** BEGIN;
  39945. ** <journal page X>
  39946. ** <modify page X>
  39947. ** SAVEPOINT sp;
  39948. ** <shrink database file to Y pages>
  39949. ** pagerStress(page X)
  39950. ** ROLLBACK TO sp;
  39951. **
  39952. ** If (X>Y), then when pagerStress is called page X will not be written
  39953. ** out to the database file, but will be dropped from the cache. Then,
  39954. ** following the "ROLLBACK TO sp" statement, reading page X will read
  39955. ** data from the database file. This will be the copy of page X as it
  39956. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  39957. ** was executed.
  39958. **
  39959. ** The solution is to write the current data for page X into the
  39960. ** sub-journal file now (if it is not already there), so that it will
  39961. ** be restored to its current value when the "ROLLBACK TO sp" is
  39962. ** executed.
  39963. */
  39964. if( NEVER(
  39965. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  39966. ) ){
  39967. rc = subjournalPage(pPg);
  39968. }
  39969. /* Write the contents of the page out to the database file. */
  39970. if( rc==SQLITE_OK ){
  39971. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  39972. rc = pager_write_pagelist(pPager, pPg);
  39973. }
  39974. }
  39975. /* Mark the page as clean. */
  39976. if( rc==SQLITE_OK ){
  39977. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  39978. sqlite3PcacheMakeClean(pPg);
  39979. }
  39980. return pager_error(pPager, rc);
  39981. }
  39982. /*
  39983. ** Allocate and initialize a new Pager object and put a pointer to it
  39984. ** in *ppPager. The pager should eventually be freed by passing it
  39985. ** to sqlite3PagerClose().
  39986. **
  39987. ** The zFilename argument is the path to the database file to open.
  39988. ** If zFilename is NULL then a randomly-named temporary file is created
  39989. ** and used as the file to be cached. Temporary files are be deleted
  39990. ** automatically when they are closed. If zFilename is ":memory:" then
  39991. ** all information is held in cache. It is never written to disk.
  39992. ** This can be used to implement an in-memory database.
  39993. **
  39994. ** The nExtra parameter specifies the number of bytes of space allocated
  39995. ** along with each page reference. This space is available to the user
  39996. ** via the sqlite3PagerGetExtra() API.
  39997. **
  39998. ** The flags argument is used to specify properties that affect the
  39999. ** operation of the pager. It should be passed some bitwise combination
  40000. ** of the PAGER_* flags.
  40001. **
  40002. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  40003. ** of the xOpen() method of the supplied VFS when opening files.
  40004. **
  40005. ** If the pager object is allocated and the specified file opened
  40006. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  40007. ** the new pager object. If an error occurs, *ppPager is set to NULL
  40008. ** and error code returned. This function may return SQLITE_NOMEM
  40009. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  40010. ** various SQLITE_IO_XXX errors.
  40011. */
  40012. SQLITE_PRIVATE int sqlite3PagerOpen(
  40013. sqlite3_vfs *pVfs, /* The virtual file system to use */
  40014. Pager **ppPager, /* OUT: Return the Pager structure here */
  40015. const char *zFilename, /* Name of the database file to open */
  40016. int nExtra, /* Extra bytes append to each in-memory page */
  40017. int flags, /* flags controlling this file */
  40018. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  40019. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  40020. ){
  40021. u8 *pPtr;
  40022. Pager *pPager = 0; /* Pager object to allocate and return */
  40023. int rc = SQLITE_OK; /* Return code */
  40024. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  40025. int memDb = 0; /* True if this is an in-memory file */
  40026. int readOnly = 0; /* True if this is a read-only file */
  40027. int journalFileSize; /* Bytes to allocate for each journal fd */
  40028. char *zPathname = 0; /* Full path to database file */
  40029. int nPathname = 0; /* Number of bytes in zPathname */
  40030. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  40031. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  40032. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  40033. const char *zUri = 0; /* URI args to copy */
  40034. int nUri = 0; /* Number of bytes of URI args at *zUri */
  40035. /* Figure out how much space is required for each journal file-handle
  40036. ** (there are two of them, the main journal and the sub-journal). This
  40037. ** is the maximum space required for an in-memory journal file handle
  40038. ** and a regular journal file-handle. Note that a "regular journal-handle"
  40039. ** may be a wrapper capable of caching the first portion of the journal
  40040. ** file in memory to implement the atomic-write optimization (see
  40041. ** source file journal.c).
  40042. */
  40043. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  40044. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  40045. }else{
  40046. journalFileSize = ROUND8(sqlite3MemJournalSize());
  40047. }
  40048. /* Set the output variable to NULL in case an error occurs. */
  40049. *ppPager = 0;
  40050. #ifndef SQLITE_OMIT_MEMORYDB
  40051. if( flags & PAGER_MEMORY ){
  40052. memDb = 1;
  40053. if( zFilename && zFilename[0] ){
  40054. zPathname = sqlite3DbStrDup(0, zFilename);
  40055. if( zPathname==0 ) return SQLITE_NOMEM;
  40056. nPathname = sqlite3Strlen30(zPathname);
  40057. zFilename = 0;
  40058. }
  40059. }
  40060. #endif
  40061. /* Compute and store the full pathname in an allocated buffer pointed
  40062. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  40063. ** leave both nPathname and zPathname set to 0.
  40064. */
  40065. if( zFilename && zFilename[0] ){
  40066. const char *z;
  40067. nPathname = pVfs->mxPathname+1;
  40068. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  40069. if( zPathname==0 ){
  40070. return SQLITE_NOMEM;
  40071. }
  40072. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  40073. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  40074. nPathname = sqlite3Strlen30(zPathname);
  40075. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  40076. while( *z ){
  40077. z += sqlite3Strlen30(z)+1;
  40078. z += sqlite3Strlen30(z)+1;
  40079. }
  40080. nUri = (int)(&z[1] - zUri);
  40081. assert( nUri>=0 );
  40082. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  40083. /* This branch is taken when the journal path required by
  40084. ** the database being opened will be more than pVfs->mxPathname
  40085. ** bytes in length. This means the database cannot be opened,
  40086. ** as it will not be possible to open the journal file or even
  40087. ** check for a hot-journal before reading.
  40088. */
  40089. rc = SQLITE_CANTOPEN_BKPT;
  40090. }
  40091. if( rc!=SQLITE_OK ){
  40092. sqlite3DbFree(0, zPathname);
  40093. return rc;
  40094. }
  40095. }
  40096. /* Allocate memory for the Pager structure, PCache object, the
  40097. ** three file descriptors, the database file name and the journal
  40098. ** file name. The layout in memory is as follows:
  40099. **
  40100. ** Pager object (sizeof(Pager) bytes)
  40101. ** PCache object (sqlite3PcacheSize() bytes)
  40102. ** Database file handle (pVfs->szOsFile bytes)
  40103. ** Sub-journal file handle (journalFileSize bytes)
  40104. ** Main journal file handle (journalFileSize bytes)
  40105. ** Database file name (nPathname+1 bytes)
  40106. ** Journal file name (nPathname+8+1 bytes)
  40107. */
  40108. pPtr = (u8 *)sqlite3MallocZero(
  40109. ROUND8(sizeof(*pPager)) + /* Pager structure */
  40110. ROUND8(pcacheSize) + /* PCache object */
  40111. ROUND8(pVfs->szOsFile) + /* The main db file */
  40112. journalFileSize * 2 + /* The two journal files */
  40113. nPathname + 1 + nUri + /* zFilename */
  40114. nPathname + 8 + 2 /* zJournal */
  40115. #ifndef SQLITE_OMIT_WAL
  40116. + nPathname + 4 + 2 /* zWal */
  40117. #endif
  40118. );
  40119. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  40120. if( !pPtr ){
  40121. sqlite3DbFree(0, zPathname);
  40122. return SQLITE_NOMEM;
  40123. }
  40124. pPager = (Pager*)(pPtr);
  40125. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  40126. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  40127. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  40128. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  40129. pPager->zFilename = (char*)(pPtr += journalFileSize);
  40130. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  40131. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  40132. if( zPathname ){
  40133. assert( nPathname>0 );
  40134. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  40135. memcpy(pPager->zFilename, zPathname, nPathname);
  40136. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  40137. memcpy(pPager->zJournal, zPathname, nPathname);
  40138. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  40139. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  40140. #ifndef SQLITE_OMIT_WAL
  40141. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  40142. memcpy(pPager->zWal, zPathname, nPathname);
  40143. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  40144. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  40145. #endif
  40146. sqlite3DbFree(0, zPathname);
  40147. }
  40148. pPager->pVfs = pVfs;
  40149. pPager->vfsFlags = vfsFlags;
  40150. /* Open the pager file.
  40151. */
  40152. if( zFilename && zFilename[0] ){
  40153. int fout = 0; /* VFS flags returned by xOpen() */
  40154. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  40155. assert( !memDb );
  40156. readOnly = (fout&SQLITE_OPEN_READONLY);
  40157. /* If the file was successfully opened for read/write access,
  40158. ** choose a default page size in case we have to create the
  40159. ** database file. The default page size is the maximum of:
  40160. **
  40161. ** + SQLITE_DEFAULT_PAGE_SIZE,
  40162. ** + The value returned by sqlite3OsSectorSize()
  40163. ** + The largest page size that can be written atomically.
  40164. */
  40165. if( rc==SQLITE_OK && !readOnly ){
  40166. setSectorSize(pPager);
  40167. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  40168. if( szPageDflt<pPager->sectorSize ){
  40169. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  40170. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  40171. }else{
  40172. szPageDflt = (u32)pPager->sectorSize;
  40173. }
  40174. }
  40175. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40176. {
  40177. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40178. int ii;
  40179. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40180. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40181. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  40182. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  40183. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  40184. szPageDflt = ii;
  40185. }
  40186. }
  40187. }
  40188. #endif
  40189. }
  40190. }else{
  40191. /* If a temporary file is requested, it is not opened immediately.
  40192. ** In this case we accept the default page size and delay actually
  40193. ** opening the file until the first call to OsWrite().
  40194. **
  40195. ** This branch is also run for an in-memory database. An in-memory
  40196. ** database is the same as a temp-file that is never written out to
  40197. ** disk and uses an in-memory rollback journal.
  40198. */
  40199. tempFile = 1;
  40200. pPager->eState = PAGER_READER;
  40201. pPager->eLock = EXCLUSIVE_LOCK;
  40202. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  40203. }
  40204. /* The following call to PagerSetPagesize() serves to set the value of
  40205. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  40206. */
  40207. if( rc==SQLITE_OK ){
  40208. assert( pPager->memDb==0 );
  40209. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  40210. testcase( rc!=SQLITE_OK );
  40211. }
  40212. /* If an error occurred in either of the blocks above, free the
  40213. ** Pager structure and close the file.
  40214. */
  40215. if( rc!=SQLITE_OK ){
  40216. assert( !pPager->pTmpSpace );
  40217. sqlite3OsClose(pPager->fd);
  40218. sqlite3_free(pPager);
  40219. return rc;
  40220. }
  40221. /* Initialize the PCache object. */
  40222. assert( nExtra<1000 );
  40223. nExtra = ROUND8(nExtra);
  40224. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  40225. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  40226. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  40227. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  40228. pPager->useJournal = (u8)useJournal;
  40229. /* pPager->stmtOpen = 0; */
  40230. /* pPager->stmtInUse = 0; */
  40231. /* pPager->nRef = 0; */
  40232. /* pPager->stmtSize = 0; */
  40233. /* pPager->stmtJSize = 0; */
  40234. /* pPager->nPage = 0; */
  40235. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  40236. /* pPager->state = PAGER_UNLOCK; */
  40237. #if 0
  40238. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  40239. #endif
  40240. /* pPager->errMask = 0; */
  40241. pPager->tempFile = (u8)tempFile;
  40242. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  40243. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  40244. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  40245. pPager->exclusiveMode = (u8)tempFile;
  40246. pPager->changeCountDone = pPager->tempFile;
  40247. pPager->memDb = (u8)memDb;
  40248. pPager->readOnly = (u8)readOnly;
  40249. assert( useJournal || pPager->tempFile );
  40250. pPager->noSync = pPager->tempFile;
  40251. if( pPager->noSync ){
  40252. assert( pPager->fullSync==0 );
  40253. assert( pPager->syncFlags==0 );
  40254. assert( pPager->walSyncFlags==0 );
  40255. assert( pPager->ckptSyncFlags==0 );
  40256. }else{
  40257. pPager->fullSync = 1;
  40258. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  40259. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  40260. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  40261. }
  40262. /* pPager->pFirst = 0; */
  40263. /* pPager->pFirstSynced = 0; */
  40264. /* pPager->pLast = 0; */
  40265. pPager->nExtra = (u16)nExtra;
  40266. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  40267. assert( isOpen(pPager->fd) || tempFile );
  40268. setSectorSize(pPager);
  40269. if( !useJournal ){
  40270. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  40271. }else if( memDb ){
  40272. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  40273. }
  40274. /* pPager->xBusyHandler = 0; */
  40275. /* pPager->pBusyHandlerArg = 0; */
  40276. pPager->xReiniter = xReinit;
  40277. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  40278. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  40279. *ppPager = pPager;
  40280. return SQLITE_OK;
  40281. }
  40282. /*
  40283. ** This function is called after transitioning from PAGER_UNLOCK to
  40284. ** PAGER_SHARED state. It tests if there is a hot journal present in
  40285. ** the file-system for the given pager. A hot journal is one that
  40286. ** needs to be played back. According to this function, a hot-journal
  40287. ** file exists if the following criteria are met:
  40288. **
  40289. ** * The journal file exists in the file system, and
  40290. ** * No process holds a RESERVED or greater lock on the database file, and
  40291. ** * The database file itself is greater than 0 bytes in size, and
  40292. ** * The first byte of the journal file exists and is not 0x00.
  40293. **
  40294. ** If the current size of the database file is 0 but a journal file
  40295. ** exists, that is probably an old journal left over from a prior
  40296. ** database with the same name. In this case the journal file is
  40297. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  40298. ** is returned.
  40299. **
  40300. ** This routine does not check if there is a master journal filename
  40301. ** at the end of the file. If there is, and that master journal file
  40302. ** does not exist, then the journal file is not really hot. In this
  40303. ** case this routine will return a false-positive. The pager_playback()
  40304. ** routine will discover that the journal file is not really hot and
  40305. ** will not roll it back.
  40306. **
  40307. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  40308. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  40309. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  40310. ** to determine whether or not a hot-journal file exists, the IO error
  40311. ** code is returned and the value of *pExists is undefined.
  40312. */
  40313. static int hasHotJournal(Pager *pPager, int *pExists){
  40314. sqlite3_vfs * const pVfs = pPager->pVfs;
  40315. int rc = SQLITE_OK; /* Return code */
  40316. int exists = 1; /* True if a journal file is present */
  40317. int jrnlOpen = !!isOpen(pPager->jfd);
  40318. assert( pPager->useJournal );
  40319. assert( isOpen(pPager->fd) );
  40320. assert( pPager->eState==PAGER_OPEN );
  40321. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  40322. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  40323. ));
  40324. *pExists = 0;
  40325. if( !jrnlOpen ){
  40326. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  40327. }
  40328. if( rc==SQLITE_OK && exists ){
  40329. int locked = 0; /* True if some process holds a RESERVED lock */
  40330. /* Race condition here: Another process might have been holding the
  40331. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  40332. ** call above, but then delete the journal and drop the lock before
  40333. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  40334. ** is the case, this routine might think there is a hot journal when
  40335. ** in fact there is none. This results in a false-positive which will
  40336. ** be dealt with by the playback routine. Ticket #3883.
  40337. */
  40338. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  40339. if( rc==SQLITE_OK && !locked ){
  40340. Pgno nPage; /* Number of pages in database file */
  40341. /* Check the size of the database file. If it consists of 0 pages,
  40342. ** then delete the journal file. See the header comment above for
  40343. ** the reasoning here. Delete the obsolete journal file under
  40344. ** a RESERVED lock to avoid race conditions and to avoid violating
  40345. ** [H33020].
  40346. */
  40347. rc = pagerPagecount(pPager, &nPage);
  40348. if( rc==SQLITE_OK ){
  40349. if( nPage==0 ){
  40350. sqlite3BeginBenignMalloc();
  40351. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  40352. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  40353. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  40354. }
  40355. sqlite3EndBenignMalloc();
  40356. }else{
  40357. /* The journal file exists and no other connection has a reserved
  40358. ** or greater lock on the database file. Now check that there is
  40359. ** at least one non-zero bytes at the start of the journal file.
  40360. ** If there is, then we consider this journal to be hot. If not,
  40361. ** it can be ignored.
  40362. */
  40363. if( !jrnlOpen ){
  40364. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  40365. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  40366. }
  40367. if( rc==SQLITE_OK ){
  40368. u8 first = 0;
  40369. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  40370. if( rc==SQLITE_IOERR_SHORT_READ ){
  40371. rc = SQLITE_OK;
  40372. }
  40373. if( !jrnlOpen ){
  40374. sqlite3OsClose(pPager->jfd);
  40375. }
  40376. *pExists = (first!=0);
  40377. }else if( rc==SQLITE_CANTOPEN ){
  40378. /* If we cannot open the rollback journal file in order to see if
  40379. ** its has a zero header, that might be due to an I/O error, or
  40380. ** it might be due to the race condition described above and in
  40381. ** ticket #3883. Either way, assume that the journal is hot.
  40382. ** This might be a false positive. But if it is, then the
  40383. ** automatic journal playback and recovery mechanism will deal
  40384. ** with it under an EXCLUSIVE lock where we do not need to
  40385. ** worry so much with race conditions.
  40386. */
  40387. *pExists = 1;
  40388. rc = SQLITE_OK;
  40389. }
  40390. }
  40391. }
  40392. }
  40393. }
  40394. return rc;
  40395. }
  40396. /*
  40397. ** This function is called to obtain a shared lock on the database file.
  40398. ** It is illegal to call sqlite3PagerAcquire() until after this function
  40399. ** has been successfully called. If a shared-lock is already held when
  40400. ** this function is called, it is a no-op.
  40401. **
  40402. ** The following operations are also performed by this function.
  40403. **
  40404. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  40405. ** on the database file), then an attempt is made to obtain a
  40406. ** SHARED lock on the database file. Immediately after obtaining
  40407. ** the SHARED lock, the file-system is checked for a hot-journal,
  40408. ** which is played back if present. Following any hot-journal
  40409. ** rollback, the contents of the cache are validated by checking
  40410. ** the 'change-counter' field of the database file header and
  40411. ** discarded if they are found to be invalid.
  40412. **
  40413. ** 2) If the pager is running in exclusive-mode, and there are currently
  40414. ** no outstanding references to any pages, and is in the error state,
  40415. ** then an attempt is made to clear the error state by discarding
  40416. ** the contents of the page cache and rolling back any open journal
  40417. ** file.
  40418. **
  40419. ** If everything is successful, SQLITE_OK is returned. If an IO error
  40420. ** occurs while locking the database, checking for a hot-journal file or
  40421. ** rolling back a journal file, the IO error code is returned.
  40422. */
  40423. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  40424. int rc = SQLITE_OK; /* Return code */
  40425. /* This routine is only called from b-tree and only when there are no
  40426. ** outstanding pages. This implies that the pager state should either
  40427. ** be OPEN or READER. READER is only possible if the pager is or was in
  40428. ** exclusive access mode.
  40429. */
  40430. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  40431. assert( assert_pager_state(pPager) );
  40432. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  40433. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  40434. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  40435. int bHotJournal = 1; /* True if there exists a hot journal-file */
  40436. assert( !MEMDB );
  40437. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  40438. if( rc!=SQLITE_OK ){
  40439. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  40440. goto failed;
  40441. }
  40442. /* If a journal file exists, and there is no RESERVED lock on the
  40443. ** database file, then it either needs to be played back or deleted.
  40444. */
  40445. if( pPager->eLock<=SHARED_LOCK ){
  40446. rc = hasHotJournal(pPager, &bHotJournal);
  40447. }
  40448. if( rc!=SQLITE_OK ){
  40449. goto failed;
  40450. }
  40451. if( bHotJournal ){
  40452. if( pPager->readOnly ){
  40453. rc = SQLITE_READONLY_ROLLBACK;
  40454. goto failed;
  40455. }
  40456. /* Get an EXCLUSIVE lock on the database file. At this point it is
  40457. ** important that a RESERVED lock is not obtained on the way to the
  40458. ** EXCLUSIVE lock. If it were, another process might open the
  40459. ** database file, detect the RESERVED lock, and conclude that the
  40460. ** database is safe to read while this process is still rolling the
  40461. ** hot-journal back.
  40462. **
  40463. ** Because the intermediate RESERVED lock is not requested, any
  40464. ** other process attempting to access the database file will get to
  40465. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  40466. ** on the database file.
  40467. **
  40468. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  40469. ** downgraded to SHARED_LOCK before this function returns.
  40470. */
  40471. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  40472. if( rc!=SQLITE_OK ){
  40473. goto failed;
  40474. }
  40475. /* If it is not already open and the file exists on disk, open the
  40476. ** journal for read/write access. Write access is required because
  40477. ** in exclusive-access mode the file descriptor will be kept open
  40478. ** and possibly used for a transaction later on. Also, write-access
  40479. ** is usually required to finalize the journal in journal_mode=persist
  40480. ** mode (and also for journal_mode=truncate on some systems).
  40481. **
  40482. ** If the journal does not exist, it usually means that some
  40483. ** other connection managed to get in and roll it back before
  40484. ** this connection obtained the exclusive lock above. Or, it
  40485. ** may mean that the pager was in the error-state when this
  40486. ** function was called and the journal file does not exist.
  40487. */
  40488. if( !isOpen(pPager->jfd) ){
  40489. sqlite3_vfs * const pVfs = pPager->pVfs;
  40490. int bExists; /* True if journal file exists */
  40491. rc = sqlite3OsAccess(
  40492. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  40493. if( rc==SQLITE_OK && bExists ){
  40494. int fout = 0;
  40495. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  40496. assert( !pPager->tempFile );
  40497. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  40498. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  40499. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  40500. rc = SQLITE_CANTOPEN_BKPT;
  40501. sqlite3OsClose(pPager->jfd);
  40502. }
  40503. }
  40504. }
  40505. /* Playback and delete the journal. Drop the database write
  40506. ** lock and reacquire the read lock. Purge the cache before
  40507. ** playing back the hot-journal so that we don't end up with
  40508. ** an inconsistent cache. Sync the hot journal before playing
  40509. ** it back since the process that crashed and left the hot journal
  40510. ** probably did not sync it and we are required to always sync
  40511. ** the journal before playing it back.
  40512. */
  40513. if( isOpen(pPager->jfd) ){
  40514. assert( rc==SQLITE_OK );
  40515. rc = pagerSyncHotJournal(pPager);
  40516. if( rc==SQLITE_OK ){
  40517. rc = pager_playback(pPager, 1);
  40518. pPager->eState = PAGER_OPEN;
  40519. }
  40520. }else if( !pPager->exclusiveMode ){
  40521. pagerUnlockDb(pPager, SHARED_LOCK);
  40522. }
  40523. if( rc!=SQLITE_OK ){
  40524. /* This branch is taken if an error occurs while trying to open
  40525. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  40526. ** pager_unlock() routine will be called before returning to unlock
  40527. ** the file. If the unlock attempt fails, then Pager.eLock must be
  40528. ** set to UNKNOWN_LOCK (see the comment above the #define for
  40529. ** UNKNOWN_LOCK above for an explanation).
  40530. **
  40531. ** In order to get pager_unlock() to do this, set Pager.eState to
  40532. ** PAGER_ERROR now. This is not actually counted as a transition
  40533. ** to ERROR state in the state diagram at the top of this file,
  40534. ** since we know that the same call to pager_unlock() will very
  40535. ** shortly transition the pager object to the OPEN state. Calling
  40536. ** assert_pager_state() would fail now, as it should not be possible
  40537. ** to be in ERROR state when there are zero outstanding page
  40538. ** references.
  40539. */
  40540. pager_error(pPager, rc);
  40541. goto failed;
  40542. }
  40543. assert( pPager->eState==PAGER_OPEN );
  40544. assert( (pPager->eLock==SHARED_LOCK)
  40545. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  40546. );
  40547. }
  40548. if( !pPager->tempFile && (
  40549. pPager->pBackup
  40550. || sqlite3PcachePagecount(pPager->pPCache)>0
  40551. || USEFETCH(pPager)
  40552. )){
  40553. /* The shared-lock has just been acquired on the database file
  40554. ** and there are already pages in the cache (from a previous
  40555. ** read or write transaction). Check to see if the database
  40556. ** has been modified. If the database has changed, flush the
  40557. ** cache.
  40558. **
  40559. ** Database changes is detected by looking at 15 bytes beginning
  40560. ** at offset 24 into the file. The first 4 of these 16 bytes are
  40561. ** a 32-bit counter that is incremented with each change. The
  40562. ** other bytes change randomly with each file change when
  40563. ** a codec is in use.
  40564. **
  40565. ** There is a vanishingly small chance that a change will not be
  40566. ** detected. The chance of an undetected change is so small that
  40567. ** it can be neglected.
  40568. */
  40569. Pgno nPage = 0;
  40570. char dbFileVers[sizeof(pPager->dbFileVers)];
  40571. rc = pagerPagecount(pPager, &nPage);
  40572. if( rc ) goto failed;
  40573. if( nPage>0 ){
  40574. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  40575. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  40576. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  40577. goto failed;
  40578. }
  40579. }else{
  40580. memset(dbFileVers, 0, sizeof(dbFileVers));
  40581. }
  40582. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  40583. pager_reset(pPager);
  40584. /* Unmap the database file. It is possible that external processes
  40585. ** may have truncated the database file and then extended it back
  40586. ** to its original size while this process was not holding a lock.
  40587. ** In this case there may exist a Pager.pMap mapping that appears
  40588. ** to be the right size but is not actually valid. Avoid this
  40589. ** possibility by unmapping the db here. */
  40590. if( USEFETCH(pPager) ){
  40591. sqlite3OsUnfetch(pPager->fd, 0, 0);
  40592. }
  40593. }
  40594. }
  40595. /* If there is a WAL file in the file-system, open this database in WAL
  40596. ** mode. Otherwise, the following function call is a no-op.
  40597. */
  40598. rc = pagerOpenWalIfPresent(pPager);
  40599. #ifndef SQLITE_OMIT_WAL
  40600. assert( pPager->pWal==0 || rc==SQLITE_OK );
  40601. #endif
  40602. }
  40603. if( pagerUseWal(pPager) ){
  40604. assert( rc==SQLITE_OK );
  40605. rc = pagerBeginReadTransaction(pPager);
  40606. }
  40607. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  40608. rc = pagerPagecount(pPager, &pPager->dbSize);
  40609. }
  40610. failed:
  40611. if( rc!=SQLITE_OK ){
  40612. assert( !MEMDB );
  40613. pager_unlock(pPager);
  40614. assert( pPager->eState==PAGER_OPEN );
  40615. }else{
  40616. pPager->eState = PAGER_READER;
  40617. }
  40618. return rc;
  40619. }
  40620. /*
  40621. ** If the reference count has reached zero, rollback any active
  40622. ** transaction and unlock the pager.
  40623. **
  40624. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  40625. ** the rollback journal, the unlock is not performed and there is
  40626. ** nothing to rollback, so this routine is a no-op.
  40627. */
  40628. static void pagerUnlockIfUnused(Pager *pPager){
  40629. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  40630. pagerUnlockAndRollback(pPager);
  40631. }
  40632. }
  40633. /*
  40634. ** Acquire a reference to page number pgno in pager pPager (a page
  40635. ** reference has type DbPage*). If the requested reference is
  40636. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  40637. **
  40638. ** If the requested page is already in the cache, it is returned.
  40639. ** Otherwise, a new page object is allocated and populated with data
  40640. ** read from the database file. In some cases, the pcache module may
  40641. ** choose not to allocate a new page object and may reuse an existing
  40642. ** object with no outstanding references.
  40643. **
  40644. ** The extra data appended to a page is always initialized to zeros the
  40645. ** first time a page is loaded into memory. If the page requested is
  40646. ** already in the cache when this function is called, then the extra
  40647. ** data is left as it was when the page object was last used.
  40648. **
  40649. ** If the database image is smaller than the requested page or if a
  40650. ** non-zero value is passed as the noContent parameter and the
  40651. ** requested page is not already stored in the cache, then no
  40652. ** actual disk read occurs. In this case the memory image of the
  40653. ** page is initialized to all zeros.
  40654. **
  40655. ** If noContent is true, it means that we do not care about the contents
  40656. ** of the page. This occurs in two seperate scenarios:
  40657. **
  40658. ** a) When reading a free-list leaf page from the database, and
  40659. **
  40660. ** b) When a savepoint is being rolled back and we need to load
  40661. ** a new page into the cache to be filled with the data read
  40662. ** from the savepoint journal.
  40663. **
  40664. ** If noContent is true, then the data returned is zeroed instead of
  40665. ** being read from the database. Additionally, the bits corresponding
  40666. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  40667. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  40668. ** savepoints are set. This means if the page is made writable at any
  40669. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  40670. ** will not be journaled. This saves IO.
  40671. **
  40672. ** The acquisition might fail for several reasons. In all cases,
  40673. ** an appropriate error code is returned and *ppPage is set to NULL.
  40674. **
  40675. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  40676. ** to find a page in the in-memory cache first. If the page is not already
  40677. ** in memory, this routine goes to disk to read it in whereas Lookup()
  40678. ** just returns 0. This routine acquires a read-lock the first time it
  40679. ** has to go to disk, and could also playback an old journal if necessary.
  40680. ** Since Lookup() never goes to disk, it never has to deal with locks
  40681. ** or journal files.
  40682. */
  40683. SQLITE_PRIVATE int sqlite3PagerAcquire(
  40684. Pager *pPager, /* The pager open on the database file */
  40685. Pgno pgno, /* Page number to fetch */
  40686. DbPage **ppPage, /* Write a pointer to the page here */
  40687. int flags /* PAGER_ACQUIRE_XXX flags */
  40688. ){
  40689. int rc = SQLITE_OK;
  40690. PgHdr *pPg = 0;
  40691. u32 iFrame = 0; /* Frame to read from WAL file */
  40692. const int noContent = (flags & PAGER_ACQUIRE_NOCONTENT);
  40693. /* It is acceptable to use a read-only (mmap) page for any page except
  40694. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  40695. ** flag was specified by the caller. And so long as the db is not a
  40696. ** temporary or in-memory database. */
  40697. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  40698. && (pPager->eState==PAGER_READER || (flags & PAGER_ACQUIRE_READONLY))
  40699. #ifdef SQLITE_HAS_CODEC
  40700. && pPager->xCodec==0
  40701. #endif
  40702. );
  40703. assert( pPager->eState>=PAGER_READER );
  40704. assert( assert_pager_state(pPager) );
  40705. assert( noContent==0 || bMmapOk==0 );
  40706. if( pgno==0 ){
  40707. return SQLITE_CORRUPT_BKPT;
  40708. }
  40709. /* If the pager is in the error state, return an error immediately.
  40710. ** Otherwise, request the page from the PCache layer. */
  40711. if( pPager->errCode!=SQLITE_OK ){
  40712. rc = pPager->errCode;
  40713. }else{
  40714. if( bMmapOk && pagerUseWal(pPager) ){
  40715. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  40716. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  40717. }
  40718. if( iFrame==0 && bMmapOk ){
  40719. void *pData = 0;
  40720. rc = sqlite3OsFetch(pPager->fd,
  40721. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  40722. );
  40723. if( rc==SQLITE_OK && pData ){
  40724. if( pPager->eState>PAGER_READER ){
  40725. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  40726. }
  40727. if( pPg==0 ){
  40728. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  40729. }else{
  40730. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  40731. }
  40732. if( pPg ){
  40733. assert( rc==SQLITE_OK );
  40734. *ppPage = pPg;
  40735. return SQLITE_OK;
  40736. }
  40737. }
  40738. if( rc!=SQLITE_OK ){
  40739. goto pager_acquire_err;
  40740. }
  40741. }
  40742. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  40743. }
  40744. if( rc!=SQLITE_OK ){
  40745. /* Either the call to sqlite3PcacheFetch() returned an error or the
  40746. ** pager was already in the error-state when this function was called.
  40747. ** Set pPg to 0 and jump to the exception handler. */
  40748. pPg = 0;
  40749. goto pager_acquire_err;
  40750. }
  40751. assert( (*ppPage)->pgno==pgno );
  40752. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  40753. if( (*ppPage)->pPager && !noContent ){
  40754. /* In this case the pcache already contains an initialized copy of
  40755. ** the page. Return without further ado. */
  40756. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  40757. pPager->aStat[PAGER_STAT_HIT]++;
  40758. return SQLITE_OK;
  40759. }else{
  40760. /* The pager cache has created a new page. Its content needs to
  40761. ** be initialized. */
  40762. pPg = *ppPage;
  40763. pPg->pPager = pPager;
  40764. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  40765. ** number greater than this, or the unused locking-page, is requested. */
  40766. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  40767. rc = SQLITE_CORRUPT_BKPT;
  40768. goto pager_acquire_err;
  40769. }
  40770. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  40771. if( pgno>pPager->mxPgno ){
  40772. rc = SQLITE_FULL;
  40773. goto pager_acquire_err;
  40774. }
  40775. if( noContent ){
  40776. /* Failure to set the bits in the InJournal bit-vectors is benign.
  40777. ** It merely means that we might do some extra work to journal a
  40778. ** page that does not need to be journaled. Nevertheless, be sure
  40779. ** to test the case where a malloc error occurs while trying to set
  40780. ** a bit in a bit vector.
  40781. */
  40782. sqlite3BeginBenignMalloc();
  40783. if( pgno<=pPager->dbOrigSize ){
  40784. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  40785. testcase( rc==SQLITE_NOMEM );
  40786. }
  40787. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  40788. testcase( rc==SQLITE_NOMEM );
  40789. sqlite3EndBenignMalloc();
  40790. }
  40791. memset(pPg->pData, 0, pPager->pageSize);
  40792. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  40793. }else{
  40794. if( pagerUseWal(pPager) && bMmapOk==0 ){
  40795. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  40796. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  40797. }
  40798. assert( pPg->pPager==pPager );
  40799. pPager->aStat[PAGER_STAT_MISS]++;
  40800. rc = readDbPage(pPg, iFrame);
  40801. if( rc!=SQLITE_OK ){
  40802. goto pager_acquire_err;
  40803. }
  40804. }
  40805. pager_set_pagehash(pPg);
  40806. }
  40807. return SQLITE_OK;
  40808. pager_acquire_err:
  40809. assert( rc!=SQLITE_OK );
  40810. if( pPg ){
  40811. sqlite3PcacheDrop(pPg);
  40812. }
  40813. pagerUnlockIfUnused(pPager);
  40814. *ppPage = 0;
  40815. return rc;
  40816. }
  40817. /*
  40818. ** Acquire a page if it is already in the in-memory cache. Do
  40819. ** not read the page from disk. Return a pointer to the page,
  40820. ** or 0 if the page is not in cache.
  40821. **
  40822. ** See also sqlite3PagerGet(). The difference between this routine
  40823. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  40824. ** in the page if the page is not already in cache. This routine
  40825. ** returns NULL if the page is not in cache or if a disk I/O error
  40826. ** has ever happened.
  40827. */
  40828. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  40829. PgHdr *pPg = 0;
  40830. assert( pPager!=0 );
  40831. assert( pgno!=0 );
  40832. assert( pPager->pPCache!=0 );
  40833. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  40834. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  40835. return pPg;
  40836. }
  40837. /*
  40838. ** Release a page reference.
  40839. **
  40840. ** If the number of references to the page drop to zero, then the
  40841. ** page is added to the LRU list. When all references to all pages
  40842. ** are released, a rollback occurs and the lock on the database is
  40843. ** removed.
  40844. */
  40845. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  40846. if( pPg ){
  40847. Pager *pPager = pPg->pPager;
  40848. if( pPg->flags & PGHDR_MMAP ){
  40849. pagerReleaseMapPage(pPg);
  40850. }else{
  40851. sqlite3PcacheRelease(pPg);
  40852. }
  40853. pagerUnlockIfUnused(pPager);
  40854. }
  40855. }
  40856. /*
  40857. ** This function is called at the start of every write transaction.
  40858. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  40859. ** file when this routine is called.
  40860. **
  40861. ** Open the journal file for pager pPager and write a journal header
  40862. ** to the start of it. If there are active savepoints, open the sub-journal
  40863. ** as well. This function is only used when the journal file is being
  40864. ** opened to write a rollback log for a transaction. It is not used
  40865. ** when opening a hot journal file to roll it back.
  40866. **
  40867. ** If the journal file is already open (as it may be in exclusive mode),
  40868. ** then this function just writes a journal header to the start of the
  40869. ** already open file.
  40870. **
  40871. ** Whether or not the journal file is opened by this function, the
  40872. ** Pager.pInJournal bitvec structure is allocated.
  40873. **
  40874. ** Return SQLITE_OK if everything is successful. Otherwise, return
  40875. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  40876. ** an IO error code if opening or writing the journal file fails.
  40877. */
  40878. static int pager_open_journal(Pager *pPager){
  40879. int rc = SQLITE_OK; /* Return code */
  40880. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  40881. assert( pPager->eState==PAGER_WRITER_LOCKED );
  40882. assert( assert_pager_state(pPager) );
  40883. assert( pPager->pInJournal==0 );
  40884. /* If already in the error state, this function is a no-op. But on
  40885. ** the other hand, this routine is never called if we are already in
  40886. ** an error state. */
  40887. if( NEVER(pPager->errCode) ) return pPager->errCode;
  40888. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  40889. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  40890. if( pPager->pInJournal==0 ){
  40891. return SQLITE_NOMEM;
  40892. }
  40893. /* Open the journal file if it is not already open. */
  40894. if( !isOpen(pPager->jfd) ){
  40895. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  40896. sqlite3MemJournalOpen(pPager->jfd);
  40897. }else{
  40898. const int flags = /* VFS flags to open journal file */
  40899. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  40900. (pPager->tempFile ?
  40901. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  40902. (SQLITE_OPEN_MAIN_JOURNAL)
  40903. );
  40904. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40905. rc = sqlite3JournalOpen(
  40906. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  40907. );
  40908. #else
  40909. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  40910. #endif
  40911. }
  40912. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  40913. }
  40914. /* Write the first journal header to the journal file and open
  40915. ** the sub-journal if necessary.
  40916. */
  40917. if( rc==SQLITE_OK ){
  40918. /* TODO: Check if all of these are really required. */
  40919. pPager->nRec = 0;
  40920. pPager->journalOff = 0;
  40921. pPager->setMaster = 0;
  40922. pPager->journalHdr = 0;
  40923. rc = writeJournalHdr(pPager);
  40924. }
  40925. }
  40926. if( rc!=SQLITE_OK ){
  40927. sqlite3BitvecDestroy(pPager->pInJournal);
  40928. pPager->pInJournal = 0;
  40929. }else{
  40930. assert( pPager->eState==PAGER_WRITER_LOCKED );
  40931. pPager->eState = PAGER_WRITER_CACHEMOD;
  40932. }
  40933. return rc;
  40934. }
  40935. /*
  40936. ** Begin a write-transaction on the specified pager object. If a
  40937. ** write-transaction has already been opened, this function is a no-op.
  40938. **
  40939. ** If the exFlag argument is false, then acquire at least a RESERVED
  40940. ** lock on the database file. If exFlag is true, then acquire at least
  40941. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  40942. ** functions need be called.
  40943. **
  40944. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  40945. ** within this transaction will be opened as an in-memory file. This
  40946. ** has no effect if the sub-journal is already opened (as it may be when
  40947. ** running in exclusive mode) or if the transaction does not require a
  40948. ** sub-journal. If the subjInMemory argument is zero, then any required
  40949. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  40950. ** or using a temporary file otherwise.
  40951. */
  40952. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  40953. int rc = SQLITE_OK;
  40954. if( pPager->errCode ) return pPager->errCode;
  40955. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  40956. pPager->subjInMemory = (u8)subjInMemory;
  40957. if( ALWAYS(pPager->eState==PAGER_READER) ){
  40958. assert( pPager->pInJournal==0 );
  40959. if( pagerUseWal(pPager) ){
  40960. /* If the pager is configured to use locking_mode=exclusive, and an
  40961. ** exclusive lock on the database is not already held, obtain it now.
  40962. */
  40963. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  40964. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  40965. if( rc!=SQLITE_OK ){
  40966. return rc;
  40967. }
  40968. sqlite3WalExclusiveMode(pPager->pWal, 1);
  40969. }
  40970. /* Grab the write lock on the log file. If successful, upgrade to
  40971. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  40972. ** The busy-handler is not invoked if another connection already
  40973. ** holds the write-lock. If possible, the upper layer will call it.
  40974. */
  40975. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  40976. }else{
  40977. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  40978. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  40979. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  40980. ** lock, but not when obtaining the RESERVED lock.
  40981. */
  40982. rc = pagerLockDb(pPager, RESERVED_LOCK);
  40983. if( rc==SQLITE_OK && exFlag ){
  40984. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  40985. }
  40986. }
  40987. if( rc==SQLITE_OK ){
  40988. /* Change to WRITER_LOCKED state.
  40989. **
  40990. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  40991. ** when it has an open transaction, but never to DBMOD or FINISHED.
  40992. ** This is because in those states the code to roll back savepoint
  40993. ** transactions may copy data from the sub-journal into the database
  40994. ** file as well as into the page cache. Which would be incorrect in
  40995. ** WAL mode.
  40996. */
  40997. pPager->eState = PAGER_WRITER_LOCKED;
  40998. pPager->dbHintSize = pPager->dbSize;
  40999. pPager->dbFileSize = pPager->dbSize;
  41000. pPager->dbOrigSize = pPager->dbSize;
  41001. pPager->journalOff = 0;
  41002. }
  41003. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  41004. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  41005. assert( assert_pager_state(pPager) );
  41006. }
  41007. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  41008. return rc;
  41009. }
  41010. /*
  41011. ** Mark a single data page as writeable. The page is written into the
  41012. ** main journal or sub-journal as required. If the page is written into
  41013. ** one of the journals, the corresponding bit is set in the
  41014. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  41015. ** of any open savepoints as appropriate.
  41016. */
  41017. static int pager_write(PgHdr *pPg){
  41018. void *pData = pPg->pData;
  41019. Pager *pPager = pPg->pPager;
  41020. int rc = SQLITE_OK;
  41021. /* This routine is not called unless a write-transaction has already
  41022. ** been started. The journal file may or may not be open at this point.
  41023. ** It is never called in the ERROR state.
  41024. */
  41025. assert( pPager->eState==PAGER_WRITER_LOCKED
  41026. || pPager->eState==PAGER_WRITER_CACHEMOD
  41027. || pPager->eState==PAGER_WRITER_DBMOD
  41028. );
  41029. assert( assert_pager_state(pPager) );
  41030. /* If an error has been previously detected, report the same error
  41031. ** again. This should not happen, but the check provides robustness. */
  41032. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41033. /* Higher-level routines never call this function if database is not
  41034. ** writable. But check anyway, just for robustness. */
  41035. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  41036. CHECK_PAGE(pPg);
  41037. /* The journal file needs to be opened. Higher level routines have already
  41038. ** obtained the necessary locks to begin the write-transaction, but the
  41039. ** rollback journal might not yet be open. Open it now if this is the case.
  41040. **
  41041. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  41042. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  41043. ** an error might occur and the pager would end up in WRITER_LOCKED state
  41044. ** with pages marked as dirty in the cache.
  41045. */
  41046. if( pPager->eState==PAGER_WRITER_LOCKED ){
  41047. rc = pager_open_journal(pPager);
  41048. if( rc!=SQLITE_OK ) return rc;
  41049. }
  41050. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  41051. assert( assert_pager_state(pPager) );
  41052. /* Mark the page as dirty. If the page has already been written
  41053. ** to the journal then we can return right away.
  41054. */
  41055. sqlite3PcacheMakeDirty(pPg);
  41056. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  41057. assert( !pagerUseWal(pPager) );
  41058. }else{
  41059. /* The transaction journal now exists and we have a RESERVED or an
  41060. ** EXCLUSIVE lock on the main database file. Write the current page to
  41061. ** the transaction journal if it is not there already.
  41062. */
  41063. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  41064. assert( pagerUseWal(pPager)==0 );
  41065. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  41066. u32 cksum;
  41067. char *pData2;
  41068. i64 iOff = pPager->journalOff;
  41069. /* We should never write to the journal file the page that
  41070. ** contains the database locks. The following assert verifies
  41071. ** that we do not. */
  41072. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  41073. assert( pPager->journalHdr<=pPager->journalOff );
  41074. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  41075. cksum = pager_cksum(pPager, (u8*)pData2);
  41076. /* Even if an IO or diskfull error occurs while journalling the
  41077. ** page in the block above, set the need-sync flag for the page.
  41078. ** Otherwise, when the transaction is rolled back, the logic in
  41079. ** playback_one_page() will think that the page needs to be restored
  41080. ** in the database file. And if an IO error occurs while doing so,
  41081. ** then corruption may follow.
  41082. */
  41083. pPg->flags |= PGHDR_NEED_SYNC;
  41084. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  41085. if( rc!=SQLITE_OK ) return rc;
  41086. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  41087. if( rc!=SQLITE_OK ) return rc;
  41088. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  41089. if( rc!=SQLITE_OK ) return rc;
  41090. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  41091. pPager->journalOff, pPager->pageSize));
  41092. PAGER_INCR(sqlite3_pager_writej_count);
  41093. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  41094. PAGERID(pPager), pPg->pgno,
  41095. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  41096. pPager->journalOff += 8 + pPager->pageSize;
  41097. pPager->nRec++;
  41098. assert( pPager->pInJournal!=0 );
  41099. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  41100. testcase( rc==SQLITE_NOMEM );
  41101. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  41102. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  41103. if( rc!=SQLITE_OK ){
  41104. assert( rc==SQLITE_NOMEM );
  41105. return rc;
  41106. }
  41107. }else{
  41108. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  41109. pPg->flags |= PGHDR_NEED_SYNC;
  41110. }
  41111. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  41112. PAGERID(pPager), pPg->pgno,
  41113. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  41114. }
  41115. }
  41116. /* If the statement journal is open and the page is not in it,
  41117. ** then write the current page to the statement journal. Note that
  41118. ** the statement journal format differs from the standard journal format
  41119. ** in that it omits the checksums and the header.
  41120. */
  41121. if( subjRequiresPage(pPg) ){
  41122. rc = subjournalPage(pPg);
  41123. }
  41124. }
  41125. /* Update the database size and return.
  41126. */
  41127. if( pPager->dbSize<pPg->pgno ){
  41128. pPager->dbSize = pPg->pgno;
  41129. }
  41130. return rc;
  41131. }
  41132. /*
  41133. ** Mark a data page as writeable. This routine must be called before
  41134. ** making changes to a page. The caller must check the return value
  41135. ** of this function and be careful not to change any page data unless
  41136. ** this routine returns SQLITE_OK.
  41137. **
  41138. ** The difference between this function and pager_write() is that this
  41139. ** function also deals with the special case where 2 or more pages
  41140. ** fit on a single disk sector. In this case all co-resident pages
  41141. ** must have been written to the journal file before returning.
  41142. **
  41143. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  41144. ** as appropriate. Otherwise, SQLITE_OK.
  41145. */
  41146. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  41147. int rc = SQLITE_OK;
  41148. PgHdr *pPg = pDbPage;
  41149. Pager *pPager = pPg->pPager;
  41150. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  41151. assert( (pPg->flags & PGHDR_MMAP)==0 );
  41152. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  41153. assert( pPager->eState!=PAGER_ERROR );
  41154. assert( assert_pager_state(pPager) );
  41155. if( nPagePerSector>1 ){
  41156. Pgno nPageCount; /* Total number of pages in database file */
  41157. Pgno pg1; /* First page of the sector pPg is located on. */
  41158. int nPage = 0; /* Number of pages starting at pg1 to journal */
  41159. int ii; /* Loop counter */
  41160. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  41161. /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
  41162. ** a journal header to be written between the pages journaled by
  41163. ** this function.
  41164. */
  41165. assert( !MEMDB );
  41166. assert( pPager->doNotSyncSpill==0 );
  41167. pPager->doNotSyncSpill++;
  41168. /* This trick assumes that both the page-size and sector-size are
  41169. ** an integer power of 2. It sets variable pg1 to the identifier
  41170. ** of the first page of the sector pPg is located on.
  41171. */
  41172. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  41173. nPageCount = pPager->dbSize;
  41174. if( pPg->pgno>nPageCount ){
  41175. nPage = (pPg->pgno - pg1)+1;
  41176. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  41177. nPage = nPageCount+1-pg1;
  41178. }else{
  41179. nPage = nPagePerSector;
  41180. }
  41181. assert(nPage>0);
  41182. assert(pg1<=pPg->pgno);
  41183. assert((pg1+nPage)>pPg->pgno);
  41184. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  41185. Pgno pg = pg1+ii;
  41186. PgHdr *pPage;
  41187. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  41188. if( pg!=PAGER_MJ_PGNO(pPager) ){
  41189. rc = sqlite3PagerGet(pPager, pg, &pPage);
  41190. if( rc==SQLITE_OK ){
  41191. rc = pager_write(pPage);
  41192. if( pPage->flags&PGHDR_NEED_SYNC ){
  41193. needSync = 1;
  41194. }
  41195. sqlite3PagerUnref(pPage);
  41196. }
  41197. }
  41198. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  41199. if( pPage->flags&PGHDR_NEED_SYNC ){
  41200. needSync = 1;
  41201. }
  41202. sqlite3PagerUnref(pPage);
  41203. }
  41204. }
  41205. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  41206. ** starting at pg1, then it needs to be set for all of them. Because
  41207. ** writing to any of these nPage pages may damage the others, the
  41208. ** journal file must contain sync()ed copies of all of them
  41209. ** before any of them can be written out to the database file.
  41210. */
  41211. if( rc==SQLITE_OK && needSync ){
  41212. assert( !MEMDB );
  41213. for(ii=0; ii<nPage; ii++){
  41214. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  41215. if( pPage ){
  41216. pPage->flags |= PGHDR_NEED_SYNC;
  41217. sqlite3PagerUnref(pPage);
  41218. }
  41219. }
  41220. }
  41221. assert( pPager->doNotSyncSpill==1 );
  41222. pPager->doNotSyncSpill--;
  41223. }else{
  41224. rc = pager_write(pDbPage);
  41225. }
  41226. return rc;
  41227. }
  41228. /*
  41229. ** Return TRUE if the page given in the argument was previously passed
  41230. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  41231. ** to change the content of the page.
  41232. */
  41233. #ifndef NDEBUG
  41234. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  41235. return pPg->flags&PGHDR_DIRTY;
  41236. }
  41237. #endif
  41238. /*
  41239. ** A call to this routine tells the pager that it is not necessary to
  41240. ** write the information on page pPg back to the disk, even though
  41241. ** that page might be marked as dirty. This happens, for example, when
  41242. ** the page has been added as a leaf of the freelist and so its
  41243. ** content no longer matters.
  41244. **
  41245. ** The overlying software layer calls this routine when all of the data
  41246. ** on the given page is unused. The pager marks the page as clean so
  41247. ** that it does not get written to disk.
  41248. **
  41249. ** Tests show that this optimization can quadruple the speed of large
  41250. ** DELETE operations.
  41251. */
  41252. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  41253. Pager *pPager = pPg->pPager;
  41254. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  41255. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  41256. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  41257. pPg->flags |= PGHDR_DONT_WRITE;
  41258. pager_set_pagehash(pPg);
  41259. }
  41260. }
  41261. /*
  41262. ** This routine is called to increment the value of the database file
  41263. ** change-counter, stored as a 4-byte big-endian integer starting at
  41264. ** byte offset 24 of the pager file. The secondary change counter at
  41265. ** 92 is also updated, as is the SQLite version number at offset 96.
  41266. **
  41267. ** But this only happens if the pPager->changeCountDone flag is false.
  41268. ** To avoid excess churning of page 1, the update only happens once.
  41269. ** See also the pager_write_changecounter() routine that does an
  41270. ** unconditional update of the change counters.
  41271. **
  41272. ** If the isDirectMode flag is zero, then this is done by calling
  41273. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  41274. ** page data. In this case the file will be updated when the current
  41275. ** transaction is committed.
  41276. **
  41277. ** The isDirectMode flag may only be non-zero if the library was compiled
  41278. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  41279. ** if isDirect is non-zero, then the database file is updated directly
  41280. ** by writing an updated version of page 1 using a call to the
  41281. ** sqlite3OsWrite() function.
  41282. */
  41283. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  41284. int rc = SQLITE_OK;
  41285. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  41286. || pPager->eState==PAGER_WRITER_DBMOD
  41287. );
  41288. assert( assert_pager_state(pPager) );
  41289. /* Declare and initialize constant integer 'isDirect'. If the
  41290. ** atomic-write optimization is enabled in this build, then isDirect
  41291. ** is initialized to the value passed as the isDirectMode parameter
  41292. ** to this function. Otherwise, it is always set to zero.
  41293. **
  41294. ** The idea is that if the atomic-write optimization is not
  41295. ** enabled at compile time, the compiler can omit the tests of
  41296. ** 'isDirect' below, as well as the block enclosed in the
  41297. ** "if( isDirect )" condition.
  41298. */
  41299. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  41300. # define DIRECT_MODE 0
  41301. assert( isDirectMode==0 );
  41302. UNUSED_PARAMETER(isDirectMode);
  41303. #else
  41304. # define DIRECT_MODE isDirectMode
  41305. #endif
  41306. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  41307. PgHdr *pPgHdr; /* Reference to page 1 */
  41308. assert( !pPager->tempFile && isOpen(pPager->fd) );
  41309. /* Open page 1 of the file for writing. */
  41310. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  41311. assert( pPgHdr==0 || rc==SQLITE_OK );
  41312. /* If page one was fetched successfully, and this function is not
  41313. ** operating in direct-mode, make page 1 writable. When not in
  41314. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  41315. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  41316. */
  41317. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  41318. rc = sqlite3PagerWrite(pPgHdr);
  41319. }
  41320. if( rc==SQLITE_OK ){
  41321. /* Actually do the update of the change counter */
  41322. pager_write_changecounter(pPgHdr);
  41323. /* If running in direct mode, write the contents of page 1 to the file. */
  41324. if( DIRECT_MODE ){
  41325. const void *zBuf;
  41326. assert( pPager->dbFileSize>0 );
  41327. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  41328. if( rc==SQLITE_OK ){
  41329. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  41330. pPager->aStat[PAGER_STAT_WRITE]++;
  41331. }
  41332. if( rc==SQLITE_OK ){
  41333. /* Update the pager's copy of the change-counter. Otherwise, the
  41334. ** next time a read transaction is opened the cache will be
  41335. ** flushed (as the change-counter values will not match). */
  41336. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  41337. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  41338. pPager->changeCountDone = 1;
  41339. }
  41340. }else{
  41341. pPager->changeCountDone = 1;
  41342. }
  41343. }
  41344. /* Release the page reference. */
  41345. sqlite3PagerUnref(pPgHdr);
  41346. }
  41347. return rc;
  41348. }
  41349. /*
  41350. ** Sync the database file to disk. This is a no-op for in-memory databases
  41351. ** or pages with the Pager.noSync flag set.
  41352. **
  41353. ** If successful, or if called on a pager for which it is a no-op, this
  41354. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  41355. */
  41356. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  41357. int rc = SQLITE_OK;
  41358. if( !pPager->noSync ){
  41359. assert( !MEMDB );
  41360. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  41361. }else if( isOpen(pPager->fd) ){
  41362. assert( !MEMDB );
  41363. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  41364. if( rc==SQLITE_NOTFOUND ){
  41365. rc = SQLITE_OK;
  41366. }
  41367. }
  41368. return rc;
  41369. }
  41370. /*
  41371. ** This function may only be called while a write-transaction is active in
  41372. ** rollback. If the connection is in WAL mode, this call is a no-op.
  41373. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  41374. ** the database file, an attempt is made to obtain one.
  41375. **
  41376. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  41377. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  41378. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  41379. ** returned.
  41380. */
  41381. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  41382. int rc = SQLITE_OK;
  41383. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  41384. || pPager->eState==PAGER_WRITER_DBMOD
  41385. || pPager->eState==PAGER_WRITER_LOCKED
  41386. );
  41387. assert( assert_pager_state(pPager) );
  41388. if( 0==pagerUseWal(pPager) ){
  41389. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  41390. }
  41391. return rc;
  41392. }
  41393. /*
  41394. ** Sync the database file for the pager pPager. zMaster points to the name
  41395. ** of a master journal file that should be written into the individual
  41396. ** journal file. zMaster may be NULL, which is interpreted as no master
  41397. ** journal (a single database transaction).
  41398. **
  41399. ** This routine ensures that:
  41400. **
  41401. ** * The database file change-counter is updated,
  41402. ** * the journal is synced (unless the atomic-write optimization is used),
  41403. ** * all dirty pages are written to the database file,
  41404. ** * the database file is truncated (if required), and
  41405. ** * the database file synced.
  41406. **
  41407. ** The only thing that remains to commit the transaction is to finalize
  41408. ** (delete, truncate or zero the first part of) the journal file (or
  41409. ** delete the master journal file if specified).
  41410. **
  41411. ** Note that if zMaster==NULL, this does not overwrite a previous value
  41412. ** passed to an sqlite3PagerCommitPhaseOne() call.
  41413. **
  41414. ** If the final parameter - noSync - is true, then the database file itself
  41415. ** is not synced. The caller must call sqlite3PagerSync() directly to
  41416. ** sync the database file before calling CommitPhaseTwo() to delete the
  41417. ** journal file in this case.
  41418. */
  41419. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  41420. Pager *pPager, /* Pager object */
  41421. const char *zMaster, /* If not NULL, the master journal name */
  41422. int noSync /* True to omit the xSync on the db file */
  41423. ){
  41424. int rc = SQLITE_OK; /* Return code */
  41425. assert( pPager->eState==PAGER_WRITER_LOCKED
  41426. || pPager->eState==PAGER_WRITER_CACHEMOD
  41427. || pPager->eState==PAGER_WRITER_DBMOD
  41428. || pPager->eState==PAGER_ERROR
  41429. );
  41430. assert( assert_pager_state(pPager) );
  41431. /* If a prior error occurred, report that error again. */
  41432. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41433. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  41434. pPager->zFilename, zMaster, pPager->dbSize));
  41435. /* If no database changes have been made, return early. */
  41436. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  41437. if( MEMDB ){
  41438. /* If this is an in-memory db, or no pages have been written to, or this
  41439. ** function has already been called, it is mostly a no-op. However, any
  41440. ** backup in progress needs to be restarted.
  41441. */
  41442. sqlite3BackupRestart(pPager->pBackup);
  41443. }else{
  41444. if( pagerUseWal(pPager) ){
  41445. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41446. PgHdr *pPageOne = 0;
  41447. if( pList==0 ){
  41448. /* Must have at least one page for the WAL commit flag.
  41449. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  41450. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  41451. pList = pPageOne;
  41452. pList->pDirty = 0;
  41453. }
  41454. assert( rc==SQLITE_OK );
  41455. if( ALWAYS(pList) ){
  41456. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  41457. }
  41458. sqlite3PagerUnref(pPageOne);
  41459. if( rc==SQLITE_OK ){
  41460. sqlite3PcacheCleanAll(pPager->pPCache);
  41461. }
  41462. }else{
  41463. /* The following block updates the change-counter. Exactly how it
  41464. ** does this depends on whether or not the atomic-update optimization
  41465. ** was enabled at compile time, and if this transaction meets the
  41466. ** runtime criteria to use the operation:
  41467. **
  41468. ** * The file-system supports the atomic-write property for
  41469. ** blocks of size page-size, and
  41470. ** * This commit is not part of a multi-file transaction, and
  41471. ** * Exactly one page has been modified and store in the journal file.
  41472. **
  41473. ** If the optimization was not enabled at compile time, then the
  41474. ** pager_incr_changecounter() function is called to update the change
  41475. ** counter in 'indirect-mode'. If the optimization is compiled in but
  41476. ** is not applicable to this transaction, call sqlite3JournalCreate()
  41477. ** to make sure the journal file has actually been created, then call
  41478. ** pager_incr_changecounter() to update the change-counter in indirect
  41479. ** mode.
  41480. **
  41481. ** Otherwise, if the optimization is both enabled and applicable,
  41482. ** then call pager_incr_changecounter() to update the change-counter
  41483. ** in 'direct' mode. In this case the journal file will never be
  41484. ** created for this transaction.
  41485. */
  41486. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  41487. PgHdr *pPg;
  41488. assert( isOpen(pPager->jfd)
  41489. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  41490. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  41491. );
  41492. if( !zMaster && isOpen(pPager->jfd)
  41493. && pPager->journalOff==jrnlBufferSize(pPager)
  41494. && pPager->dbSize>=pPager->dbOrigSize
  41495. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  41496. ){
  41497. /* Update the db file change counter via the direct-write method. The
  41498. ** following call will modify the in-memory representation of page 1
  41499. ** to include the updated change counter and then write page 1
  41500. ** directly to the database file. Because of the atomic-write
  41501. ** property of the host file-system, this is safe.
  41502. */
  41503. rc = pager_incr_changecounter(pPager, 1);
  41504. }else{
  41505. rc = sqlite3JournalCreate(pPager->jfd);
  41506. if( rc==SQLITE_OK ){
  41507. rc = pager_incr_changecounter(pPager, 0);
  41508. }
  41509. }
  41510. #else
  41511. rc = pager_incr_changecounter(pPager, 0);
  41512. #endif
  41513. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41514. /* Write the master journal name into the journal file. If a master
  41515. ** journal file name has already been written to the journal file,
  41516. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  41517. */
  41518. rc = writeMasterJournal(pPager, zMaster);
  41519. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41520. /* Sync the journal file and write all dirty pages to the database.
  41521. ** If the atomic-update optimization is being used, this sync will not
  41522. ** create the journal file or perform any real IO.
  41523. **
  41524. ** Because the change-counter page was just modified, unless the
  41525. ** atomic-update optimization is used it is almost certain that the
  41526. ** journal requires a sync here. However, in locking_mode=exclusive
  41527. ** on a system under memory pressure it is just possible that this is
  41528. ** not the case. In this case it is likely enough that the redundant
  41529. ** xSync() call will be changed to a no-op by the OS anyhow.
  41530. */
  41531. rc = syncJournal(pPager, 0);
  41532. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41533. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  41534. if( rc!=SQLITE_OK ){
  41535. assert( rc!=SQLITE_IOERR_BLOCKED );
  41536. goto commit_phase_one_exit;
  41537. }
  41538. sqlite3PcacheCleanAll(pPager->pPCache);
  41539. /* If the file on disk is smaller than the database image, use
  41540. ** pager_truncate to grow the file here. This can happen if the database
  41541. ** image was extended as part of the current transaction and then the
  41542. ** last page in the db image moved to the free-list. In this case the
  41543. ** last page is never written out to disk, leaving the database file
  41544. ** undersized. Fix this now if it is the case. */
  41545. if( pPager->dbSize>pPager->dbFileSize ){
  41546. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  41547. assert( pPager->eState==PAGER_WRITER_DBMOD );
  41548. rc = pager_truncate(pPager, nNew);
  41549. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  41550. }
  41551. /* Finally, sync the database file. */
  41552. if( !noSync ){
  41553. rc = sqlite3PagerSync(pPager);
  41554. }
  41555. IOTRACE(("DBSYNC %p\n", pPager))
  41556. }
  41557. }
  41558. commit_phase_one_exit:
  41559. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  41560. pPager->eState = PAGER_WRITER_FINISHED;
  41561. }
  41562. return rc;
  41563. }
  41564. /*
  41565. ** When this function is called, the database file has been completely
  41566. ** updated to reflect the changes made by the current transaction and
  41567. ** synced to disk. The journal file still exists in the file-system
  41568. ** though, and if a failure occurs at this point it will eventually
  41569. ** be used as a hot-journal and the current transaction rolled back.
  41570. **
  41571. ** This function finalizes the journal file, either by deleting,
  41572. ** truncating or partially zeroing it, so that it cannot be used
  41573. ** for hot-journal rollback. Once this is done the transaction is
  41574. ** irrevocably committed.
  41575. **
  41576. ** If an error occurs, an IO error code is returned and the pager
  41577. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  41578. */
  41579. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  41580. int rc = SQLITE_OK; /* Return code */
  41581. /* This routine should not be called if a prior error has occurred.
  41582. ** But if (due to a coding error elsewhere in the system) it does get
  41583. ** called, just return the same error code without doing anything. */
  41584. if( NEVER(pPager->errCode) ) return pPager->errCode;
  41585. assert( pPager->eState==PAGER_WRITER_LOCKED
  41586. || pPager->eState==PAGER_WRITER_FINISHED
  41587. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  41588. );
  41589. assert( assert_pager_state(pPager) );
  41590. /* An optimization. If the database was not actually modified during
  41591. ** this transaction, the pager is running in exclusive-mode and is
  41592. ** using persistent journals, then this function is a no-op.
  41593. **
  41594. ** The start of the journal file currently contains a single journal
  41595. ** header with the nRec field set to 0. If such a journal is used as
  41596. ** a hot-journal during hot-journal rollback, 0 changes will be made
  41597. ** to the database file. So there is no need to zero the journal
  41598. ** header. Since the pager is in exclusive mode, there is no need
  41599. ** to drop any locks either.
  41600. */
  41601. if( pPager->eState==PAGER_WRITER_LOCKED
  41602. && pPager->exclusiveMode
  41603. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  41604. ){
  41605. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  41606. pPager->eState = PAGER_READER;
  41607. return SQLITE_OK;
  41608. }
  41609. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  41610. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  41611. return pager_error(pPager, rc);
  41612. }
  41613. /*
  41614. ** If a write transaction is open, then all changes made within the
  41615. ** transaction are reverted and the current write-transaction is closed.
  41616. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  41617. ** state if an error occurs.
  41618. **
  41619. ** If the pager is already in PAGER_ERROR state when this function is called,
  41620. ** it returns Pager.errCode immediately. No work is performed in this case.
  41621. **
  41622. ** Otherwise, in rollback mode, this function performs two functions:
  41623. **
  41624. ** 1) It rolls back the journal file, restoring all database file and
  41625. ** in-memory cache pages to the state they were in when the transaction
  41626. ** was opened, and
  41627. **
  41628. ** 2) It finalizes the journal file, so that it is not used for hot
  41629. ** rollback at any point in the future.
  41630. **
  41631. ** Finalization of the journal file (task 2) is only performed if the
  41632. ** rollback is successful.
  41633. **
  41634. ** In WAL mode, all cache-entries containing data modified within the
  41635. ** current transaction are either expelled from the cache or reverted to
  41636. ** their pre-transaction state by re-reading data from the database or
  41637. ** WAL files. The WAL transaction is then closed.
  41638. */
  41639. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  41640. int rc = SQLITE_OK; /* Return code */
  41641. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  41642. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  41643. ** the pager is already in the ERROR state, the rollback is not
  41644. ** attempted here. Instead, the error code is returned to the caller.
  41645. */
  41646. assert( assert_pager_state(pPager) );
  41647. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  41648. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  41649. if( pagerUseWal(pPager) ){
  41650. int rc2;
  41651. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  41652. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  41653. if( rc==SQLITE_OK ) rc = rc2;
  41654. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  41655. int eState = pPager->eState;
  41656. rc = pager_end_transaction(pPager, 0, 0);
  41657. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  41658. /* This can happen using journal_mode=off. Move the pager to the error
  41659. ** state to indicate that the contents of the cache may not be trusted.
  41660. ** Any active readers will get SQLITE_ABORT.
  41661. */
  41662. pPager->errCode = SQLITE_ABORT;
  41663. pPager->eState = PAGER_ERROR;
  41664. return rc;
  41665. }
  41666. }else{
  41667. rc = pager_playback(pPager, 0);
  41668. }
  41669. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  41670. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  41671. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  41672. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  41673. ** cache. So call pager_error() on the way out to make any error persistent.
  41674. */
  41675. return pager_error(pPager, rc);
  41676. }
  41677. /*
  41678. ** Return TRUE if the database file is opened read-only. Return FALSE
  41679. ** if the database is (in theory) writable.
  41680. */
  41681. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  41682. return pPager->readOnly;
  41683. }
  41684. /*
  41685. ** Return the number of references to the pager.
  41686. */
  41687. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  41688. return sqlite3PcacheRefCount(pPager->pPCache);
  41689. }
  41690. /*
  41691. ** Return the approximate number of bytes of memory currently
  41692. ** used by the pager and its associated cache.
  41693. */
  41694. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  41695. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  41696. + 5*sizeof(void*);
  41697. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  41698. + sqlite3MallocSize(pPager)
  41699. + pPager->pageSize;
  41700. }
  41701. /*
  41702. ** Return the number of references to the specified page.
  41703. */
  41704. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  41705. return sqlite3PcachePageRefcount(pPage);
  41706. }
  41707. #ifdef SQLITE_TEST
  41708. /*
  41709. ** This routine is used for testing and analysis only.
  41710. */
  41711. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  41712. static int a[11];
  41713. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  41714. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  41715. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  41716. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  41717. a[4] = pPager->eState;
  41718. a[5] = pPager->errCode;
  41719. a[6] = pPager->aStat[PAGER_STAT_HIT];
  41720. a[7] = pPager->aStat[PAGER_STAT_MISS];
  41721. a[8] = 0; /* Used to be pPager->nOvfl */
  41722. a[9] = pPager->nRead;
  41723. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  41724. return a;
  41725. }
  41726. #endif
  41727. /*
  41728. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  41729. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  41730. ** current cache hit or miss count, according to the value of eStat. If the
  41731. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  41732. ** returning.
  41733. */
  41734. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  41735. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  41736. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  41737. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  41738. );
  41739. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  41740. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  41741. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  41742. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  41743. if( reset ){
  41744. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  41745. }
  41746. }
  41747. /*
  41748. ** Return true if this is an in-memory pager.
  41749. */
  41750. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  41751. return MEMDB;
  41752. }
  41753. /*
  41754. ** Check that there are at least nSavepoint savepoints open. If there are
  41755. ** currently less than nSavepoints open, then open one or more savepoints
  41756. ** to make up the difference. If the number of savepoints is already
  41757. ** equal to nSavepoint, then this function is a no-op.
  41758. **
  41759. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  41760. ** occurs while opening the sub-journal file, then an IO error code is
  41761. ** returned. Otherwise, SQLITE_OK.
  41762. */
  41763. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  41764. int rc = SQLITE_OK; /* Return code */
  41765. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  41766. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  41767. assert( assert_pager_state(pPager) );
  41768. if( nSavepoint>nCurrent && pPager->useJournal ){
  41769. int ii; /* Iterator variable */
  41770. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  41771. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  41772. ** if the allocation fails. Otherwise, zero the new portion in case a
  41773. ** malloc failure occurs while populating it in the for(...) loop below.
  41774. */
  41775. aNew = (PagerSavepoint *)sqlite3Realloc(
  41776. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  41777. );
  41778. if( !aNew ){
  41779. return SQLITE_NOMEM;
  41780. }
  41781. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  41782. pPager->aSavepoint = aNew;
  41783. /* Populate the PagerSavepoint structures just allocated. */
  41784. for(ii=nCurrent; ii<nSavepoint; ii++){
  41785. aNew[ii].nOrig = pPager->dbSize;
  41786. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  41787. aNew[ii].iOffset = pPager->journalOff;
  41788. }else{
  41789. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  41790. }
  41791. aNew[ii].iSubRec = pPager->nSubRec;
  41792. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  41793. if( !aNew[ii].pInSavepoint ){
  41794. return SQLITE_NOMEM;
  41795. }
  41796. if( pagerUseWal(pPager) ){
  41797. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  41798. }
  41799. pPager->nSavepoint = ii+1;
  41800. }
  41801. assert( pPager->nSavepoint==nSavepoint );
  41802. assertTruncateConstraint(pPager);
  41803. }
  41804. return rc;
  41805. }
  41806. /*
  41807. ** This function is called to rollback or release (commit) a savepoint.
  41808. ** The savepoint to release or rollback need not be the most recently
  41809. ** created savepoint.
  41810. **
  41811. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  41812. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  41813. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  41814. ** that have occurred since the specified savepoint was created.
  41815. **
  41816. ** The savepoint to rollback or release is identified by parameter
  41817. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  41818. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  41819. ** on the most recently created savepoint. If iSavepoint is greater than
  41820. ** (Pager.nSavepoint-1), then this function is a no-op.
  41821. **
  41822. ** If a negative value is passed to this function, then the current
  41823. ** transaction is rolled back. This is different to calling
  41824. ** sqlite3PagerRollback() because this function does not terminate
  41825. ** the transaction or unlock the database, it just restores the
  41826. ** contents of the database to its original state.
  41827. **
  41828. ** In any case, all savepoints with an index greater than iSavepoint
  41829. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  41830. ** then savepoint iSavepoint is also destroyed.
  41831. **
  41832. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  41833. ** or an IO error code if an IO error occurs while rolling back a
  41834. ** savepoint. If no errors occur, SQLITE_OK is returned.
  41835. */
  41836. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  41837. int rc = pPager->errCode; /* Return code */
  41838. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  41839. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  41840. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  41841. int ii; /* Iterator variable */
  41842. int nNew; /* Number of remaining savepoints after this op. */
  41843. /* Figure out how many savepoints will still be active after this
  41844. ** operation. Store this value in nNew. Then free resources associated
  41845. ** with any savepoints that are destroyed by this operation.
  41846. */
  41847. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  41848. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  41849. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  41850. }
  41851. pPager->nSavepoint = nNew;
  41852. /* If this is a release of the outermost savepoint, truncate
  41853. ** the sub-journal to zero bytes in size. */
  41854. if( op==SAVEPOINT_RELEASE ){
  41855. if( nNew==0 && isOpen(pPager->sjfd) ){
  41856. /* Only truncate if it is an in-memory sub-journal. */
  41857. if( sqlite3IsMemJournal(pPager->sjfd) ){
  41858. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  41859. assert( rc==SQLITE_OK );
  41860. }
  41861. pPager->nSubRec = 0;
  41862. }
  41863. }
  41864. /* Else this is a rollback operation, playback the specified savepoint.
  41865. ** If this is a temp-file, it is possible that the journal file has
  41866. ** not yet been opened. In this case there have been no changes to
  41867. ** the database file, so the playback operation can be skipped.
  41868. */
  41869. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  41870. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  41871. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  41872. assert(rc!=SQLITE_DONE);
  41873. }
  41874. }
  41875. return rc;
  41876. }
  41877. /*
  41878. ** Return the full pathname of the database file.
  41879. **
  41880. ** Except, if the pager is in-memory only, then return an empty string if
  41881. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  41882. ** used to report the filename to the user, for compatibility with legacy
  41883. ** behavior. But when the Btree needs to know the filename for matching to
  41884. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  41885. ** participate in shared-cache.
  41886. */
  41887. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  41888. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  41889. }
  41890. /*
  41891. ** Return the VFS structure for the pager.
  41892. */
  41893. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  41894. return pPager->pVfs;
  41895. }
  41896. /*
  41897. ** Return the file handle for the database file associated
  41898. ** with the pager. This might return NULL if the file has
  41899. ** not yet been opened.
  41900. */
  41901. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  41902. return pPager->fd;
  41903. }
  41904. /*
  41905. ** Return the full pathname of the journal file.
  41906. */
  41907. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  41908. return pPager->zJournal;
  41909. }
  41910. /*
  41911. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  41912. ** if fsync()s are executed normally.
  41913. */
  41914. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  41915. return pPager->noSync;
  41916. }
  41917. #ifdef SQLITE_HAS_CODEC
  41918. /*
  41919. ** Set or retrieve the codec for this pager
  41920. */
  41921. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  41922. Pager *pPager,
  41923. void *(*xCodec)(void*,void*,Pgno,int),
  41924. void (*xCodecSizeChng)(void*,int,int),
  41925. void (*xCodecFree)(void*),
  41926. void *pCodec
  41927. ){
  41928. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  41929. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  41930. pPager->xCodecSizeChng = xCodecSizeChng;
  41931. pPager->xCodecFree = xCodecFree;
  41932. pPager->pCodec = pCodec;
  41933. pagerReportSize(pPager);
  41934. }
  41935. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  41936. return pPager->pCodec;
  41937. }
  41938. #endif
  41939. #ifndef SQLITE_OMIT_AUTOVACUUM
  41940. /*
  41941. ** Move the page pPg to location pgno in the file.
  41942. **
  41943. ** There must be no references to the page previously located at
  41944. ** pgno (which we call pPgOld) though that page is allowed to be
  41945. ** in cache. If the page previously located at pgno is not already
  41946. ** in the rollback journal, it is not put there by by this routine.
  41947. **
  41948. ** References to the page pPg remain valid. Updating any
  41949. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  41950. ** allocated along with the page) is the responsibility of the caller.
  41951. **
  41952. ** A transaction must be active when this routine is called. It used to be
  41953. ** required that a statement transaction was not active, but this restriction
  41954. ** has been removed (CREATE INDEX needs to move a page when a statement
  41955. ** transaction is active).
  41956. **
  41957. ** If the fourth argument, isCommit, is non-zero, then this page is being
  41958. ** moved as part of a database reorganization just before the transaction
  41959. ** is being committed. In this case, it is guaranteed that the database page
  41960. ** pPg refers to will not be written to again within this transaction.
  41961. **
  41962. ** This function may return SQLITE_NOMEM or an IO error code if an error
  41963. ** occurs. Otherwise, it returns SQLITE_OK.
  41964. */
  41965. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  41966. PgHdr *pPgOld; /* The page being overwritten. */
  41967. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  41968. int rc; /* Return code */
  41969. Pgno origPgno; /* The original page number */
  41970. assert( pPg->nRef>0 );
  41971. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  41972. || pPager->eState==PAGER_WRITER_DBMOD
  41973. );
  41974. assert( assert_pager_state(pPager) );
  41975. /* In order to be able to rollback, an in-memory database must journal
  41976. ** the page we are moving from.
  41977. */
  41978. if( MEMDB ){
  41979. rc = sqlite3PagerWrite(pPg);
  41980. if( rc ) return rc;
  41981. }
  41982. /* If the page being moved is dirty and has not been saved by the latest
  41983. ** savepoint, then save the current contents of the page into the
  41984. ** sub-journal now. This is required to handle the following scenario:
  41985. **
  41986. ** BEGIN;
  41987. ** <journal page X, then modify it in memory>
  41988. ** SAVEPOINT one;
  41989. ** <Move page X to location Y>
  41990. ** ROLLBACK TO one;
  41991. **
  41992. ** If page X were not written to the sub-journal here, it would not
  41993. ** be possible to restore its contents when the "ROLLBACK TO one"
  41994. ** statement were is processed.
  41995. **
  41996. ** subjournalPage() may need to allocate space to store pPg->pgno into
  41997. ** one or more savepoint bitvecs. This is the reason this function
  41998. ** may return SQLITE_NOMEM.
  41999. */
  42000. if( pPg->flags&PGHDR_DIRTY
  42001. && subjRequiresPage(pPg)
  42002. && SQLITE_OK!=(rc = subjournalPage(pPg))
  42003. ){
  42004. return rc;
  42005. }
  42006. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  42007. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  42008. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  42009. /* If the journal needs to be sync()ed before page pPg->pgno can
  42010. ** be written to, store pPg->pgno in local variable needSyncPgno.
  42011. **
  42012. ** If the isCommit flag is set, there is no need to remember that
  42013. ** the journal needs to be sync()ed before database page pPg->pgno
  42014. ** can be written to. The caller has already promised not to write to it.
  42015. */
  42016. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  42017. needSyncPgno = pPg->pgno;
  42018. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  42019. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  42020. assert( pPg->flags&PGHDR_DIRTY );
  42021. }
  42022. /* If the cache contains a page with page-number pgno, remove it
  42023. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  42024. ** page pgno before the 'move' operation, it needs to be retained
  42025. ** for the page moved there.
  42026. */
  42027. pPg->flags &= ~PGHDR_NEED_SYNC;
  42028. pPgOld = pager_lookup(pPager, pgno);
  42029. assert( !pPgOld || pPgOld->nRef==1 );
  42030. if( pPgOld ){
  42031. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  42032. if( MEMDB ){
  42033. /* Do not discard pages from an in-memory database since we might
  42034. ** need to rollback later. Just move the page out of the way. */
  42035. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  42036. }else{
  42037. sqlite3PcacheDrop(pPgOld);
  42038. }
  42039. }
  42040. origPgno = pPg->pgno;
  42041. sqlite3PcacheMove(pPg, pgno);
  42042. sqlite3PcacheMakeDirty(pPg);
  42043. /* For an in-memory database, make sure the original page continues
  42044. ** to exist, in case the transaction needs to roll back. Use pPgOld
  42045. ** as the original page since it has already been allocated.
  42046. */
  42047. if( MEMDB ){
  42048. assert( pPgOld );
  42049. sqlite3PcacheMove(pPgOld, origPgno);
  42050. sqlite3PagerUnref(pPgOld);
  42051. }
  42052. if( needSyncPgno ){
  42053. /* If needSyncPgno is non-zero, then the journal file needs to be
  42054. ** sync()ed before any data is written to database file page needSyncPgno.
  42055. ** Currently, no such page exists in the page-cache and the
  42056. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  42057. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  42058. ** flag.
  42059. **
  42060. ** If the attempt to load the page into the page-cache fails, (due
  42061. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  42062. ** array. Otherwise, if the page is loaded and written again in
  42063. ** this transaction, it may be written to the database file before
  42064. ** it is synced into the journal file. This way, it may end up in
  42065. ** the journal file twice, but that is not a problem.
  42066. */
  42067. PgHdr *pPgHdr;
  42068. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  42069. if( rc!=SQLITE_OK ){
  42070. if( needSyncPgno<=pPager->dbOrigSize ){
  42071. assert( pPager->pTmpSpace!=0 );
  42072. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  42073. }
  42074. return rc;
  42075. }
  42076. pPgHdr->flags |= PGHDR_NEED_SYNC;
  42077. sqlite3PcacheMakeDirty(pPgHdr);
  42078. sqlite3PagerUnref(pPgHdr);
  42079. }
  42080. return SQLITE_OK;
  42081. }
  42082. #endif
  42083. /*
  42084. ** Return a pointer to the data for the specified page.
  42085. */
  42086. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  42087. assert( pPg->nRef>0 || pPg->pPager->memDb );
  42088. return pPg->pData;
  42089. }
  42090. /*
  42091. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  42092. ** allocated along with the specified page.
  42093. */
  42094. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  42095. return pPg->pExtra;
  42096. }
  42097. /*
  42098. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  42099. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  42100. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  42101. ** the locking-mode is set to the value specified.
  42102. **
  42103. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  42104. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  42105. ** locking-mode.
  42106. */
  42107. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  42108. assert( eMode==PAGER_LOCKINGMODE_QUERY
  42109. || eMode==PAGER_LOCKINGMODE_NORMAL
  42110. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  42111. assert( PAGER_LOCKINGMODE_QUERY<0 );
  42112. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  42113. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  42114. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  42115. pPager->exclusiveMode = (u8)eMode;
  42116. }
  42117. return (int)pPager->exclusiveMode;
  42118. }
  42119. /*
  42120. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  42121. **
  42122. ** PAGER_JOURNALMODE_DELETE
  42123. ** PAGER_JOURNALMODE_TRUNCATE
  42124. ** PAGER_JOURNALMODE_PERSIST
  42125. ** PAGER_JOURNALMODE_OFF
  42126. ** PAGER_JOURNALMODE_MEMORY
  42127. ** PAGER_JOURNALMODE_WAL
  42128. **
  42129. ** The journalmode is set to the value specified if the change is allowed.
  42130. ** The change may be disallowed for the following reasons:
  42131. **
  42132. ** * An in-memory database can only have its journal_mode set to _OFF
  42133. ** or _MEMORY.
  42134. **
  42135. ** * Temporary databases cannot have _WAL journalmode.
  42136. **
  42137. ** The returned indicate the current (possibly updated) journal-mode.
  42138. */
  42139. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  42140. u8 eOld = pPager->journalMode; /* Prior journalmode */
  42141. #ifdef SQLITE_DEBUG
  42142. /* The print_pager_state() routine is intended to be used by the debugger
  42143. ** only. We invoke it once here to suppress a compiler warning. */
  42144. print_pager_state(pPager);
  42145. #endif
  42146. /* The eMode parameter is always valid */
  42147. assert( eMode==PAGER_JOURNALMODE_DELETE
  42148. || eMode==PAGER_JOURNALMODE_TRUNCATE
  42149. || eMode==PAGER_JOURNALMODE_PERSIST
  42150. || eMode==PAGER_JOURNALMODE_OFF
  42151. || eMode==PAGER_JOURNALMODE_WAL
  42152. || eMode==PAGER_JOURNALMODE_MEMORY );
  42153. /* This routine is only called from the OP_JournalMode opcode, and
  42154. ** the logic there will never allow a temporary file to be changed
  42155. ** to WAL mode.
  42156. */
  42157. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  42158. /* Do allow the journalmode of an in-memory database to be set to
  42159. ** anything other than MEMORY or OFF
  42160. */
  42161. if( MEMDB ){
  42162. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  42163. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  42164. eMode = eOld;
  42165. }
  42166. }
  42167. if( eMode!=eOld ){
  42168. /* Change the journal mode. */
  42169. assert( pPager->eState!=PAGER_ERROR );
  42170. pPager->journalMode = (u8)eMode;
  42171. /* When transistioning from TRUNCATE or PERSIST to any other journal
  42172. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  42173. ** delete the journal file.
  42174. */
  42175. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  42176. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  42177. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  42178. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  42179. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  42180. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  42181. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  42182. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  42183. /* In this case we would like to delete the journal file. If it is
  42184. ** not possible, then that is not a problem. Deleting the journal file
  42185. ** here is an optimization only.
  42186. **
  42187. ** Before deleting the journal file, obtain a RESERVED lock on the
  42188. ** database file. This ensures that the journal file is not deleted
  42189. ** while it is in use by some other client.
  42190. */
  42191. sqlite3OsClose(pPager->jfd);
  42192. if( pPager->eLock>=RESERVED_LOCK ){
  42193. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42194. }else{
  42195. int rc = SQLITE_OK;
  42196. int state = pPager->eState;
  42197. assert( state==PAGER_OPEN || state==PAGER_READER );
  42198. if( state==PAGER_OPEN ){
  42199. rc = sqlite3PagerSharedLock(pPager);
  42200. }
  42201. if( pPager->eState==PAGER_READER ){
  42202. assert( rc==SQLITE_OK );
  42203. rc = pagerLockDb(pPager, RESERVED_LOCK);
  42204. }
  42205. if( rc==SQLITE_OK ){
  42206. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42207. }
  42208. if( rc==SQLITE_OK && state==PAGER_READER ){
  42209. pagerUnlockDb(pPager, SHARED_LOCK);
  42210. }else if( state==PAGER_OPEN ){
  42211. pager_unlock(pPager);
  42212. }
  42213. assert( state==pPager->eState );
  42214. }
  42215. }
  42216. }
  42217. /* Return the new journal mode */
  42218. return (int)pPager->journalMode;
  42219. }
  42220. /*
  42221. ** Return the current journal mode.
  42222. */
  42223. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  42224. return (int)pPager->journalMode;
  42225. }
  42226. /*
  42227. ** Return TRUE if the pager is in a state where it is OK to change the
  42228. ** journalmode. Journalmode changes can only happen when the database
  42229. ** is unmodified.
  42230. */
  42231. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  42232. assert( assert_pager_state(pPager) );
  42233. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  42234. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  42235. return 1;
  42236. }
  42237. /*
  42238. ** Get/set the size-limit used for persistent journal files.
  42239. **
  42240. ** Setting the size limit to -1 means no limit is enforced.
  42241. ** An attempt to set a limit smaller than -1 is a no-op.
  42242. */
  42243. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  42244. if( iLimit>=-1 ){
  42245. pPager->journalSizeLimit = iLimit;
  42246. sqlite3WalLimit(pPager->pWal, iLimit);
  42247. }
  42248. return pPager->journalSizeLimit;
  42249. }
  42250. /*
  42251. ** Return a pointer to the pPager->pBackup variable. The backup module
  42252. ** in backup.c maintains the content of this variable. This module
  42253. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  42254. ** sqlite3BackupUpdate() only.
  42255. */
  42256. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  42257. return &pPager->pBackup;
  42258. }
  42259. #ifndef SQLITE_OMIT_VACUUM
  42260. /*
  42261. ** Unless this is an in-memory or temporary database, clear the pager cache.
  42262. */
  42263. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  42264. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  42265. }
  42266. #endif
  42267. #ifndef SQLITE_OMIT_WAL
  42268. /*
  42269. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  42270. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  42271. ** or wal_blocking_checkpoint() API functions.
  42272. **
  42273. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  42274. */
  42275. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  42276. int rc = SQLITE_OK;
  42277. if( pPager->pWal ){
  42278. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  42279. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  42280. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  42281. pnLog, pnCkpt
  42282. );
  42283. }
  42284. return rc;
  42285. }
  42286. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  42287. return sqlite3WalCallback(pPager->pWal);
  42288. }
  42289. /*
  42290. ** Return true if the underlying VFS for the given pager supports the
  42291. ** primitives necessary for write-ahead logging.
  42292. */
  42293. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  42294. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  42295. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  42296. }
  42297. /*
  42298. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  42299. ** is obtained instead, immediately release it.
  42300. */
  42301. static int pagerExclusiveLock(Pager *pPager){
  42302. int rc; /* Return code */
  42303. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  42304. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  42305. if( rc!=SQLITE_OK ){
  42306. /* If the attempt to grab the exclusive lock failed, release the
  42307. ** pending lock that may have been obtained instead. */
  42308. pagerUnlockDb(pPager, SHARED_LOCK);
  42309. }
  42310. return rc;
  42311. }
  42312. /*
  42313. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  42314. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  42315. ** lock on the database file and use heap-memory to store the wal-index
  42316. ** in. Otherwise, use the normal shared-memory.
  42317. */
  42318. static int pagerOpenWal(Pager *pPager){
  42319. int rc = SQLITE_OK;
  42320. assert( pPager->pWal==0 && pPager->tempFile==0 );
  42321. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  42322. /* If the pager is already in exclusive-mode, the WAL module will use
  42323. ** heap-memory for the wal-index instead of the VFS shared-memory
  42324. ** implementation. Take the exclusive lock now, before opening the WAL
  42325. ** file, to make sure this is safe.
  42326. */
  42327. if( pPager->exclusiveMode ){
  42328. rc = pagerExclusiveLock(pPager);
  42329. }
  42330. /* Open the connection to the log file. If this operation fails,
  42331. ** (e.g. due to malloc() failure), return an error code.
  42332. */
  42333. if( rc==SQLITE_OK ){
  42334. rc = sqlite3WalOpen(pPager->pVfs,
  42335. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  42336. pPager->journalSizeLimit, &pPager->pWal
  42337. );
  42338. }
  42339. pagerFixMaplimit(pPager);
  42340. return rc;
  42341. }
  42342. /*
  42343. ** The caller must be holding a SHARED lock on the database file to call
  42344. ** this function.
  42345. **
  42346. ** If the pager passed as the first argument is open on a real database
  42347. ** file (not a temp file or an in-memory database), and the WAL file
  42348. ** is not already open, make an attempt to open it now. If successful,
  42349. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  42350. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  42351. ** not modified in either case.
  42352. **
  42353. ** If the pager is open on a temp-file (or in-memory database), or if
  42354. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  42355. ** without doing anything.
  42356. */
  42357. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  42358. Pager *pPager, /* Pager object */
  42359. int *pbOpen /* OUT: Set to true if call is a no-op */
  42360. ){
  42361. int rc = SQLITE_OK; /* Return code */
  42362. assert( assert_pager_state(pPager) );
  42363. assert( pPager->eState==PAGER_OPEN || pbOpen );
  42364. assert( pPager->eState==PAGER_READER || !pbOpen );
  42365. assert( pbOpen==0 || *pbOpen==0 );
  42366. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  42367. if( !pPager->tempFile && !pPager->pWal ){
  42368. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  42369. /* Close any rollback journal previously open */
  42370. sqlite3OsClose(pPager->jfd);
  42371. rc = pagerOpenWal(pPager);
  42372. if( rc==SQLITE_OK ){
  42373. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  42374. pPager->eState = PAGER_OPEN;
  42375. }
  42376. }else{
  42377. *pbOpen = 1;
  42378. }
  42379. return rc;
  42380. }
  42381. /*
  42382. ** This function is called to close the connection to the log file prior
  42383. ** to switching from WAL to rollback mode.
  42384. **
  42385. ** Before closing the log file, this function attempts to take an
  42386. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  42387. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  42388. ** If successful, the EXCLUSIVE lock is not released before returning.
  42389. */
  42390. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  42391. int rc = SQLITE_OK;
  42392. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  42393. /* If the log file is not already open, but does exist in the file-system,
  42394. ** it may need to be checkpointed before the connection can switch to
  42395. ** rollback mode. Open it now so this can happen.
  42396. */
  42397. if( !pPager->pWal ){
  42398. int logexists = 0;
  42399. rc = pagerLockDb(pPager, SHARED_LOCK);
  42400. if( rc==SQLITE_OK ){
  42401. rc = sqlite3OsAccess(
  42402. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  42403. );
  42404. }
  42405. if( rc==SQLITE_OK && logexists ){
  42406. rc = pagerOpenWal(pPager);
  42407. }
  42408. }
  42409. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  42410. ** the database file, the log and log-summary files will be deleted.
  42411. */
  42412. if( rc==SQLITE_OK && pPager->pWal ){
  42413. rc = pagerExclusiveLock(pPager);
  42414. if( rc==SQLITE_OK ){
  42415. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  42416. pPager->pageSize, (u8*)pPager->pTmpSpace);
  42417. pPager->pWal = 0;
  42418. pagerFixMaplimit(pPager);
  42419. }
  42420. }
  42421. return rc;
  42422. }
  42423. #endif /* !SQLITE_OMIT_WAL */
  42424. #ifdef SQLITE_ENABLE_ZIPVFS
  42425. /*
  42426. ** A read-lock must be held on the pager when this function is called. If
  42427. ** the pager is in WAL mode and the WAL file currently contains one or more
  42428. ** frames, return the size in bytes of the page images stored within the
  42429. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  42430. ** is empty, return 0.
  42431. */
  42432. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  42433. assert( pPager->eState==PAGER_READER );
  42434. return sqlite3WalFramesize(pPager->pWal);
  42435. }
  42436. #endif
  42437. #ifdef SQLITE_HAS_CODEC
  42438. /*
  42439. ** This function is called by the wal module when writing page content
  42440. ** into the log file.
  42441. **
  42442. ** This function returns a pointer to a buffer containing the encrypted
  42443. ** page content. If a malloc fails, this function may return NULL.
  42444. */
  42445. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  42446. void *aData = 0;
  42447. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  42448. return aData;
  42449. }
  42450. #endif /* SQLITE_HAS_CODEC */
  42451. #endif /* SQLITE_OMIT_DISKIO */
  42452. /************** End of pager.c ***********************************************/
  42453. /************** Begin file wal.c *********************************************/
  42454. /*
  42455. ** 2010 February 1
  42456. **
  42457. ** The author disclaims copyright to this source code. In place of
  42458. ** a legal notice, here is a blessing:
  42459. **
  42460. ** May you do good and not evil.
  42461. ** May you find forgiveness for yourself and forgive others.
  42462. ** May you share freely, never taking more than you give.
  42463. **
  42464. *************************************************************************
  42465. **
  42466. ** This file contains the implementation of a write-ahead log (WAL) used in
  42467. ** "journal_mode=WAL" mode.
  42468. **
  42469. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  42470. **
  42471. ** A WAL file consists of a header followed by zero or more "frames".
  42472. ** Each frame records the revised content of a single page from the
  42473. ** database file. All changes to the database are recorded by writing
  42474. ** frames into the WAL. Transactions commit when a frame is written that
  42475. ** contains a commit marker. A single WAL can and usually does record
  42476. ** multiple transactions. Periodically, the content of the WAL is
  42477. ** transferred back into the database file in an operation called a
  42478. ** "checkpoint".
  42479. **
  42480. ** A single WAL file can be used multiple times. In other words, the
  42481. ** WAL can fill up with frames and then be checkpointed and then new
  42482. ** frames can overwrite the old ones. A WAL always grows from beginning
  42483. ** toward the end. Checksums and counters attached to each frame are
  42484. ** used to determine which frames within the WAL are valid and which
  42485. ** are leftovers from prior checkpoints.
  42486. **
  42487. ** The WAL header is 32 bytes in size and consists of the following eight
  42488. ** big-endian 32-bit unsigned integer values:
  42489. **
  42490. ** 0: Magic number. 0x377f0682 or 0x377f0683
  42491. ** 4: File format version. Currently 3007000
  42492. ** 8: Database page size. Example: 1024
  42493. ** 12: Checkpoint sequence number
  42494. ** 16: Salt-1, random integer incremented with each checkpoint
  42495. ** 20: Salt-2, a different random integer changing with each ckpt
  42496. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  42497. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  42498. **
  42499. ** Immediately following the wal-header are zero or more frames. Each
  42500. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  42501. ** of page data. The frame-header is six big-endian 32-bit unsigned
  42502. ** integer values, as follows:
  42503. **
  42504. ** 0: Page number.
  42505. ** 4: For commit records, the size of the database image in pages
  42506. ** after the commit. For all other records, zero.
  42507. ** 8: Salt-1 (copied from the header)
  42508. ** 12: Salt-2 (copied from the header)
  42509. ** 16: Checksum-1.
  42510. ** 20: Checksum-2.
  42511. **
  42512. ** A frame is considered valid if and only if the following conditions are
  42513. ** true:
  42514. **
  42515. ** (1) The salt-1 and salt-2 values in the frame-header match
  42516. ** salt values in the wal-header
  42517. **
  42518. ** (2) The checksum values in the final 8 bytes of the frame-header
  42519. ** exactly match the checksum computed consecutively on the
  42520. ** WAL header and the first 8 bytes and the content of all frames
  42521. ** up to and including the current frame.
  42522. **
  42523. ** The checksum is computed using 32-bit big-endian integers if the
  42524. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  42525. ** is computed using little-endian if the magic number is 0x377f0682.
  42526. ** The checksum values are always stored in the frame header in a
  42527. ** big-endian format regardless of which byte order is used to compute
  42528. ** the checksum. The checksum is computed by interpreting the input as
  42529. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  42530. ** algorithm used for the checksum is as follows:
  42531. **
  42532. ** for i from 0 to n-1 step 2:
  42533. ** s0 += x[i] + s1;
  42534. ** s1 += x[i+1] + s0;
  42535. ** endfor
  42536. **
  42537. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  42538. ** in reverse order (the largest fibonacci weight occurs on the first element
  42539. ** of the sequence being summed.) The s1 value spans all 32-bit
  42540. ** terms of the sequence whereas s0 omits the final term.
  42541. **
  42542. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  42543. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  42544. ** The VFS.xSync operations serve as write barriers - all writes launched
  42545. ** before the xSync must complete before any write that launches after the
  42546. ** xSync begins.
  42547. **
  42548. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  42549. ** value is randomized. This prevents old and new frames in the WAL from
  42550. ** being considered valid at the same time and being checkpointing together
  42551. ** following a crash.
  42552. **
  42553. ** READER ALGORITHM
  42554. **
  42555. ** To read a page from the database (call it page number P), a reader
  42556. ** first checks the WAL to see if it contains page P. If so, then the
  42557. ** last valid instance of page P that is a followed by a commit frame
  42558. ** or is a commit frame itself becomes the value read. If the WAL
  42559. ** contains no copies of page P that are valid and which are a commit
  42560. ** frame or are followed by a commit frame, then page P is read from
  42561. ** the database file.
  42562. **
  42563. ** To start a read transaction, the reader records the index of the last
  42564. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  42565. ** for all subsequent read operations. New transactions can be appended
  42566. ** to the WAL, but as long as the reader uses its original mxFrame value
  42567. ** and ignores the newly appended content, it will see a consistent snapshot
  42568. ** of the database from a single point in time. This technique allows
  42569. ** multiple concurrent readers to view different versions of the database
  42570. ** content simultaneously.
  42571. **
  42572. ** The reader algorithm in the previous paragraphs works correctly, but
  42573. ** because frames for page P can appear anywhere within the WAL, the
  42574. ** reader has to scan the entire WAL looking for page P frames. If the
  42575. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  42576. ** and read performance suffers. To overcome this problem, a separate
  42577. ** data structure called the wal-index is maintained to expedite the
  42578. ** search for frames of a particular page.
  42579. **
  42580. ** WAL-INDEX FORMAT
  42581. **
  42582. ** Conceptually, the wal-index is shared memory, though VFS implementations
  42583. ** might choose to implement the wal-index using a mmapped file. Because
  42584. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  42585. ** on a network filesystem. All users of the database must be able to
  42586. ** share memory.
  42587. **
  42588. ** The wal-index is transient. After a crash, the wal-index can (and should
  42589. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  42590. ** to either truncate or zero the header of the wal-index when the last
  42591. ** connection to it closes. Because the wal-index is transient, it can
  42592. ** use an architecture-specific format; it does not have to be cross-platform.
  42593. ** Hence, unlike the database and WAL file formats which store all values
  42594. ** as big endian, the wal-index can store multi-byte values in the native
  42595. ** byte order of the host computer.
  42596. **
  42597. ** The purpose of the wal-index is to answer this question quickly: Given
  42598. ** a page number P and a maximum frame index M, return the index of the
  42599. ** last frame in the wal before frame M for page P in the WAL, or return
  42600. ** NULL if there are no frames for page P in the WAL prior to M.
  42601. **
  42602. ** The wal-index consists of a header region, followed by an one or
  42603. ** more index blocks.
  42604. **
  42605. ** The wal-index header contains the total number of frames within the WAL
  42606. ** in the mxFrame field.
  42607. **
  42608. ** Each index block except for the first contains information on
  42609. ** HASHTABLE_NPAGE frames. The first index block contains information on
  42610. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  42611. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  42612. ** first index block are the same size as all other index blocks in the
  42613. ** wal-index.
  42614. **
  42615. ** Each index block contains two sections, a page-mapping that contains the
  42616. ** database page number associated with each wal frame, and a hash-table
  42617. ** that allows readers to query an index block for a specific page number.
  42618. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  42619. ** for the first index block) 32-bit page numbers. The first entry in the
  42620. ** first index-block contains the database page number corresponding to the
  42621. ** first frame in the WAL file. The first entry in the second index block
  42622. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  42623. ** the log, and so on.
  42624. **
  42625. ** The last index block in a wal-index usually contains less than the full
  42626. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  42627. ** depending on the contents of the WAL file. This does not change the
  42628. ** allocated size of the page-mapping array - the page-mapping array merely
  42629. ** contains unused entries.
  42630. **
  42631. ** Even without using the hash table, the last frame for page P
  42632. ** can be found by scanning the page-mapping sections of each index block
  42633. ** starting with the last index block and moving toward the first, and
  42634. ** within each index block, starting at the end and moving toward the
  42635. ** beginning. The first entry that equals P corresponds to the frame
  42636. ** holding the content for that page.
  42637. **
  42638. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  42639. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  42640. ** hash table for each page number in the mapping section, so the hash
  42641. ** table is never more than half full. The expected number of collisions
  42642. ** prior to finding a match is 1. Each entry of the hash table is an
  42643. ** 1-based index of an entry in the mapping section of the same
  42644. ** index block. Let K be the 1-based index of the largest entry in
  42645. ** the mapping section. (For index blocks other than the last, K will
  42646. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  42647. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  42648. ** contain a value of 0.
  42649. **
  42650. ** To look for page P in the hash table, first compute a hash iKey on
  42651. ** P as follows:
  42652. **
  42653. ** iKey = (P * 383) % HASHTABLE_NSLOT
  42654. **
  42655. ** Then start scanning entries of the hash table, starting with iKey
  42656. ** (wrapping around to the beginning when the end of the hash table is
  42657. ** reached) until an unused hash slot is found. Let the first unused slot
  42658. ** be at index iUnused. (iUnused might be less than iKey if there was
  42659. ** wrap-around.) Because the hash table is never more than half full,
  42660. ** the search is guaranteed to eventually hit an unused entry. Let
  42661. ** iMax be the value between iKey and iUnused, closest to iUnused,
  42662. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  42663. ** no hash slot such that aHash[i]==p) then page P is not in the
  42664. ** current index block. Otherwise the iMax-th mapping entry of the
  42665. ** current index block corresponds to the last entry that references
  42666. ** page P.
  42667. **
  42668. ** A hash search begins with the last index block and moves toward the
  42669. ** first index block, looking for entries corresponding to page P. On
  42670. ** average, only two or three slots in each index block need to be
  42671. ** examined in order to either find the last entry for page P, or to
  42672. ** establish that no such entry exists in the block. Each index block
  42673. ** holds over 4000 entries. So two or three index blocks are sufficient
  42674. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  42675. ** comparisons (on average) suffice to either locate a frame in the
  42676. ** WAL or to establish that the frame does not exist in the WAL. This
  42677. ** is much faster than scanning the entire 10MB WAL.
  42678. **
  42679. ** Note that entries are added in order of increasing K. Hence, one
  42680. ** reader might be using some value K0 and a second reader that started
  42681. ** at a later time (after additional transactions were added to the WAL
  42682. ** and to the wal-index) might be using a different value K1, where K1>K0.
  42683. ** Both readers can use the same hash table and mapping section to get
  42684. ** the correct result. There may be entries in the hash table with
  42685. ** K>K0 but to the first reader, those entries will appear to be unused
  42686. ** slots in the hash table and so the first reader will get an answer as
  42687. ** if no values greater than K0 had ever been inserted into the hash table
  42688. ** in the first place - which is what reader one wants. Meanwhile, the
  42689. ** second reader using K1 will see additional values that were inserted
  42690. ** later, which is exactly what reader two wants.
  42691. **
  42692. ** When a rollback occurs, the value of K is decreased. Hash table entries
  42693. ** that correspond to frames greater than the new K value are removed
  42694. ** from the hash table at this point.
  42695. */
  42696. #ifndef SQLITE_OMIT_WAL
  42697. /*
  42698. ** Trace output macros
  42699. */
  42700. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  42701. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  42702. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  42703. #else
  42704. # define WALTRACE(X)
  42705. #endif
  42706. /*
  42707. ** The maximum (and only) versions of the wal and wal-index formats
  42708. ** that may be interpreted by this version of SQLite.
  42709. **
  42710. ** If a client begins recovering a WAL file and finds that (a) the checksum
  42711. ** values in the wal-header are correct and (b) the version field is not
  42712. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  42713. **
  42714. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  42715. ** checksum test is successful) and finds that the version field is not
  42716. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  42717. ** returns SQLITE_CANTOPEN.
  42718. */
  42719. #define WAL_MAX_VERSION 3007000
  42720. #define WALINDEX_MAX_VERSION 3007000
  42721. /*
  42722. ** Indices of various locking bytes. WAL_NREADER is the number
  42723. ** of available reader locks and should be at least 3.
  42724. */
  42725. #define WAL_WRITE_LOCK 0
  42726. #define WAL_ALL_BUT_WRITE 1
  42727. #define WAL_CKPT_LOCK 1
  42728. #define WAL_RECOVER_LOCK 2
  42729. #define WAL_READ_LOCK(I) (3+(I))
  42730. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  42731. /* Object declarations */
  42732. typedef struct WalIndexHdr WalIndexHdr;
  42733. typedef struct WalIterator WalIterator;
  42734. typedef struct WalCkptInfo WalCkptInfo;
  42735. /*
  42736. ** The following object holds a copy of the wal-index header content.
  42737. **
  42738. ** The actual header in the wal-index consists of two copies of this
  42739. ** object.
  42740. **
  42741. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  42742. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  42743. ** added in 3.7.1 when support for 64K pages was added.
  42744. */
  42745. struct WalIndexHdr {
  42746. u32 iVersion; /* Wal-index version */
  42747. u32 unused; /* Unused (padding) field */
  42748. u32 iChange; /* Counter incremented each transaction */
  42749. u8 isInit; /* 1 when initialized */
  42750. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  42751. u16 szPage; /* Database page size in bytes. 1==64K */
  42752. u32 mxFrame; /* Index of last valid frame in the WAL */
  42753. u32 nPage; /* Size of database in pages */
  42754. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  42755. u32 aSalt[2]; /* Two salt values copied from WAL header */
  42756. u32 aCksum[2]; /* Checksum over all prior fields */
  42757. };
  42758. /*
  42759. ** A copy of the following object occurs in the wal-index immediately
  42760. ** following the second copy of the WalIndexHdr. This object stores
  42761. ** information used by checkpoint.
  42762. **
  42763. ** nBackfill is the number of frames in the WAL that have been written
  42764. ** back into the database. (We call the act of moving content from WAL to
  42765. ** database "backfilling".) The nBackfill number is never greater than
  42766. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  42767. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  42768. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  42769. ** mxFrame back to zero when the WAL is reset.
  42770. **
  42771. ** There is one entry in aReadMark[] for each reader lock. If a reader
  42772. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  42773. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  42774. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  42775. ** a special case; its value is never used and it exists as a place-holder
  42776. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  42777. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  42778. ** directly from the database.
  42779. **
  42780. ** The value of aReadMark[K] may only be changed by a thread that
  42781. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  42782. ** aReadMark[K] cannot changed while there is a reader is using that mark
  42783. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  42784. **
  42785. ** The checkpointer may only transfer frames from WAL to database where
  42786. ** the frame numbers are less than or equal to every aReadMark[] that is
  42787. ** in use (that is, every aReadMark[j] for which there is a corresponding
  42788. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  42789. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  42790. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  42791. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  42792. ** in the WAL has been backfilled into the database) then new readers
  42793. ** will choose aReadMark[0] which has value 0 and hence such reader will
  42794. ** get all their all content directly from the database file and ignore
  42795. ** the WAL.
  42796. **
  42797. ** Writers normally append new frames to the end of the WAL. However,
  42798. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  42799. ** written back into the database) and if no readers are using the WAL
  42800. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  42801. ** the writer will first "reset" the WAL back to the beginning and start
  42802. ** writing new content beginning at frame 1.
  42803. **
  42804. ** We assume that 32-bit loads are atomic and so no locks are needed in
  42805. ** order to read from any aReadMark[] entries.
  42806. */
  42807. struct WalCkptInfo {
  42808. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  42809. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  42810. };
  42811. #define READMARK_NOT_USED 0xffffffff
  42812. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  42813. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  42814. ** only support mandatory file-locks, we do not read or write data
  42815. ** from the region of the file on which locks are applied.
  42816. */
  42817. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  42818. #define WALINDEX_LOCK_RESERVED 16
  42819. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  42820. /* Size of header before each frame in wal */
  42821. #define WAL_FRAME_HDRSIZE 24
  42822. /* Size of write ahead log header, including checksum. */
  42823. /* #define WAL_HDRSIZE 24 */
  42824. #define WAL_HDRSIZE 32
  42825. /* WAL magic value. Either this value, or the same value with the least
  42826. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  42827. ** big-endian format in the first 4 bytes of a WAL file.
  42828. **
  42829. ** If the LSB is set, then the checksums for each frame within the WAL
  42830. ** file are calculated by treating all data as an array of 32-bit
  42831. ** big-endian words. Otherwise, they are calculated by interpreting
  42832. ** all data as 32-bit little-endian words.
  42833. */
  42834. #define WAL_MAGIC 0x377f0682
  42835. /*
  42836. ** Return the offset of frame iFrame in the write-ahead log file,
  42837. ** assuming a database page size of szPage bytes. The offset returned
  42838. ** is to the start of the write-ahead log frame-header.
  42839. */
  42840. #define walFrameOffset(iFrame, szPage) ( \
  42841. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  42842. )
  42843. /*
  42844. ** An open write-ahead log file is represented by an instance of the
  42845. ** following object.
  42846. */
  42847. struct Wal {
  42848. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  42849. sqlite3_file *pDbFd; /* File handle for the database file */
  42850. sqlite3_file *pWalFd; /* File handle for WAL file */
  42851. u32 iCallback; /* Value to pass to log callback (or 0) */
  42852. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  42853. int nWiData; /* Size of array apWiData */
  42854. int szFirstBlock; /* Size of first block written to WAL file */
  42855. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  42856. u32 szPage; /* Database page size */
  42857. i16 readLock; /* Which read lock is being held. -1 for none */
  42858. u8 syncFlags; /* Flags to use to sync header writes */
  42859. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  42860. u8 writeLock; /* True if in a write transaction */
  42861. u8 ckptLock; /* True if holding a checkpoint lock */
  42862. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  42863. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  42864. u8 syncHeader; /* Fsync the WAL header if true */
  42865. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  42866. WalIndexHdr hdr; /* Wal-index header for current transaction */
  42867. const char *zWalName; /* Name of WAL file */
  42868. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  42869. #ifdef SQLITE_DEBUG
  42870. u8 lockError; /* True if a locking error has occurred */
  42871. #endif
  42872. };
  42873. /*
  42874. ** Candidate values for Wal.exclusiveMode.
  42875. */
  42876. #define WAL_NORMAL_MODE 0
  42877. #define WAL_EXCLUSIVE_MODE 1
  42878. #define WAL_HEAPMEMORY_MODE 2
  42879. /*
  42880. ** Possible values for WAL.readOnly
  42881. */
  42882. #define WAL_RDWR 0 /* Normal read/write connection */
  42883. #define WAL_RDONLY 1 /* The WAL file is readonly */
  42884. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  42885. /*
  42886. ** Each page of the wal-index mapping contains a hash-table made up of
  42887. ** an array of HASHTABLE_NSLOT elements of the following type.
  42888. */
  42889. typedef u16 ht_slot;
  42890. /*
  42891. ** This structure is used to implement an iterator that loops through
  42892. ** all frames in the WAL in database page order. Where two or more frames
  42893. ** correspond to the same database page, the iterator visits only the
  42894. ** frame most recently written to the WAL (in other words, the frame with
  42895. ** the largest index).
  42896. **
  42897. ** The internals of this structure are only accessed by:
  42898. **
  42899. ** walIteratorInit() - Create a new iterator,
  42900. ** walIteratorNext() - Step an iterator,
  42901. ** walIteratorFree() - Free an iterator.
  42902. **
  42903. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  42904. */
  42905. struct WalIterator {
  42906. int iPrior; /* Last result returned from the iterator */
  42907. int nSegment; /* Number of entries in aSegment[] */
  42908. struct WalSegment {
  42909. int iNext; /* Next slot in aIndex[] not yet returned */
  42910. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  42911. u32 *aPgno; /* Array of page numbers. */
  42912. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  42913. int iZero; /* Frame number associated with aPgno[0] */
  42914. } aSegment[1]; /* One for every 32KB page in the wal-index */
  42915. };
  42916. /*
  42917. ** Define the parameters of the hash tables in the wal-index file. There
  42918. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  42919. ** wal-index.
  42920. **
  42921. ** Changing any of these constants will alter the wal-index format and
  42922. ** create incompatibilities.
  42923. */
  42924. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  42925. #define HASHTABLE_HASH_1 383 /* Should be prime */
  42926. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  42927. /*
  42928. ** The block of page numbers associated with the first hash-table in a
  42929. ** wal-index is smaller than usual. This is so that there is a complete
  42930. ** hash-table on each aligned 32KB page of the wal-index.
  42931. */
  42932. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  42933. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  42934. #define WALINDEX_PGSZ ( \
  42935. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  42936. )
  42937. /*
  42938. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  42939. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  42940. ** numbered from zero.
  42941. **
  42942. ** If this call is successful, *ppPage is set to point to the wal-index
  42943. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  42944. ** then an SQLite error code is returned and *ppPage is set to 0.
  42945. */
  42946. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  42947. int rc = SQLITE_OK;
  42948. /* Enlarge the pWal->apWiData[] array if required */
  42949. if( pWal->nWiData<=iPage ){
  42950. int nByte = sizeof(u32*)*(iPage+1);
  42951. volatile u32 **apNew;
  42952. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  42953. if( !apNew ){
  42954. *ppPage = 0;
  42955. return SQLITE_NOMEM;
  42956. }
  42957. memset((void*)&apNew[pWal->nWiData], 0,
  42958. sizeof(u32*)*(iPage+1-pWal->nWiData));
  42959. pWal->apWiData = apNew;
  42960. pWal->nWiData = iPage+1;
  42961. }
  42962. /* Request a pointer to the required page from the VFS */
  42963. if( pWal->apWiData[iPage]==0 ){
  42964. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  42965. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  42966. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  42967. }else{
  42968. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  42969. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  42970. );
  42971. if( rc==SQLITE_READONLY ){
  42972. pWal->readOnly |= WAL_SHM_RDONLY;
  42973. rc = SQLITE_OK;
  42974. }
  42975. }
  42976. }
  42977. *ppPage = pWal->apWiData[iPage];
  42978. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  42979. return rc;
  42980. }
  42981. /*
  42982. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  42983. */
  42984. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  42985. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  42986. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  42987. }
  42988. /*
  42989. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  42990. */
  42991. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  42992. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  42993. return (volatile WalIndexHdr*)pWal->apWiData[0];
  42994. }
  42995. /*
  42996. ** The argument to this macro must be of type u32. On a little-endian
  42997. ** architecture, it returns the u32 value that results from interpreting
  42998. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  42999. ** returns the value that would be produced by intepreting the 4 bytes
  43000. ** of the input value as a little-endian integer.
  43001. */
  43002. #define BYTESWAP32(x) ( \
  43003. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  43004. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  43005. )
  43006. /*
  43007. ** Generate or extend an 8 byte checksum based on the data in
  43008. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  43009. ** initial values of 0 and 0 if aIn==NULL).
  43010. **
  43011. ** The checksum is written back into aOut[] before returning.
  43012. **
  43013. ** nByte must be a positive multiple of 8.
  43014. */
  43015. static void walChecksumBytes(
  43016. int nativeCksum, /* True for native byte-order, false for non-native */
  43017. u8 *a, /* Content to be checksummed */
  43018. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  43019. const u32 *aIn, /* Initial checksum value input */
  43020. u32 *aOut /* OUT: Final checksum value output */
  43021. ){
  43022. u32 s1, s2;
  43023. u32 *aData = (u32 *)a;
  43024. u32 *aEnd = (u32 *)&a[nByte];
  43025. if( aIn ){
  43026. s1 = aIn[0];
  43027. s2 = aIn[1];
  43028. }else{
  43029. s1 = s2 = 0;
  43030. }
  43031. assert( nByte>=8 );
  43032. assert( (nByte&0x00000007)==0 );
  43033. if( nativeCksum ){
  43034. do {
  43035. s1 += *aData++ + s2;
  43036. s2 += *aData++ + s1;
  43037. }while( aData<aEnd );
  43038. }else{
  43039. do {
  43040. s1 += BYTESWAP32(aData[0]) + s2;
  43041. s2 += BYTESWAP32(aData[1]) + s1;
  43042. aData += 2;
  43043. }while( aData<aEnd );
  43044. }
  43045. aOut[0] = s1;
  43046. aOut[1] = s2;
  43047. }
  43048. static void walShmBarrier(Wal *pWal){
  43049. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  43050. sqlite3OsShmBarrier(pWal->pDbFd);
  43051. }
  43052. }
  43053. /*
  43054. ** Write the header information in pWal->hdr into the wal-index.
  43055. **
  43056. ** The checksum on pWal->hdr is updated before it is written.
  43057. */
  43058. static void walIndexWriteHdr(Wal *pWal){
  43059. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  43060. const int nCksum = offsetof(WalIndexHdr, aCksum);
  43061. assert( pWal->writeLock );
  43062. pWal->hdr.isInit = 1;
  43063. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  43064. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  43065. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  43066. walShmBarrier(pWal);
  43067. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  43068. }
  43069. /*
  43070. ** This function encodes a single frame header and writes it to a buffer
  43071. ** supplied by the caller. A frame-header is made up of a series of
  43072. ** 4-byte big-endian integers, as follows:
  43073. **
  43074. ** 0: Page number.
  43075. ** 4: For commit records, the size of the database image in pages
  43076. ** after the commit. For all other records, zero.
  43077. ** 8: Salt-1 (copied from the wal-header)
  43078. ** 12: Salt-2 (copied from the wal-header)
  43079. ** 16: Checksum-1.
  43080. ** 20: Checksum-2.
  43081. */
  43082. static void walEncodeFrame(
  43083. Wal *pWal, /* The write-ahead log */
  43084. u32 iPage, /* Database page number for frame */
  43085. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  43086. u8 *aData, /* Pointer to page data */
  43087. u8 *aFrame /* OUT: Write encoded frame here */
  43088. ){
  43089. int nativeCksum; /* True for native byte-order checksums */
  43090. u32 *aCksum = pWal->hdr.aFrameCksum;
  43091. assert( WAL_FRAME_HDRSIZE==24 );
  43092. sqlite3Put4byte(&aFrame[0], iPage);
  43093. sqlite3Put4byte(&aFrame[4], nTruncate);
  43094. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  43095. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  43096. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  43097. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  43098. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  43099. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  43100. }
  43101. /*
  43102. ** Check to see if the frame with header in aFrame[] and content
  43103. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  43104. ** *pnTruncate and return true. Return if the frame is not valid.
  43105. */
  43106. static int walDecodeFrame(
  43107. Wal *pWal, /* The write-ahead log */
  43108. u32 *piPage, /* OUT: Database page number for frame */
  43109. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  43110. u8 *aData, /* Pointer to page data (for checksum) */
  43111. u8 *aFrame /* Frame data */
  43112. ){
  43113. int nativeCksum; /* True for native byte-order checksums */
  43114. u32 *aCksum = pWal->hdr.aFrameCksum;
  43115. u32 pgno; /* Page number of the frame */
  43116. assert( WAL_FRAME_HDRSIZE==24 );
  43117. /* A frame is only valid if the salt values in the frame-header
  43118. ** match the salt values in the wal-header.
  43119. */
  43120. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  43121. return 0;
  43122. }
  43123. /* A frame is only valid if the page number is creater than zero.
  43124. */
  43125. pgno = sqlite3Get4byte(&aFrame[0]);
  43126. if( pgno==0 ){
  43127. return 0;
  43128. }
  43129. /* A frame is only valid if a checksum of the WAL header,
  43130. ** all prior frams, the first 16 bytes of this frame-header,
  43131. ** and the frame-data matches the checksum in the last 8
  43132. ** bytes of this frame-header.
  43133. */
  43134. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  43135. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  43136. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  43137. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  43138. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  43139. ){
  43140. /* Checksum failed. */
  43141. return 0;
  43142. }
  43143. /* If we reach this point, the frame is valid. Return the page number
  43144. ** and the new database size.
  43145. */
  43146. *piPage = pgno;
  43147. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  43148. return 1;
  43149. }
  43150. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  43151. /*
  43152. ** Names of locks. This routine is used to provide debugging output and is not
  43153. ** a part of an ordinary build.
  43154. */
  43155. static const char *walLockName(int lockIdx){
  43156. if( lockIdx==WAL_WRITE_LOCK ){
  43157. return "WRITE-LOCK";
  43158. }else if( lockIdx==WAL_CKPT_LOCK ){
  43159. return "CKPT-LOCK";
  43160. }else if( lockIdx==WAL_RECOVER_LOCK ){
  43161. return "RECOVER-LOCK";
  43162. }else{
  43163. static char zName[15];
  43164. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  43165. lockIdx-WAL_READ_LOCK(0));
  43166. return zName;
  43167. }
  43168. }
  43169. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  43170. /*
  43171. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  43172. ** A lock cannot be moved directly between shared and exclusive - it must go
  43173. ** through the unlocked state first.
  43174. **
  43175. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  43176. */
  43177. static int walLockShared(Wal *pWal, int lockIdx){
  43178. int rc;
  43179. if( pWal->exclusiveMode ) return SQLITE_OK;
  43180. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  43181. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  43182. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  43183. walLockName(lockIdx), rc ? "failed" : "ok"));
  43184. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  43185. return rc;
  43186. }
  43187. static void walUnlockShared(Wal *pWal, int lockIdx){
  43188. if( pWal->exclusiveMode ) return;
  43189. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  43190. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  43191. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  43192. }
  43193. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  43194. int rc;
  43195. if( pWal->exclusiveMode ) return SQLITE_OK;
  43196. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  43197. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  43198. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  43199. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  43200. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  43201. return rc;
  43202. }
  43203. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  43204. if( pWal->exclusiveMode ) return;
  43205. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  43206. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  43207. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  43208. walLockName(lockIdx), n));
  43209. }
  43210. /*
  43211. ** Compute a hash on a page number. The resulting hash value must land
  43212. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  43213. ** the hash to the next value in the event of a collision.
  43214. */
  43215. static int walHash(u32 iPage){
  43216. assert( iPage>0 );
  43217. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  43218. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  43219. }
  43220. static int walNextHash(int iPriorHash){
  43221. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  43222. }
  43223. /*
  43224. ** Return pointers to the hash table and page number array stored on
  43225. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  43226. ** numbered starting from 0.
  43227. **
  43228. ** Set output variable *paHash to point to the start of the hash table
  43229. ** in the wal-index file. Set *piZero to one less than the frame
  43230. ** number of the first frame indexed by this hash table. If a
  43231. ** slot in the hash table is set to N, it refers to frame number
  43232. ** (*piZero+N) in the log.
  43233. **
  43234. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  43235. ** first frame indexed by the hash table, frame (*piZero+1).
  43236. */
  43237. static int walHashGet(
  43238. Wal *pWal, /* WAL handle */
  43239. int iHash, /* Find the iHash'th table */
  43240. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  43241. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  43242. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  43243. ){
  43244. int rc; /* Return code */
  43245. volatile u32 *aPgno;
  43246. rc = walIndexPage(pWal, iHash, &aPgno);
  43247. assert( rc==SQLITE_OK || iHash>0 );
  43248. if( rc==SQLITE_OK ){
  43249. u32 iZero;
  43250. volatile ht_slot *aHash;
  43251. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  43252. if( iHash==0 ){
  43253. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  43254. iZero = 0;
  43255. }else{
  43256. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  43257. }
  43258. *paPgno = &aPgno[-1];
  43259. *paHash = aHash;
  43260. *piZero = iZero;
  43261. }
  43262. return rc;
  43263. }
  43264. /*
  43265. ** Return the number of the wal-index page that contains the hash-table
  43266. ** and page-number array that contain entries corresponding to WAL frame
  43267. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  43268. ** are numbered starting from 0.
  43269. */
  43270. static int walFramePage(u32 iFrame){
  43271. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  43272. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  43273. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  43274. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  43275. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  43276. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  43277. );
  43278. return iHash;
  43279. }
  43280. /*
  43281. ** Return the page number associated with frame iFrame in this WAL.
  43282. */
  43283. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  43284. int iHash = walFramePage(iFrame);
  43285. if( iHash==0 ){
  43286. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  43287. }
  43288. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  43289. }
  43290. /*
  43291. ** Remove entries from the hash table that point to WAL slots greater
  43292. ** than pWal->hdr.mxFrame.
  43293. **
  43294. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  43295. ** to a rollback or savepoint.
  43296. **
  43297. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  43298. ** updated. Any later hash tables will be automatically cleared when
  43299. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  43300. ** actually needed.
  43301. */
  43302. static void walCleanupHash(Wal *pWal){
  43303. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  43304. volatile u32 *aPgno = 0; /* Page number array for hash table */
  43305. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  43306. int iLimit = 0; /* Zero values greater than this */
  43307. int nByte; /* Number of bytes to zero in aPgno[] */
  43308. int i; /* Used to iterate through aHash[] */
  43309. assert( pWal->writeLock );
  43310. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  43311. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  43312. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  43313. if( pWal->hdr.mxFrame==0 ) return;
  43314. /* Obtain pointers to the hash-table and page-number array containing
  43315. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  43316. ** that the page said hash-table and array reside on is already mapped.
  43317. */
  43318. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  43319. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  43320. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  43321. /* Zero all hash-table entries that correspond to frame numbers greater
  43322. ** than pWal->hdr.mxFrame.
  43323. */
  43324. iLimit = pWal->hdr.mxFrame - iZero;
  43325. assert( iLimit>0 );
  43326. for(i=0; i<HASHTABLE_NSLOT; i++){
  43327. if( aHash[i]>iLimit ){
  43328. aHash[i] = 0;
  43329. }
  43330. }
  43331. /* Zero the entries in the aPgno array that correspond to frames with
  43332. ** frame numbers greater than pWal->hdr.mxFrame.
  43333. */
  43334. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  43335. memset((void *)&aPgno[iLimit+1], 0, nByte);
  43336. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  43337. /* Verify that the every entry in the mapping region is still reachable
  43338. ** via the hash table even after the cleanup.
  43339. */
  43340. if( iLimit ){
  43341. int i; /* Loop counter */
  43342. int iKey; /* Hash key */
  43343. for(i=1; i<=iLimit; i++){
  43344. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  43345. if( aHash[iKey]==i ) break;
  43346. }
  43347. assert( aHash[iKey]==i );
  43348. }
  43349. }
  43350. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  43351. }
  43352. /*
  43353. ** Set an entry in the wal-index that will map database page number
  43354. ** pPage into WAL frame iFrame.
  43355. */
  43356. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  43357. int rc; /* Return code */
  43358. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  43359. volatile u32 *aPgno = 0; /* Page number array */
  43360. volatile ht_slot *aHash = 0; /* Hash table */
  43361. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  43362. /* Assuming the wal-index file was successfully mapped, populate the
  43363. ** page number array and hash table entry.
  43364. */
  43365. if( rc==SQLITE_OK ){
  43366. int iKey; /* Hash table key */
  43367. int idx; /* Value to write to hash-table slot */
  43368. int nCollide; /* Number of hash collisions */
  43369. idx = iFrame - iZero;
  43370. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  43371. /* If this is the first entry to be added to this hash-table, zero the
  43372. ** entire hash table and aPgno[] array before proceding.
  43373. */
  43374. if( idx==1 ){
  43375. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  43376. memset((void*)&aPgno[1], 0, nByte);
  43377. }
  43378. /* If the entry in aPgno[] is already set, then the previous writer
  43379. ** must have exited unexpectedly in the middle of a transaction (after
  43380. ** writing one or more dirty pages to the WAL to free up memory).
  43381. ** Remove the remnants of that writers uncommitted transaction from
  43382. ** the hash-table before writing any new entries.
  43383. */
  43384. if( aPgno[idx] ){
  43385. walCleanupHash(pWal);
  43386. assert( !aPgno[idx] );
  43387. }
  43388. /* Write the aPgno[] array entry and the hash-table slot. */
  43389. nCollide = idx;
  43390. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  43391. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  43392. }
  43393. aPgno[idx] = iPage;
  43394. aHash[iKey] = (ht_slot)idx;
  43395. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  43396. /* Verify that the number of entries in the hash table exactly equals
  43397. ** the number of entries in the mapping region.
  43398. */
  43399. {
  43400. int i; /* Loop counter */
  43401. int nEntry = 0; /* Number of entries in the hash table */
  43402. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  43403. assert( nEntry==idx );
  43404. }
  43405. /* Verify that the every entry in the mapping region is reachable
  43406. ** via the hash table. This turns out to be a really, really expensive
  43407. ** thing to check, so only do this occasionally - not on every
  43408. ** iteration.
  43409. */
  43410. if( (idx&0x3ff)==0 ){
  43411. int i; /* Loop counter */
  43412. for(i=1; i<=idx; i++){
  43413. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  43414. if( aHash[iKey]==i ) break;
  43415. }
  43416. assert( aHash[iKey]==i );
  43417. }
  43418. }
  43419. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  43420. }
  43421. return rc;
  43422. }
  43423. /*
  43424. ** Recover the wal-index by reading the write-ahead log file.
  43425. **
  43426. ** This routine first tries to establish an exclusive lock on the
  43427. ** wal-index to prevent other threads/processes from doing anything
  43428. ** with the WAL or wal-index while recovery is running. The
  43429. ** WAL_RECOVER_LOCK is also held so that other threads will know
  43430. ** that this thread is running recovery. If unable to establish
  43431. ** the necessary locks, this routine returns SQLITE_BUSY.
  43432. */
  43433. static int walIndexRecover(Wal *pWal){
  43434. int rc; /* Return Code */
  43435. i64 nSize; /* Size of log file */
  43436. u32 aFrameCksum[2] = {0, 0};
  43437. int iLock; /* Lock offset to lock for checkpoint */
  43438. int nLock; /* Number of locks to hold */
  43439. /* Obtain an exclusive lock on all byte in the locking range not already
  43440. ** locked by the caller. The caller is guaranteed to have locked the
  43441. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  43442. ** If successful, the same bytes that are locked here are unlocked before
  43443. ** this function returns.
  43444. */
  43445. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  43446. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  43447. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  43448. assert( pWal->writeLock );
  43449. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  43450. nLock = SQLITE_SHM_NLOCK - iLock;
  43451. rc = walLockExclusive(pWal, iLock, nLock);
  43452. if( rc ){
  43453. return rc;
  43454. }
  43455. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  43456. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  43457. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  43458. if( rc!=SQLITE_OK ){
  43459. goto recovery_error;
  43460. }
  43461. if( nSize>WAL_HDRSIZE ){
  43462. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  43463. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  43464. int szFrame; /* Number of bytes in buffer aFrame[] */
  43465. u8 *aData; /* Pointer to data part of aFrame buffer */
  43466. int iFrame; /* Index of last frame read */
  43467. i64 iOffset; /* Next offset to read from log file */
  43468. int szPage; /* Page size according to the log */
  43469. u32 magic; /* Magic value read from WAL header */
  43470. u32 version; /* Magic value read from WAL header */
  43471. int isValid; /* True if this frame is valid */
  43472. /* Read in the WAL header. */
  43473. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  43474. if( rc!=SQLITE_OK ){
  43475. goto recovery_error;
  43476. }
  43477. /* If the database page size is not a power of two, or is greater than
  43478. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  43479. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  43480. ** WAL file.
  43481. */
  43482. magic = sqlite3Get4byte(&aBuf[0]);
  43483. szPage = sqlite3Get4byte(&aBuf[8]);
  43484. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  43485. || szPage&(szPage-1)
  43486. || szPage>SQLITE_MAX_PAGE_SIZE
  43487. || szPage<512
  43488. ){
  43489. goto finished;
  43490. }
  43491. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  43492. pWal->szPage = szPage;
  43493. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  43494. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  43495. /* Verify that the WAL header checksum is correct */
  43496. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  43497. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  43498. );
  43499. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  43500. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  43501. ){
  43502. goto finished;
  43503. }
  43504. /* Verify that the version number on the WAL format is one that
  43505. ** are able to understand */
  43506. version = sqlite3Get4byte(&aBuf[4]);
  43507. if( version!=WAL_MAX_VERSION ){
  43508. rc = SQLITE_CANTOPEN_BKPT;
  43509. goto finished;
  43510. }
  43511. /* Malloc a buffer to read frames into. */
  43512. szFrame = szPage + WAL_FRAME_HDRSIZE;
  43513. aFrame = (u8 *)sqlite3_malloc(szFrame);
  43514. if( !aFrame ){
  43515. rc = SQLITE_NOMEM;
  43516. goto recovery_error;
  43517. }
  43518. aData = &aFrame[WAL_FRAME_HDRSIZE];
  43519. /* Read all frames from the log file. */
  43520. iFrame = 0;
  43521. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  43522. u32 pgno; /* Database page number for frame */
  43523. u32 nTruncate; /* dbsize field from frame header */
  43524. /* Read and decode the next log frame. */
  43525. iFrame++;
  43526. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  43527. if( rc!=SQLITE_OK ) break;
  43528. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  43529. if( !isValid ) break;
  43530. rc = walIndexAppend(pWal, iFrame, pgno);
  43531. if( rc!=SQLITE_OK ) break;
  43532. /* If nTruncate is non-zero, this is a commit record. */
  43533. if( nTruncate ){
  43534. pWal->hdr.mxFrame = iFrame;
  43535. pWal->hdr.nPage = nTruncate;
  43536. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  43537. testcase( szPage<=32768 );
  43538. testcase( szPage>=65536 );
  43539. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  43540. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  43541. }
  43542. }
  43543. sqlite3_free(aFrame);
  43544. }
  43545. finished:
  43546. if( rc==SQLITE_OK ){
  43547. volatile WalCkptInfo *pInfo;
  43548. int i;
  43549. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  43550. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  43551. walIndexWriteHdr(pWal);
  43552. /* Reset the checkpoint-header. This is safe because this thread is
  43553. ** currently holding locks that exclude all other readers, writers and
  43554. ** checkpointers.
  43555. */
  43556. pInfo = walCkptInfo(pWal);
  43557. pInfo->nBackfill = 0;
  43558. pInfo->aReadMark[0] = 0;
  43559. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  43560. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  43561. /* If more than one frame was recovered from the log file, report an
  43562. ** event via sqlite3_log(). This is to help with identifying performance
  43563. ** problems caused by applications routinely shutting down without
  43564. ** checkpointing the log file.
  43565. */
  43566. if( pWal->hdr.nPage ){
  43567. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  43568. "recovered %d frames from WAL file %s",
  43569. pWal->hdr.mxFrame, pWal->zWalName
  43570. );
  43571. }
  43572. }
  43573. recovery_error:
  43574. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  43575. walUnlockExclusive(pWal, iLock, nLock);
  43576. return rc;
  43577. }
  43578. /*
  43579. ** Close an open wal-index.
  43580. */
  43581. static void walIndexClose(Wal *pWal, int isDelete){
  43582. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  43583. int i;
  43584. for(i=0; i<pWal->nWiData; i++){
  43585. sqlite3_free((void *)pWal->apWiData[i]);
  43586. pWal->apWiData[i] = 0;
  43587. }
  43588. }else{
  43589. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  43590. }
  43591. }
  43592. /*
  43593. ** Open a connection to the WAL file zWalName. The database file must
  43594. ** already be opened on connection pDbFd. The buffer that zWalName points
  43595. ** to must remain valid for the lifetime of the returned Wal* handle.
  43596. **
  43597. ** A SHARED lock should be held on the database file when this function
  43598. ** is called. The purpose of this SHARED lock is to prevent any other
  43599. ** client from unlinking the WAL or wal-index file. If another process
  43600. ** were to do this just after this client opened one of these files, the
  43601. ** system would be badly broken.
  43602. **
  43603. ** If the log file is successfully opened, SQLITE_OK is returned and
  43604. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  43605. ** an SQLite error code is returned and *ppWal is left unmodified.
  43606. */
  43607. SQLITE_PRIVATE int sqlite3WalOpen(
  43608. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  43609. sqlite3_file *pDbFd, /* The open database file */
  43610. const char *zWalName, /* Name of the WAL file */
  43611. int bNoShm, /* True to run in heap-memory mode */
  43612. i64 mxWalSize, /* Truncate WAL to this size on reset */
  43613. Wal **ppWal /* OUT: Allocated Wal handle */
  43614. ){
  43615. int rc; /* Return Code */
  43616. Wal *pRet; /* Object to allocate and return */
  43617. int flags; /* Flags passed to OsOpen() */
  43618. assert( zWalName && zWalName[0] );
  43619. assert( pDbFd );
  43620. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  43621. ** this source file. Verify that the #defines of the locking byte offsets
  43622. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  43623. */
  43624. #ifdef WIN_SHM_BASE
  43625. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  43626. #endif
  43627. #ifdef UNIX_SHM_BASE
  43628. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  43629. #endif
  43630. /* Allocate an instance of struct Wal to return. */
  43631. *ppWal = 0;
  43632. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  43633. if( !pRet ){
  43634. return SQLITE_NOMEM;
  43635. }
  43636. pRet->pVfs = pVfs;
  43637. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  43638. pRet->pDbFd = pDbFd;
  43639. pRet->readLock = -1;
  43640. pRet->mxWalSize = mxWalSize;
  43641. pRet->zWalName = zWalName;
  43642. pRet->syncHeader = 1;
  43643. pRet->padToSectorBoundary = 1;
  43644. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  43645. /* Open file handle on the write-ahead log file. */
  43646. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  43647. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  43648. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  43649. pRet->readOnly = WAL_RDONLY;
  43650. }
  43651. if( rc!=SQLITE_OK ){
  43652. walIndexClose(pRet, 0);
  43653. sqlite3OsClose(pRet->pWalFd);
  43654. sqlite3_free(pRet);
  43655. }else{
  43656. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  43657. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  43658. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  43659. pRet->padToSectorBoundary = 0;
  43660. }
  43661. *ppWal = pRet;
  43662. WALTRACE(("WAL%d: opened\n", pRet));
  43663. }
  43664. return rc;
  43665. }
  43666. /*
  43667. ** Change the size to which the WAL file is trucated on each reset.
  43668. */
  43669. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  43670. if( pWal ) pWal->mxWalSize = iLimit;
  43671. }
  43672. /*
  43673. ** Find the smallest page number out of all pages held in the WAL that
  43674. ** has not been returned by any prior invocation of this method on the
  43675. ** same WalIterator object. Write into *piFrame the frame index where
  43676. ** that page was last written into the WAL. Write into *piPage the page
  43677. ** number.
  43678. **
  43679. ** Return 0 on success. If there are no pages in the WAL with a page
  43680. ** number larger than *piPage, then return 1.
  43681. */
  43682. static int walIteratorNext(
  43683. WalIterator *p, /* Iterator */
  43684. u32 *piPage, /* OUT: The page number of the next page */
  43685. u32 *piFrame /* OUT: Wal frame index of next page */
  43686. ){
  43687. u32 iMin; /* Result pgno must be greater than iMin */
  43688. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  43689. int i; /* For looping through segments */
  43690. iMin = p->iPrior;
  43691. assert( iMin<0xffffffff );
  43692. for(i=p->nSegment-1; i>=0; i--){
  43693. struct WalSegment *pSegment = &p->aSegment[i];
  43694. while( pSegment->iNext<pSegment->nEntry ){
  43695. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  43696. if( iPg>iMin ){
  43697. if( iPg<iRet ){
  43698. iRet = iPg;
  43699. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  43700. }
  43701. break;
  43702. }
  43703. pSegment->iNext++;
  43704. }
  43705. }
  43706. *piPage = p->iPrior = iRet;
  43707. return (iRet==0xFFFFFFFF);
  43708. }
  43709. /*
  43710. ** This function merges two sorted lists into a single sorted list.
  43711. **
  43712. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  43713. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  43714. ** is guaranteed for all J<K:
  43715. **
  43716. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  43717. ** aContent[aRight[J]] < aContent[aRight[K]]
  43718. **
  43719. ** This routine overwrites aRight[] with a new (probably longer) sequence
  43720. ** of indices such that the aRight[] contains every index that appears in
  43721. ** either aLeft[] or the old aRight[] and such that the second condition
  43722. ** above is still met.
  43723. **
  43724. ** The aContent[aLeft[X]] values will be unique for all X. And the
  43725. ** aContent[aRight[X]] values will be unique too. But there might be
  43726. ** one or more combinations of X and Y such that
  43727. **
  43728. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  43729. **
  43730. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  43731. */
  43732. static void walMerge(
  43733. const u32 *aContent, /* Pages in wal - keys for the sort */
  43734. ht_slot *aLeft, /* IN: Left hand input list */
  43735. int nLeft, /* IN: Elements in array *paLeft */
  43736. ht_slot **paRight, /* IN/OUT: Right hand input list */
  43737. int *pnRight, /* IN/OUT: Elements in *paRight */
  43738. ht_slot *aTmp /* Temporary buffer */
  43739. ){
  43740. int iLeft = 0; /* Current index in aLeft */
  43741. int iRight = 0; /* Current index in aRight */
  43742. int iOut = 0; /* Current index in output buffer */
  43743. int nRight = *pnRight;
  43744. ht_slot *aRight = *paRight;
  43745. assert( nLeft>0 && nRight>0 );
  43746. while( iRight<nRight || iLeft<nLeft ){
  43747. ht_slot logpage;
  43748. Pgno dbpage;
  43749. if( (iLeft<nLeft)
  43750. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  43751. ){
  43752. logpage = aLeft[iLeft++];
  43753. }else{
  43754. logpage = aRight[iRight++];
  43755. }
  43756. dbpage = aContent[logpage];
  43757. aTmp[iOut++] = logpage;
  43758. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  43759. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  43760. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  43761. }
  43762. *paRight = aLeft;
  43763. *pnRight = iOut;
  43764. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  43765. }
  43766. /*
  43767. ** Sort the elements in list aList using aContent[] as the sort key.
  43768. ** Remove elements with duplicate keys, preferring to keep the
  43769. ** larger aList[] values.
  43770. **
  43771. ** The aList[] entries are indices into aContent[]. The values in
  43772. ** aList[] are to be sorted so that for all J<K:
  43773. **
  43774. ** aContent[aList[J]] < aContent[aList[K]]
  43775. **
  43776. ** For any X and Y such that
  43777. **
  43778. ** aContent[aList[X]] == aContent[aList[Y]]
  43779. **
  43780. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  43781. ** the smaller.
  43782. */
  43783. static void walMergesort(
  43784. const u32 *aContent, /* Pages in wal */
  43785. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  43786. ht_slot *aList, /* IN/OUT: List to sort */
  43787. int *pnList /* IN/OUT: Number of elements in aList[] */
  43788. ){
  43789. struct Sublist {
  43790. int nList; /* Number of elements in aList */
  43791. ht_slot *aList; /* Pointer to sub-list content */
  43792. };
  43793. const int nList = *pnList; /* Size of input list */
  43794. int nMerge = 0; /* Number of elements in list aMerge */
  43795. ht_slot *aMerge = 0; /* List to be merged */
  43796. int iList; /* Index into input list */
  43797. int iSub = 0; /* Index into aSub array */
  43798. struct Sublist aSub[13]; /* Array of sub-lists */
  43799. memset(aSub, 0, sizeof(aSub));
  43800. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  43801. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  43802. for(iList=0; iList<nList; iList++){
  43803. nMerge = 1;
  43804. aMerge = &aList[iList];
  43805. for(iSub=0; iList & (1<<iSub); iSub++){
  43806. struct Sublist *p = &aSub[iSub];
  43807. assert( p->aList && p->nList<=(1<<iSub) );
  43808. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  43809. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  43810. }
  43811. aSub[iSub].aList = aMerge;
  43812. aSub[iSub].nList = nMerge;
  43813. }
  43814. for(iSub++; iSub<ArraySize(aSub); iSub++){
  43815. if( nList & (1<<iSub) ){
  43816. struct Sublist *p = &aSub[iSub];
  43817. assert( p->nList<=(1<<iSub) );
  43818. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  43819. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  43820. }
  43821. }
  43822. assert( aMerge==aList );
  43823. *pnList = nMerge;
  43824. #ifdef SQLITE_DEBUG
  43825. {
  43826. int i;
  43827. for(i=1; i<*pnList; i++){
  43828. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  43829. }
  43830. }
  43831. #endif
  43832. }
  43833. /*
  43834. ** Free an iterator allocated by walIteratorInit().
  43835. */
  43836. static void walIteratorFree(WalIterator *p){
  43837. sqlite3ScratchFree(p);
  43838. }
  43839. /*
  43840. ** Construct a WalInterator object that can be used to loop over all
  43841. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  43842. ** lock.
  43843. **
  43844. ** On success, make *pp point to the newly allocated WalInterator object
  43845. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  43846. ** returns an error, the value of *pp is undefined.
  43847. **
  43848. ** The calling routine should invoke walIteratorFree() to destroy the
  43849. ** WalIterator object when it has finished with it.
  43850. */
  43851. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  43852. WalIterator *p; /* Return value */
  43853. int nSegment; /* Number of segments to merge */
  43854. u32 iLast; /* Last frame in log */
  43855. int nByte; /* Number of bytes to allocate */
  43856. int i; /* Iterator variable */
  43857. ht_slot *aTmp; /* Temp space used by merge-sort */
  43858. int rc = SQLITE_OK; /* Return Code */
  43859. /* This routine only runs while holding the checkpoint lock. And
  43860. ** it only runs if there is actually content in the log (mxFrame>0).
  43861. */
  43862. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  43863. iLast = pWal->hdr.mxFrame;
  43864. /* Allocate space for the WalIterator object. */
  43865. nSegment = walFramePage(iLast) + 1;
  43866. nByte = sizeof(WalIterator)
  43867. + (nSegment-1)*sizeof(struct WalSegment)
  43868. + iLast*sizeof(ht_slot);
  43869. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  43870. if( !p ){
  43871. return SQLITE_NOMEM;
  43872. }
  43873. memset(p, 0, nByte);
  43874. p->nSegment = nSegment;
  43875. /* Allocate temporary space used by the merge-sort routine. This block
  43876. ** of memory will be freed before this function returns.
  43877. */
  43878. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  43879. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  43880. );
  43881. if( !aTmp ){
  43882. rc = SQLITE_NOMEM;
  43883. }
  43884. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  43885. volatile ht_slot *aHash;
  43886. u32 iZero;
  43887. volatile u32 *aPgno;
  43888. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  43889. if( rc==SQLITE_OK ){
  43890. int j; /* Counter variable */
  43891. int nEntry; /* Number of entries in this segment */
  43892. ht_slot *aIndex; /* Sorted index for this segment */
  43893. aPgno++;
  43894. if( (i+1)==nSegment ){
  43895. nEntry = (int)(iLast - iZero);
  43896. }else{
  43897. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  43898. }
  43899. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  43900. iZero++;
  43901. for(j=0; j<nEntry; j++){
  43902. aIndex[j] = (ht_slot)j;
  43903. }
  43904. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  43905. p->aSegment[i].iZero = iZero;
  43906. p->aSegment[i].nEntry = nEntry;
  43907. p->aSegment[i].aIndex = aIndex;
  43908. p->aSegment[i].aPgno = (u32 *)aPgno;
  43909. }
  43910. }
  43911. sqlite3ScratchFree(aTmp);
  43912. if( rc!=SQLITE_OK ){
  43913. walIteratorFree(p);
  43914. }
  43915. *pp = p;
  43916. return rc;
  43917. }
  43918. /*
  43919. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  43920. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  43921. ** busy-handler function. Invoke it and retry the lock until either the
  43922. ** lock is successfully obtained or the busy-handler returns 0.
  43923. */
  43924. static int walBusyLock(
  43925. Wal *pWal, /* WAL connection */
  43926. int (*xBusy)(void*), /* Function to call when busy */
  43927. void *pBusyArg, /* Context argument for xBusyHandler */
  43928. int lockIdx, /* Offset of first byte to lock */
  43929. int n /* Number of bytes to lock */
  43930. ){
  43931. int rc;
  43932. do {
  43933. rc = walLockExclusive(pWal, lockIdx, n);
  43934. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  43935. return rc;
  43936. }
  43937. /*
  43938. ** The cache of the wal-index header must be valid to call this function.
  43939. ** Return the page-size in bytes used by the database.
  43940. */
  43941. static int walPagesize(Wal *pWal){
  43942. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  43943. }
  43944. /*
  43945. ** Copy as much content as we can from the WAL back into the database file
  43946. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  43947. **
  43948. ** The amount of information copies from WAL to database might be limited
  43949. ** by active readers. This routine will never overwrite a database page
  43950. ** that a concurrent reader might be using.
  43951. **
  43952. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  43953. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  43954. ** checkpoints are always run by a background thread or background
  43955. ** process, foreground threads will never block on a lengthy fsync call.
  43956. **
  43957. ** Fsync is called on the WAL before writing content out of the WAL and
  43958. ** into the database. This ensures that if the new content is persistent
  43959. ** in the WAL and can be recovered following a power-loss or hard reset.
  43960. **
  43961. ** Fsync is also called on the database file if (and only if) the entire
  43962. ** WAL content is copied into the database file. This second fsync makes
  43963. ** it safe to delete the WAL since the new content will persist in the
  43964. ** database file.
  43965. **
  43966. ** This routine uses and updates the nBackfill field of the wal-index header.
  43967. ** This is the only routine tha will increase the value of nBackfill.
  43968. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  43969. ** its value.)
  43970. **
  43971. ** The caller must be holding sufficient locks to ensure that no other
  43972. ** checkpoint is running (in any other thread or process) at the same
  43973. ** time.
  43974. */
  43975. static int walCheckpoint(
  43976. Wal *pWal, /* Wal connection */
  43977. int eMode, /* One of PASSIVE, FULL or RESTART */
  43978. int (*xBusyCall)(void*), /* Function to call when busy */
  43979. void *pBusyArg, /* Context argument for xBusyHandler */
  43980. int sync_flags, /* Flags for OsSync() (or 0) */
  43981. u8 *zBuf /* Temporary buffer to use */
  43982. ){
  43983. int rc; /* Return code */
  43984. int szPage; /* Database page-size */
  43985. WalIterator *pIter = 0; /* Wal iterator context */
  43986. u32 iDbpage = 0; /* Next database page to write */
  43987. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  43988. u32 mxSafeFrame; /* Max frame that can be backfilled */
  43989. u32 mxPage; /* Max database page to write */
  43990. int i; /* Loop counter */
  43991. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  43992. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  43993. szPage = walPagesize(pWal);
  43994. testcase( szPage<=32768 );
  43995. testcase( szPage>=65536 );
  43996. pInfo = walCkptInfo(pWal);
  43997. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  43998. /* Allocate the iterator */
  43999. rc = walIteratorInit(pWal, &pIter);
  44000. if( rc!=SQLITE_OK ){
  44001. return rc;
  44002. }
  44003. assert( pIter );
  44004. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  44005. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  44006. ** safe to write into the database. Frames beyond mxSafeFrame might
  44007. ** overwrite database pages that are in use by active readers and thus
  44008. ** cannot be backfilled from the WAL.
  44009. */
  44010. mxSafeFrame = pWal->hdr.mxFrame;
  44011. mxPage = pWal->hdr.nPage;
  44012. for(i=1; i<WAL_NREADER; i++){
  44013. u32 y = pInfo->aReadMark[i];
  44014. if( mxSafeFrame>y ){
  44015. assert( y<=pWal->hdr.mxFrame );
  44016. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  44017. if( rc==SQLITE_OK ){
  44018. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  44019. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44020. }else if( rc==SQLITE_BUSY ){
  44021. mxSafeFrame = y;
  44022. xBusy = 0;
  44023. }else{
  44024. goto walcheckpoint_out;
  44025. }
  44026. }
  44027. }
  44028. if( pInfo->nBackfill<mxSafeFrame
  44029. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  44030. ){
  44031. i64 nSize; /* Current size of database file */
  44032. u32 nBackfill = pInfo->nBackfill;
  44033. /* Sync the WAL to disk */
  44034. if( sync_flags ){
  44035. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  44036. }
  44037. /* If the database may grow as a result of this checkpoint, hint
  44038. ** about the eventual size of the db file to the VFS layer.
  44039. */
  44040. if( rc==SQLITE_OK ){
  44041. i64 nReq = ((i64)mxPage * szPage);
  44042. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  44043. if( rc==SQLITE_OK && nSize<nReq ){
  44044. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  44045. }
  44046. }
  44047. /* Iterate through the contents of the WAL, copying data to the db file. */
  44048. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  44049. i64 iOffset;
  44050. assert( walFramePgno(pWal, iFrame)==iDbpage );
  44051. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  44052. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  44053. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  44054. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  44055. if( rc!=SQLITE_OK ) break;
  44056. iOffset = (iDbpage-1)*(i64)szPage;
  44057. testcase( IS_BIG_INT(iOffset) );
  44058. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  44059. if( rc!=SQLITE_OK ) break;
  44060. }
  44061. /* If work was actually accomplished... */
  44062. if( rc==SQLITE_OK ){
  44063. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  44064. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  44065. testcase( IS_BIG_INT(szDb) );
  44066. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  44067. if( rc==SQLITE_OK && sync_flags ){
  44068. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  44069. }
  44070. }
  44071. if( rc==SQLITE_OK ){
  44072. pInfo->nBackfill = mxSafeFrame;
  44073. }
  44074. }
  44075. /* Release the reader lock held while backfilling */
  44076. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  44077. }
  44078. if( rc==SQLITE_BUSY ){
  44079. /* Reset the return code so as not to report a checkpoint failure
  44080. ** just because there are active readers. */
  44081. rc = SQLITE_OK;
  44082. }
  44083. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  44084. ** file has been copied into the database file, then block until all
  44085. ** readers have finished using the wal file. This ensures that the next
  44086. ** process to write to the database restarts the wal file.
  44087. */
  44088. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  44089. assert( pWal->writeLock );
  44090. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  44091. rc = SQLITE_BUSY;
  44092. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  44093. assert( mxSafeFrame==pWal->hdr.mxFrame );
  44094. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  44095. if( rc==SQLITE_OK ){
  44096. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  44097. }
  44098. }
  44099. }
  44100. walcheckpoint_out:
  44101. walIteratorFree(pIter);
  44102. return rc;
  44103. }
  44104. /*
  44105. ** If the WAL file is currently larger than nMax bytes in size, truncate
  44106. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  44107. */
  44108. static void walLimitSize(Wal *pWal, i64 nMax){
  44109. i64 sz;
  44110. int rx;
  44111. sqlite3BeginBenignMalloc();
  44112. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  44113. if( rx==SQLITE_OK && (sz > nMax ) ){
  44114. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  44115. }
  44116. sqlite3EndBenignMalloc();
  44117. if( rx ){
  44118. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  44119. }
  44120. }
  44121. /*
  44122. ** Close a connection to a log file.
  44123. */
  44124. SQLITE_PRIVATE int sqlite3WalClose(
  44125. Wal *pWal, /* Wal to close */
  44126. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  44127. int nBuf,
  44128. u8 *zBuf /* Buffer of at least nBuf bytes */
  44129. ){
  44130. int rc = SQLITE_OK;
  44131. if( pWal ){
  44132. int isDelete = 0; /* True to unlink wal and wal-index files */
  44133. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  44134. ** ordinary, rollback-mode locking methods, this guarantees that the
  44135. ** connection associated with this log file is the only connection to
  44136. ** the database. In this case checkpoint the database and unlink both
  44137. ** the wal and wal-index files.
  44138. **
  44139. ** The EXCLUSIVE lock is not released before returning.
  44140. */
  44141. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  44142. if( rc==SQLITE_OK ){
  44143. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  44144. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  44145. }
  44146. rc = sqlite3WalCheckpoint(
  44147. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  44148. );
  44149. if( rc==SQLITE_OK ){
  44150. int bPersist = -1;
  44151. sqlite3OsFileControlHint(
  44152. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  44153. );
  44154. if( bPersist!=1 ){
  44155. /* Try to delete the WAL file if the checkpoint completed and
  44156. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  44157. ** mode (!bPersist) */
  44158. isDelete = 1;
  44159. }else if( pWal->mxWalSize>=0 ){
  44160. /* Try to truncate the WAL file to zero bytes if the checkpoint
  44161. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  44162. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  44163. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  44164. ** to zero bytes as truncating to the journal_size_limit might
  44165. ** leave a corrupt WAL file on disk. */
  44166. walLimitSize(pWal, 0);
  44167. }
  44168. }
  44169. }
  44170. walIndexClose(pWal, isDelete);
  44171. sqlite3OsClose(pWal->pWalFd);
  44172. if( isDelete ){
  44173. sqlite3BeginBenignMalloc();
  44174. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  44175. sqlite3EndBenignMalloc();
  44176. }
  44177. WALTRACE(("WAL%p: closed\n", pWal));
  44178. sqlite3_free((void *)pWal->apWiData);
  44179. sqlite3_free(pWal);
  44180. }
  44181. return rc;
  44182. }
  44183. /*
  44184. ** Try to read the wal-index header. Return 0 on success and 1 if
  44185. ** there is a problem.
  44186. **
  44187. ** The wal-index is in shared memory. Another thread or process might
  44188. ** be writing the header at the same time this procedure is trying to
  44189. ** read it, which might result in inconsistency. A dirty read is detected
  44190. ** by verifying that both copies of the header are the same and also by
  44191. ** a checksum on the header.
  44192. **
  44193. ** If and only if the read is consistent and the header is different from
  44194. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  44195. ** and *pChanged is set to 1.
  44196. **
  44197. ** If the checksum cannot be verified return non-zero. If the header
  44198. ** is read successfully and the checksum verified, return zero.
  44199. */
  44200. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  44201. u32 aCksum[2]; /* Checksum on the header content */
  44202. WalIndexHdr h1, h2; /* Two copies of the header content */
  44203. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  44204. /* The first page of the wal-index must be mapped at this point. */
  44205. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  44206. /* Read the header. This might happen concurrently with a write to the
  44207. ** same area of shared memory on a different CPU in a SMP,
  44208. ** meaning it is possible that an inconsistent snapshot is read
  44209. ** from the file. If this happens, return non-zero.
  44210. **
  44211. ** There are two copies of the header at the beginning of the wal-index.
  44212. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  44213. ** Memory barriers are used to prevent the compiler or the hardware from
  44214. ** reordering the reads and writes.
  44215. */
  44216. aHdr = walIndexHdr(pWal);
  44217. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  44218. walShmBarrier(pWal);
  44219. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  44220. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  44221. return 1; /* Dirty read */
  44222. }
  44223. if( h1.isInit==0 ){
  44224. return 1; /* Malformed header - probably all zeros */
  44225. }
  44226. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  44227. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  44228. return 1; /* Checksum does not match */
  44229. }
  44230. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  44231. *pChanged = 1;
  44232. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  44233. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  44234. testcase( pWal->szPage<=32768 );
  44235. testcase( pWal->szPage>=65536 );
  44236. }
  44237. /* The header was successfully read. Return zero. */
  44238. return 0;
  44239. }
  44240. /*
  44241. ** Read the wal-index header from the wal-index and into pWal->hdr.
  44242. ** If the wal-header appears to be corrupt, try to reconstruct the
  44243. ** wal-index from the WAL before returning.
  44244. **
  44245. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  44246. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  44247. ** to 0.
  44248. **
  44249. ** If the wal-index header is successfully read, return SQLITE_OK.
  44250. ** Otherwise an SQLite error code.
  44251. */
  44252. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  44253. int rc; /* Return code */
  44254. int badHdr; /* True if a header read failed */
  44255. volatile u32 *page0; /* Chunk of wal-index containing header */
  44256. /* Ensure that page 0 of the wal-index (the page that contains the
  44257. ** wal-index header) is mapped. Return early if an error occurs here.
  44258. */
  44259. assert( pChanged );
  44260. rc = walIndexPage(pWal, 0, &page0);
  44261. if( rc!=SQLITE_OK ){
  44262. return rc;
  44263. };
  44264. assert( page0 || pWal->writeLock==0 );
  44265. /* If the first page of the wal-index has been mapped, try to read the
  44266. ** wal-index header immediately, without holding any lock. This usually
  44267. ** works, but may fail if the wal-index header is corrupt or currently
  44268. ** being modified by another thread or process.
  44269. */
  44270. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  44271. /* If the first attempt failed, it might have been due to a race
  44272. ** with a writer. So get a WRITE lock and try again.
  44273. */
  44274. assert( badHdr==0 || pWal->writeLock==0 );
  44275. if( badHdr ){
  44276. if( pWal->readOnly & WAL_SHM_RDONLY ){
  44277. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  44278. walUnlockShared(pWal, WAL_WRITE_LOCK);
  44279. rc = SQLITE_READONLY_RECOVERY;
  44280. }
  44281. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  44282. pWal->writeLock = 1;
  44283. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  44284. badHdr = walIndexTryHdr(pWal, pChanged);
  44285. if( badHdr ){
  44286. /* If the wal-index header is still malformed even while holding
  44287. ** a WRITE lock, it can only mean that the header is corrupted and
  44288. ** needs to be reconstructed. So run recovery to do exactly that.
  44289. */
  44290. rc = walIndexRecover(pWal);
  44291. *pChanged = 1;
  44292. }
  44293. }
  44294. pWal->writeLock = 0;
  44295. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  44296. }
  44297. }
  44298. /* If the header is read successfully, check the version number to make
  44299. ** sure the wal-index was not constructed with some future format that
  44300. ** this version of SQLite cannot understand.
  44301. */
  44302. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  44303. rc = SQLITE_CANTOPEN_BKPT;
  44304. }
  44305. return rc;
  44306. }
  44307. /*
  44308. ** This is the value that walTryBeginRead returns when it needs to
  44309. ** be retried.
  44310. */
  44311. #define WAL_RETRY (-1)
  44312. /*
  44313. ** Attempt to start a read transaction. This might fail due to a race or
  44314. ** other transient condition. When that happens, it returns WAL_RETRY to
  44315. ** indicate to the caller that it is safe to retry immediately.
  44316. **
  44317. ** On success return SQLITE_OK. On a permanent failure (such an
  44318. ** I/O error or an SQLITE_BUSY because another process is running
  44319. ** recovery) return a positive error code.
  44320. **
  44321. ** The useWal parameter is true to force the use of the WAL and disable
  44322. ** the case where the WAL is bypassed because it has been completely
  44323. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  44324. ** to make a copy of the wal-index header into pWal->hdr. If the
  44325. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  44326. ** to the caller that the local paget cache is obsolete and needs to be
  44327. ** flushed.) When useWal==1, the wal-index header is assumed to already
  44328. ** be loaded and the pChanged parameter is unused.
  44329. **
  44330. ** The caller must set the cnt parameter to the number of prior calls to
  44331. ** this routine during the current read attempt that returned WAL_RETRY.
  44332. ** This routine will start taking more aggressive measures to clear the
  44333. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  44334. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  44335. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  44336. ** and is not honoring the locking protocol. There is a vanishingly small
  44337. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  44338. ** bad luck when there is lots of contention for the wal-index, but that
  44339. ** possibility is so small that it can be safely neglected, we believe.
  44340. **
  44341. ** On success, this routine obtains a read lock on
  44342. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  44343. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  44344. ** that means the Wal does not hold any read lock. The reader must not
  44345. ** access any database page that is modified by a WAL frame up to and
  44346. ** including frame number aReadMark[pWal->readLock]. The reader will
  44347. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  44348. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  44349. ** completely and get all content directly from the database file.
  44350. ** If the useWal parameter is 1 then the WAL will never be ignored and
  44351. ** this routine will always set pWal->readLock>0 on success.
  44352. ** When the read transaction is completed, the caller must release the
  44353. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  44354. **
  44355. ** This routine uses the nBackfill and aReadMark[] fields of the header
  44356. ** to select a particular WAL_READ_LOCK() that strives to let the
  44357. ** checkpoint process do as much work as possible. This routine might
  44358. ** update values of the aReadMark[] array in the header, but if it does
  44359. ** so it takes care to hold an exclusive lock on the corresponding
  44360. ** WAL_READ_LOCK() while changing values.
  44361. */
  44362. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  44363. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  44364. u32 mxReadMark; /* Largest aReadMark[] value */
  44365. int mxI; /* Index of largest aReadMark[] value */
  44366. int i; /* Loop counter */
  44367. int rc = SQLITE_OK; /* Return code */
  44368. assert( pWal->readLock<0 ); /* Not currently locked */
  44369. /* Take steps to avoid spinning forever if there is a protocol error.
  44370. **
  44371. ** Circumstances that cause a RETRY should only last for the briefest
  44372. ** instances of time. No I/O or other system calls are done while the
  44373. ** locks are held, so the locks should not be held for very long. But
  44374. ** if we are unlucky, another process that is holding a lock might get
  44375. ** paged out or take a page-fault that is time-consuming to resolve,
  44376. ** during the few nanoseconds that it is holding the lock. In that case,
  44377. ** it might take longer than normal for the lock to free.
  44378. **
  44379. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  44380. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  44381. ** is more of a scheduler yield than an actual delay. But on the 10th
  44382. ** an subsequent retries, the delays start becoming longer and longer,
  44383. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  44384. ** The total delay time before giving up is less than 1 second.
  44385. */
  44386. if( cnt>5 ){
  44387. int nDelay = 1; /* Pause time in microseconds */
  44388. if( cnt>100 ){
  44389. VVA_ONLY( pWal->lockError = 1; )
  44390. return SQLITE_PROTOCOL;
  44391. }
  44392. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  44393. sqlite3OsSleep(pWal->pVfs, nDelay);
  44394. }
  44395. if( !useWal ){
  44396. rc = walIndexReadHdr(pWal, pChanged);
  44397. if( rc==SQLITE_BUSY ){
  44398. /* If there is not a recovery running in another thread or process
  44399. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  44400. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  44401. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  44402. ** would be technically correct. But the race is benign since with
  44403. ** WAL_RETRY this routine will be called again and will probably be
  44404. ** right on the second iteration.
  44405. */
  44406. if( pWal->apWiData[0]==0 ){
  44407. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  44408. ** We assume this is a transient condition, so return WAL_RETRY. The
  44409. ** xShmMap() implementation used by the default unix and win32 VFS
  44410. ** modules may return SQLITE_BUSY due to a race condition in the
  44411. ** code that determines whether or not the shared-memory region
  44412. ** must be zeroed before the requested page is returned.
  44413. */
  44414. rc = WAL_RETRY;
  44415. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  44416. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  44417. rc = WAL_RETRY;
  44418. }else if( rc==SQLITE_BUSY ){
  44419. rc = SQLITE_BUSY_RECOVERY;
  44420. }
  44421. }
  44422. if( rc!=SQLITE_OK ){
  44423. return rc;
  44424. }
  44425. }
  44426. pInfo = walCkptInfo(pWal);
  44427. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  44428. /* The WAL has been completely backfilled (or it is empty).
  44429. ** and can be safely ignored.
  44430. */
  44431. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  44432. walShmBarrier(pWal);
  44433. if( rc==SQLITE_OK ){
  44434. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  44435. /* It is not safe to allow the reader to continue here if frames
  44436. ** may have been appended to the log before READ_LOCK(0) was obtained.
  44437. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  44438. ** which implies that the database file contains a trustworthy
  44439. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  44440. ** happening, this is usually correct.
  44441. **
  44442. ** However, if frames have been appended to the log (or if the log
  44443. ** is wrapped and written for that matter) before the READ_LOCK(0)
  44444. ** is obtained, that is not necessarily true. A checkpointer may
  44445. ** have started to backfill the appended frames but crashed before
  44446. ** it finished. Leaving a corrupt image in the database file.
  44447. */
  44448. walUnlockShared(pWal, WAL_READ_LOCK(0));
  44449. return WAL_RETRY;
  44450. }
  44451. pWal->readLock = 0;
  44452. return SQLITE_OK;
  44453. }else if( rc!=SQLITE_BUSY ){
  44454. return rc;
  44455. }
  44456. }
  44457. /* If we get this far, it means that the reader will want to use
  44458. ** the WAL to get at content from recent commits. The job now is
  44459. ** to select one of the aReadMark[] entries that is closest to
  44460. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  44461. */
  44462. mxReadMark = 0;
  44463. mxI = 0;
  44464. for(i=1; i<WAL_NREADER; i++){
  44465. u32 thisMark = pInfo->aReadMark[i];
  44466. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  44467. assert( thisMark!=READMARK_NOT_USED );
  44468. mxReadMark = thisMark;
  44469. mxI = i;
  44470. }
  44471. }
  44472. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  44473. {
  44474. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  44475. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  44476. ){
  44477. for(i=1; i<WAL_NREADER; i++){
  44478. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44479. if( rc==SQLITE_OK ){
  44480. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  44481. mxI = i;
  44482. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  44483. break;
  44484. }else if( rc!=SQLITE_BUSY ){
  44485. return rc;
  44486. }
  44487. }
  44488. }
  44489. if( mxI==0 ){
  44490. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  44491. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  44492. }
  44493. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  44494. if( rc ){
  44495. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  44496. }
  44497. /* Now that the read-lock has been obtained, check that neither the
  44498. ** value in the aReadMark[] array or the contents of the wal-index
  44499. ** header have changed.
  44500. **
  44501. ** It is necessary to check that the wal-index header did not change
  44502. ** between the time it was read and when the shared-lock was obtained
  44503. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  44504. ** that the log file may have been wrapped by a writer, or that frames
  44505. ** that occur later in the log than pWal->hdr.mxFrame may have been
  44506. ** copied into the database by a checkpointer. If either of these things
  44507. ** happened, then reading the database with the current value of
  44508. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  44509. ** instead.
  44510. **
  44511. ** This does not guarantee that the copy of the wal-index header is up to
  44512. ** date before proceeding. That would not be possible without somehow
  44513. ** blocking writers. It only guarantees that a dangerous checkpoint or
  44514. ** log-wrap (either of which would require an exclusive lock on
  44515. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  44516. */
  44517. walShmBarrier(pWal);
  44518. if( pInfo->aReadMark[mxI]!=mxReadMark
  44519. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  44520. ){
  44521. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  44522. return WAL_RETRY;
  44523. }else{
  44524. assert( mxReadMark<=pWal->hdr.mxFrame );
  44525. pWal->readLock = (i16)mxI;
  44526. }
  44527. }
  44528. return rc;
  44529. }
  44530. /*
  44531. ** Begin a read transaction on the database.
  44532. **
  44533. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  44534. ** it takes a snapshot of the state of the WAL and wal-index for the current
  44535. ** instant in time. The current thread will continue to use this snapshot.
  44536. ** Other threads might append new content to the WAL and wal-index but
  44537. ** that extra content is ignored by the current thread.
  44538. **
  44539. ** If the database contents have changes since the previous read
  44540. ** transaction, then *pChanged is set to 1 before returning. The
  44541. ** Pager layer will use this to know that is cache is stale and
  44542. ** needs to be flushed.
  44543. */
  44544. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  44545. int rc; /* Return code */
  44546. int cnt = 0; /* Number of TryBeginRead attempts */
  44547. do{
  44548. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  44549. }while( rc==WAL_RETRY );
  44550. testcase( (rc&0xff)==SQLITE_BUSY );
  44551. testcase( (rc&0xff)==SQLITE_IOERR );
  44552. testcase( rc==SQLITE_PROTOCOL );
  44553. testcase( rc==SQLITE_OK );
  44554. return rc;
  44555. }
  44556. /*
  44557. ** Finish with a read transaction. All this does is release the
  44558. ** read-lock.
  44559. */
  44560. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  44561. sqlite3WalEndWriteTransaction(pWal);
  44562. if( pWal->readLock>=0 ){
  44563. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  44564. pWal->readLock = -1;
  44565. }
  44566. }
  44567. /*
  44568. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  44569. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  44570. ** to zero.
  44571. **
  44572. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  44573. ** error does occur, the final value of *piRead is undefined.
  44574. */
  44575. SQLITE_PRIVATE int sqlite3WalFindFrame(
  44576. Wal *pWal, /* WAL handle */
  44577. Pgno pgno, /* Database page number to read data for */
  44578. u32 *piRead /* OUT: Frame number (or zero) */
  44579. ){
  44580. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  44581. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  44582. int iHash; /* Used to loop through N hash tables */
  44583. /* This routine is only be called from within a read transaction. */
  44584. assert( pWal->readLock>=0 || pWal->lockError );
  44585. /* If the "last page" field of the wal-index header snapshot is 0, then
  44586. ** no data will be read from the wal under any circumstances. Return early
  44587. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  44588. ** then the WAL is ignored by the reader so return early, as if the
  44589. ** WAL were empty.
  44590. */
  44591. if( iLast==0 || pWal->readLock==0 ){
  44592. *piRead = 0;
  44593. return SQLITE_OK;
  44594. }
  44595. /* Search the hash table or tables for an entry matching page number
  44596. ** pgno. Each iteration of the following for() loop searches one
  44597. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  44598. **
  44599. ** This code might run concurrently to the code in walIndexAppend()
  44600. ** that adds entries to the wal-index (and possibly to this hash
  44601. ** table). This means the value just read from the hash
  44602. ** slot (aHash[iKey]) may have been added before or after the
  44603. ** current read transaction was opened. Values added after the
  44604. ** read transaction was opened may have been written incorrectly -
  44605. ** i.e. these slots may contain garbage data. However, we assume
  44606. ** that any slots written before the current read transaction was
  44607. ** opened remain unmodified.
  44608. **
  44609. ** For the reasons above, the if(...) condition featured in the inner
  44610. ** loop of the following block is more stringent that would be required
  44611. ** if we had exclusive access to the hash-table:
  44612. **
  44613. ** (aPgno[iFrame]==pgno):
  44614. ** This condition filters out normal hash-table collisions.
  44615. **
  44616. ** (iFrame<=iLast):
  44617. ** This condition filters out entries that were added to the hash
  44618. ** table after the current read-transaction had started.
  44619. */
  44620. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  44621. volatile ht_slot *aHash; /* Pointer to hash table */
  44622. volatile u32 *aPgno; /* Pointer to array of page numbers */
  44623. u32 iZero; /* Frame number corresponding to aPgno[0] */
  44624. int iKey; /* Hash slot index */
  44625. int nCollide; /* Number of hash collisions remaining */
  44626. int rc; /* Error code */
  44627. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  44628. if( rc!=SQLITE_OK ){
  44629. return rc;
  44630. }
  44631. nCollide = HASHTABLE_NSLOT;
  44632. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  44633. u32 iFrame = aHash[iKey] + iZero;
  44634. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  44635. /* assert( iFrame>iRead ); -- not true if there is corruption */
  44636. iRead = iFrame;
  44637. }
  44638. if( (nCollide--)==0 ){
  44639. return SQLITE_CORRUPT_BKPT;
  44640. }
  44641. }
  44642. }
  44643. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  44644. /* If expensive assert() statements are available, do a linear search
  44645. ** of the wal-index file content. Make sure the results agree with the
  44646. ** result obtained using the hash indexes above. */
  44647. {
  44648. u32 iRead2 = 0;
  44649. u32 iTest;
  44650. for(iTest=iLast; iTest>0; iTest--){
  44651. if( walFramePgno(pWal, iTest)==pgno ){
  44652. iRead2 = iTest;
  44653. break;
  44654. }
  44655. }
  44656. assert( iRead==iRead2 );
  44657. }
  44658. #endif
  44659. *piRead = iRead;
  44660. return SQLITE_OK;
  44661. }
  44662. /*
  44663. ** Read the contents of frame iRead from the wal file into buffer pOut
  44664. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  44665. ** error code otherwise.
  44666. */
  44667. SQLITE_PRIVATE int sqlite3WalReadFrame(
  44668. Wal *pWal, /* WAL handle */
  44669. u32 iRead, /* Frame to read */
  44670. int nOut, /* Size of buffer pOut in bytes */
  44671. u8 *pOut /* Buffer to write page data to */
  44672. ){
  44673. int sz;
  44674. i64 iOffset;
  44675. sz = pWal->hdr.szPage;
  44676. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  44677. testcase( sz<=32768 );
  44678. testcase( sz>=65536 );
  44679. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  44680. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  44681. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  44682. }
  44683. /*
  44684. ** Return the size of the database in pages (or zero, if unknown).
  44685. */
  44686. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  44687. if( pWal && ALWAYS(pWal->readLock>=0) ){
  44688. return pWal->hdr.nPage;
  44689. }
  44690. return 0;
  44691. }
  44692. /*
  44693. ** This function starts a write transaction on the WAL.
  44694. **
  44695. ** A read transaction must have already been started by a prior call
  44696. ** to sqlite3WalBeginReadTransaction().
  44697. **
  44698. ** If another thread or process has written into the database since
  44699. ** the read transaction was started, then it is not possible for this
  44700. ** thread to write as doing so would cause a fork. So this routine
  44701. ** returns SQLITE_BUSY in that case and no write transaction is started.
  44702. **
  44703. ** There can only be a single writer active at a time.
  44704. */
  44705. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  44706. int rc;
  44707. /* Cannot start a write transaction without first holding a read
  44708. ** transaction. */
  44709. assert( pWal->readLock>=0 );
  44710. if( pWal->readOnly ){
  44711. return SQLITE_READONLY;
  44712. }
  44713. /* Only one writer allowed at a time. Get the write lock. Return
  44714. ** SQLITE_BUSY if unable.
  44715. */
  44716. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  44717. if( rc ){
  44718. return rc;
  44719. }
  44720. pWal->writeLock = 1;
  44721. /* If another connection has written to the database file since the
  44722. ** time the read transaction on this connection was started, then
  44723. ** the write is disallowed.
  44724. */
  44725. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  44726. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  44727. pWal->writeLock = 0;
  44728. rc = SQLITE_BUSY;
  44729. }
  44730. return rc;
  44731. }
  44732. /*
  44733. ** End a write transaction. The commit has already been done. This
  44734. ** routine merely releases the lock.
  44735. */
  44736. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  44737. if( pWal->writeLock ){
  44738. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  44739. pWal->writeLock = 0;
  44740. pWal->truncateOnCommit = 0;
  44741. }
  44742. return SQLITE_OK;
  44743. }
  44744. /*
  44745. ** If any data has been written (but not committed) to the log file, this
  44746. ** function moves the write-pointer back to the start of the transaction.
  44747. **
  44748. ** Additionally, the callback function is invoked for each frame written
  44749. ** to the WAL since the start of the transaction. If the callback returns
  44750. ** other than SQLITE_OK, it is not invoked again and the error code is
  44751. ** returned to the caller.
  44752. **
  44753. ** Otherwise, if the callback function does not return an error, this
  44754. ** function returns SQLITE_OK.
  44755. */
  44756. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  44757. int rc = SQLITE_OK;
  44758. if( ALWAYS(pWal->writeLock) ){
  44759. Pgno iMax = pWal->hdr.mxFrame;
  44760. Pgno iFrame;
  44761. /* Restore the clients cache of the wal-index header to the state it
  44762. ** was in before the client began writing to the database.
  44763. */
  44764. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  44765. for(iFrame=pWal->hdr.mxFrame+1;
  44766. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  44767. iFrame++
  44768. ){
  44769. /* This call cannot fail. Unless the page for which the page number
  44770. ** is passed as the second argument is (a) in the cache and
  44771. ** (b) has an outstanding reference, then xUndo is either a no-op
  44772. ** (if (a) is false) or simply expels the page from the cache (if (b)
  44773. ** is false).
  44774. **
  44775. ** If the upper layer is doing a rollback, it is guaranteed that there
  44776. ** are no outstanding references to any page other than page 1. And
  44777. ** page 1 is never written to the log until the transaction is
  44778. ** committed. As a result, the call to xUndo may not fail.
  44779. */
  44780. assert( walFramePgno(pWal, iFrame)!=1 );
  44781. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  44782. }
  44783. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  44784. }
  44785. assert( rc==SQLITE_OK );
  44786. return rc;
  44787. }
  44788. /*
  44789. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  44790. ** values. This function populates the array with values required to
  44791. ** "rollback" the write position of the WAL handle back to the current
  44792. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  44793. */
  44794. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  44795. assert( pWal->writeLock );
  44796. aWalData[0] = pWal->hdr.mxFrame;
  44797. aWalData[1] = pWal->hdr.aFrameCksum[0];
  44798. aWalData[2] = pWal->hdr.aFrameCksum[1];
  44799. aWalData[3] = pWal->nCkpt;
  44800. }
  44801. /*
  44802. ** Move the write position of the WAL back to the point identified by
  44803. ** the values in the aWalData[] array. aWalData must point to an array
  44804. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  44805. ** by a call to WalSavepoint().
  44806. */
  44807. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  44808. int rc = SQLITE_OK;
  44809. assert( pWal->writeLock );
  44810. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  44811. if( aWalData[3]!=pWal->nCkpt ){
  44812. /* This savepoint was opened immediately after the write-transaction
  44813. ** was started. Right after that, the writer decided to wrap around
  44814. ** to the start of the log. Update the savepoint values to match.
  44815. */
  44816. aWalData[0] = 0;
  44817. aWalData[3] = pWal->nCkpt;
  44818. }
  44819. if( aWalData[0]<pWal->hdr.mxFrame ){
  44820. pWal->hdr.mxFrame = aWalData[0];
  44821. pWal->hdr.aFrameCksum[0] = aWalData[1];
  44822. pWal->hdr.aFrameCksum[1] = aWalData[2];
  44823. walCleanupHash(pWal);
  44824. }
  44825. return rc;
  44826. }
  44827. /*
  44828. ** This function is called just before writing a set of frames to the log
  44829. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  44830. ** to the current log file, it is possible to overwrite the start of the
  44831. ** existing log file with the new frames (i.e. "reset" the log). If so,
  44832. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  44833. ** unchanged.
  44834. **
  44835. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  44836. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  44837. ** if an error occurs.
  44838. */
  44839. static int walRestartLog(Wal *pWal){
  44840. int rc = SQLITE_OK;
  44841. int cnt;
  44842. if( pWal->readLock==0 ){
  44843. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  44844. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  44845. if( pInfo->nBackfill>0 ){
  44846. u32 salt1;
  44847. sqlite3_randomness(4, &salt1);
  44848. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  44849. if( rc==SQLITE_OK ){
  44850. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  44851. ** readers are currently using the WAL), then the transactions
  44852. ** frames will overwrite the start of the existing log. Update the
  44853. ** wal-index header to reflect this.
  44854. **
  44855. ** In theory it would be Ok to update the cache of the header only
  44856. ** at this point. But updating the actual wal-index header is also
  44857. ** safe and means there is no special case for sqlite3WalUndo()
  44858. ** to handle if this transaction is rolled back.
  44859. */
  44860. int i; /* Loop counter */
  44861. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  44862. pWal->nCkpt++;
  44863. pWal->hdr.mxFrame = 0;
  44864. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  44865. aSalt[1] = salt1;
  44866. walIndexWriteHdr(pWal);
  44867. pInfo->nBackfill = 0;
  44868. pInfo->aReadMark[1] = 0;
  44869. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  44870. assert( pInfo->aReadMark[0]==0 );
  44871. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  44872. }else if( rc!=SQLITE_BUSY ){
  44873. return rc;
  44874. }
  44875. }
  44876. walUnlockShared(pWal, WAL_READ_LOCK(0));
  44877. pWal->readLock = -1;
  44878. cnt = 0;
  44879. do{
  44880. int notUsed;
  44881. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  44882. }while( rc==WAL_RETRY );
  44883. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  44884. testcase( (rc&0xff)==SQLITE_IOERR );
  44885. testcase( rc==SQLITE_PROTOCOL );
  44886. testcase( rc==SQLITE_OK );
  44887. }
  44888. return rc;
  44889. }
  44890. /*
  44891. ** Information about the current state of the WAL file and where
  44892. ** the next fsync should occur - passed from sqlite3WalFrames() into
  44893. ** walWriteToLog().
  44894. */
  44895. typedef struct WalWriter {
  44896. Wal *pWal; /* The complete WAL information */
  44897. sqlite3_file *pFd; /* The WAL file to which we write */
  44898. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  44899. int syncFlags; /* Flags for the fsync */
  44900. int szPage; /* Size of one page */
  44901. } WalWriter;
  44902. /*
  44903. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  44904. ** Do a sync when crossing the p->iSyncPoint boundary.
  44905. **
  44906. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  44907. ** first write the part before iSyncPoint, then sync, then write the
  44908. ** rest.
  44909. */
  44910. static int walWriteToLog(
  44911. WalWriter *p, /* WAL to write to */
  44912. void *pContent, /* Content to be written */
  44913. int iAmt, /* Number of bytes to write */
  44914. sqlite3_int64 iOffset /* Start writing at this offset */
  44915. ){
  44916. int rc;
  44917. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  44918. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  44919. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  44920. if( rc ) return rc;
  44921. iOffset += iFirstAmt;
  44922. iAmt -= iFirstAmt;
  44923. pContent = (void*)(iFirstAmt + (char*)pContent);
  44924. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  44925. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  44926. if( iAmt==0 || rc ) return rc;
  44927. }
  44928. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  44929. return rc;
  44930. }
  44931. /*
  44932. ** Write out a single frame of the WAL
  44933. */
  44934. static int walWriteOneFrame(
  44935. WalWriter *p, /* Where to write the frame */
  44936. PgHdr *pPage, /* The page of the frame to be written */
  44937. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  44938. sqlite3_int64 iOffset /* Byte offset at which to write */
  44939. ){
  44940. int rc; /* Result code from subfunctions */
  44941. void *pData; /* Data actually written */
  44942. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  44943. #if defined(SQLITE_HAS_CODEC)
  44944. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  44945. #else
  44946. pData = pPage->pData;
  44947. #endif
  44948. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  44949. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  44950. if( rc ) return rc;
  44951. /* Write the page data */
  44952. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  44953. return rc;
  44954. }
  44955. /*
  44956. ** Write a set of frames to the log. The caller must hold the write-lock
  44957. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  44958. */
  44959. SQLITE_PRIVATE int sqlite3WalFrames(
  44960. Wal *pWal, /* Wal handle to write to */
  44961. int szPage, /* Database page-size in bytes */
  44962. PgHdr *pList, /* List of dirty pages to write */
  44963. Pgno nTruncate, /* Database size after this commit */
  44964. int isCommit, /* True if this is a commit */
  44965. int sync_flags /* Flags to pass to OsSync() (or 0) */
  44966. ){
  44967. int rc; /* Used to catch return codes */
  44968. u32 iFrame; /* Next frame address */
  44969. PgHdr *p; /* Iterator to run through pList with. */
  44970. PgHdr *pLast = 0; /* Last frame in list */
  44971. int nExtra = 0; /* Number of extra copies of last page */
  44972. int szFrame; /* The size of a single frame */
  44973. i64 iOffset; /* Next byte to write in WAL file */
  44974. WalWriter w; /* The writer */
  44975. assert( pList );
  44976. assert( pWal->writeLock );
  44977. /* If this frame set completes a transaction, then nTruncate>0. If
  44978. ** nTruncate==0 then this frame set does not complete the transaction. */
  44979. assert( (isCommit!=0)==(nTruncate!=0) );
  44980. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  44981. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  44982. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  44983. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  44984. }
  44985. #endif
  44986. /* See if it is possible to write these frames into the start of the
  44987. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  44988. */
  44989. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  44990. return rc;
  44991. }
  44992. /* If this is the first frame written into the log, write the WAL
  44993. ** header to the start of the WAL file. See comments at the top of
  44994. ** this source file for a description of the WAL header format.
  44995. */
  44996. iFrame = pWal->hdr.mxFrame;
  44997. if( iFrame==0 ){
  44998. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  44999. u32 aCksum[2]; /* Checksum for wal-header */
  45000. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  45001. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  45002. sqlite3Put4byte(&aWalHdr[8], szPage);
  45003. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  45004. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  45005. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  45006. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  45007. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  45008. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  45009. pWal->szPage = szPage;
  45010. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  45011. pWal->hdr.aFrameCksum[0] = aCksum[0];
  45012. pWal->hdr.aFrameCksum[1] = aCksum[1];
  45013. pWal->truncateOnCommit = 1;
  45014. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  45015. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  45016. if( rc!=SQLITE_OK ){
  45017. return rc;
  45018. }
  45019. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  45020. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  45021. ** an out-of-order write following a WAL restart could result in
  45022. ** database corruption. See the ticket:
  45023. **
  45024. ** http://localhost:591/sqlite/info/ff5be73dee
  45025. */
  45026. if( pWal->syncHeader && sync_flags ){
  45027. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  45028. if( rc ) return rc;
  45029. }
  45030. }
  45031. assert( (int)pWal->szPage==szPage );
  45032. /* Setup information needed to write frames into the WAL */
  45033. w.pWal = pWal;
  45034. w.pFd = pWal->pWalFd;
  45035. w.iSyncPoint = 0;
  45036. w.syncFlags = sync_flags;
  45037. w.szPage = szPage;
  45038. iOffset = walFrameOffset(iFrame+1, szPage);
  45039. szFrame = szPage + WAL_FRAME_HDRSIZE;
  45040. /* Write all frames into the log file exactly once */
  45041. for(p=pList; p; p=p->pDirty){
  45042. int nDbSize; /* 0 normally. Positive == commit flag */
  45043. iFrame++;
  45044. assert( iOffset==walFrameOffset(iFrame, szPage) );
  45045. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  45046. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  45047. if( rc ) return rc;
  45048. pLast = p;
  45049. iOffset += szFrame;
  45050. }
  45051. /* If this is the end of a transaction, then we might need to pad
  45052. ** the transaction and/or sync the WAL file.
  45053. **
  45054. ** Padding and syncing only occur if this set of frames complete a
  45055. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  45056. ** or synchonous==OFF, then no padding or syncing are needed.
  45057. **
  45058. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  45059. ** needed and only the sync is done. If padding is needed, then the
  45060. ** final frame is repeated (with its commit mark) until the next sector
  45061. ** boundary is crossed. Only the part of the WAL prior to the last
  45062. ** sector boundary is synced; the part of the last frame that extends
  45063. ** past the sector boundary is written after the sync.
  45064. */
  45065. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  45066. if( pWal->padToSectorBoundary ){
  45067. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  45068. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  45069. while( iOffset<w.iSyncPoint ){
  45070. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  45071. if( rc ) return rc;
  45072. iOffset += szFrame;
  45073. nExtra++;
  45074. }
  45075. }else{
  45076. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  45077. }
  45078. }
  45079. /* If this frame set completes the first transaction in the WAL and
  45080. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  45081. ** journal size limit, if possible.
  45082. */
  45083. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  45084. i64 sz = pWal->mxWalSize;
  45085. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  45086. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  45087. }
  45088. walLimitSize(pWal, sz);
  45089. pWal->truncateOnCommit = 0;
  45090. }
  45091. /* Append data to the wal-index. It is not necessary to lock the
  45092. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  45093. ** guarantees that there are no other writers, and no data that may
  45094. ** be in use by existing readers is being overwritten.
  45095. */
  45096. iFrame = pWal->hdr.mxFrame;
  45097. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  45098. iFrame++;
  45099. rc = walIndexAppend(pWal, iFrame, p->pgno);
  45100. }
  45101. while( rc==SQLITE_OK && nExtra>0 ){
  45102. iFrame++;
  45103. nExtra--;
  45104. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  45105. }
  45106. if( rc==SQLITE_OK ){
  45107. /* Update the private copy of the header. */
  45108. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  45109. testcase( szPage<=32768 );
  45110. testcase( szPage>=65536 );
  45111. pWal->hdr.mxFrame = iFrame;
  45112. if( isCommit ){
  45113. pWal->hdr.iChange++;
  45114. pWal->hdr.nPage = nTruncate;
  45115. }
  45116. /* If this is a commit, update the wal-index header too. */
  45117. if( isCommit ){
  45118. walIndexWriteHdr(pWal);
  45119. pWal->iCallback = iFrame;
  45120. }
  45121. }
  45122. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  45123. return rc;
  45124. }
  45125. /*
  45126. ** This routine is called to implement sqlite3_wal_checkpoint() and
  45127. ** related interfaces.
  45128. **
  45129. ** Obtain a CHECKPOINT lock and then backfill as much information as
  45130. ** we can from WAL into the database.
  45131. **
  45132. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  45133. ** callback. In this case this function runs a blocking checkpoint.
  45134. */
  45135. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  45136. Wal *pWal, /* Wal connection */
  45137. int eMode, /* PASSIVE, FULL or RESTART */
  45138. int (*xBusy)(void*), /* Function to call when busy */
  45139. void *pBusyArg, /* Context argument for xBusyHandler */
  45140. int sync_flags, /* Flags to sync db file with (or 0) */
  45141. int nBuf, /* Size of temporary buffer */
  45142. u8 *zBuf, /* Temporary buffer to use */
  45143. int *pnLog, /* OUT: Number of frames in WAL */
  45144. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  45145. ){
  45146. int rc; /* Return code */
  45147. int isChanged = 0; /* True if a new wal-index header is loaded */
  45148. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  45149. assert( pWal->ckptLock==0 );
  45150. assert( pWal->writeLock==0 );
  45151. if( pWal->readOnly ) return SQLITE_READONLY;
  45152. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  45153. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  45154. if( rc ){
  45155. /* Usually this is SQLITE_BUSY meaning that another thread or process
  45156. ** is already running a checkpoint, or maybe a recovery. But it might
  45157. ** also be SQLITE_IOERR. */
  45158. return rc;
  45159. }
  45160. pWal->ckptLock = 1;
  45161. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  45162. ** to prevent any writers from running while the checkpoint is underway.
  45163. ** This has to be done before the call to walIndexReadHdr() below.
  45164. **
  45165. ** If the writer lock cannot be obtained, then a passive checkpoint is
  45166. ** run instead. Since the checkpointer is not holding the writer lock,
  45167. ** there is no point in blocking waiting for any readers. Assuming no
  45168. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  45169. */
  45170. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  45171. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  45172. if( rc==SQLITE_OK ){
  45173. pWal->writeLock = 1;
  45174. }else if( rc==SQLITE_BUSY ){
  45175. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  45176. rc = SQLITE_OK;
  45177. }
  45178. }
  45179. /* Read the wal-index header. */
  45180. if( rc==SQLITE_OK ){
  45181. rc = walIndexReadHdr(pWal, &isChanged);
  45182. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  45183. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  45184. }
  45185. }
  45186. /* Copy data from the log to the database file. */
  45187. if( rc==SQLITE_OK ){
  45188. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  45189. rc = SQLITE_CORRUPT_BKPT;
  45190. }else{
  45191. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  45192. }
  45193. /* If no error occurred, set the output variables. */
  45194. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  45195. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  45196. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  45197. }
  45198. }
  45199. if( isChanged ){
  45200. /* If a new wal-index header was loaded before the checkpoint was
  45201. ** performed, then the pager-cache associated with pWal is now
  45202. ** out of date. So zero the cached wal-index header to ensure that
  45203. ** next time the pager opens a snapshot on this database it knows that
  45204. ** the cache needs to be reset.
  45205. */
  45206. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  45207. }
  45208. /* Release the locks. */
  45209. sqlite3WalEndWriteTransaction(pWal);
  45210. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  45211. pWal->ckptLock = 0;
  45212. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  45213. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  45214. }
  45215. /* Return the value to pass to a sqlite3_wal_hook callback, the
  45216. ** number of frames in the WAL at the point of the last commit since
  45217. ** sqlite3WalCallback() was called. If no commits have occurred since
  45218. ** the last call, then return 0.
  45219. */
  45220. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  45221. u32 ret = 0;
  45222. if( pWal ){
  45223. ret = pWal->iCallback;
  45224. pWal->iCallback = 0;
  45225. }
  45226. return (int)ret;
  45227. }
  45228. /*
  45229. ** This function is called to change the WAL subsystem into or out
  45230. ** of locking_mode=EXCLUSIVE.
  45231. **
  45232. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  45233. ** into locking_mode=NORMAL. This means that we must acquire a lock
  45234. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  45235. ** or if the acquisition of the lock fails, then return 0. If the
  45236. ** transition out of exclusive-mode is successful, return 1. This
  45237. ** operation must occur while the pager is still holding the exclusive
  45238. ** lock on the main database file.
  45239. **
  45240. ** If op is one, then change from locking_mode=NORMAL into
  45241. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  45242. ** be released. Return 1 if the transition is made and 0 if the
  45243. ** WAL is already in exclusive-locking mode - meaning that this
  45244. ** routine is a no-op. The pager must already hold the exclusive lock
  45245. ** on the main database file before invoking this operation.
  45246. **
  45247. ** If op is negative, then do a dry-run of the op==1 case but do
  45248. ** not actually change anything. The pager uses this to see if it
  45249. ** should acquire the database exclusive lock prior to invoking
  45250. ** the op==1 case.
  45251. */
  45252. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  45253. int rc;
  45254. assert( pWal->writeLock==0 );
  45255. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  45256. /* pWal->readLock is usually set, but might be -1 if there was a
  45257. ** prior error while attempting to acquire are read-lock. This cannot
  45258. ** happen if the connection is actually in exclusive mode (as no xShmLock
  45259. ** locks are taken in this case). Nor should the pager attempt to
  45260. ** upgrade to exclusive-mode following such an error.
  45261. */
  45262. assert( pWal->readLock>=0 || pWal->lockError );
  45263. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  45264. if( op==0 ){
  45265. if( pWal->exclusiveMode ){
  45266. pWal->exclusiveMode = 0;
  45267. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  45268. pWal->exclusiveMode = 1;
  45269. }
  45270. rc = pWal->exclusiveMode==0;
  45271. }else{
  45272. /* Already in locking_mode=NORMAL */
  45273. rc = 0;
  45274. }
  45275. }else if( op>0 ){
  45276. assert( pWal->exclusiveMode==0 );
  45277. assert( pWal->readLock>=0 );
  45278. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  45279. pWal->exclusiveMode = 1;
  45280. rc = 1;
  45281. }else{
  45282. rc = pWal->exclusiveMode==0;
  45283. }
  45284. return rc;
  45285. }
  45286. /*
  45287. ** Return true if the argument is non-NULL and the WAL module is using
  45288. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  45289. ** WAL module is using shared-memory, return false.
  45290. */
  45291. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  45292. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  45293. }
  45294. #ifdef SQLITE_ENABLE_ZIPVFS
  45295. /*
  45296. ** If the argument is not NULL, it points to a Wal object that holds a
  45297. ** read-lock. This function returns the database page-size if it is known,
  45298. ** or zero if it is not (or if pWal is NULL).
  45299. */
  45300. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  45301. assert( pWal==0 || pWal->readLock>=0 );
  45302. return (pWal ? pWal->szPage : 0);
  45303. }
  45304. #endif
  45305. #endif /* #ifndef SQLITE_OMIT_WAL */
  45306. /************** End of wal.c *************************************************/
  45307. /************** Begin file btmutex.c *****************************************/
  45308. /*
  45309. ** 2007 August 27
  45310. **
  45311. ** The author disclaims copyright to this source code. In place of
  45312. ** a legal notice, here is a blessing:
  45313. **
  45314. ** May you do good and not evil.
  45315. ** May you find forgiveness for yourself and forgive others.
  45316. ** May you share freely, never taking more than you give.
  45317. **
  45318. *************************************************************************
  45319. **
  45320. ** This file contains code used to implement mutexes on Btree objects.
  45321. ** This code really belongs in btree.c. But btree.c is getting too
  45322. ** big and we want to break it down some. This packaged seemed like
  45323. ** a good breakout.
  45324. */
  45325. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  45326. /************** Begin file btreeInt.h ****************************************/
  45327. /*
  45328. ** 2004 April 6
  45329. **
  45330. ** The author disclaims copyright to this source code. In place of
  45331. ** a legal notice, here is a blessing:
  45332. **
  45333. ** May you do good and not evil.
  45334. ** May you find forgiveness for yourself and forgive others.
  45335. ** May you share freely, never taking more than you give.
  45336. **
  45337. *************************************************************************
  45338. ** This file implements a external (disk-based) database using BTrees.
  45339. ** For a detailed discussion of BTrees, refer to
  45340. **
  45341. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  45342. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  45343. ** Publishing Company, Reading, Massachusetts.
  45344. **
  45345. ** The basic idea is that each page of the file contains N database
  45346. ** entries and N+1 pointers to subpages.
  45347. **
  45348. ** ----------------------------------------------------------------
  45349. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  45350. ** ----------------------------------------------------------------
  45351. **
  45352. ** All of the keys on the page that Ptr(0) points to have values less
  45353. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  45354. ** values greater than Key(0) and less than Key(1). All of the keys
  45355. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  45356. ** so forth.
  45357. **
  45358. ** Finding a particular key requires reading O(log(M)) pages from the
  45359. ** disk where M is the number of entries in the tree.
  45360. **
  45361. ** In this implementation, a single file can hold one or more separate
  45362. ** BTrees. Each BTree is identified by the index of its root page. The
  45363. ** key and data for any entry are combined to form the "payload". A
  45364. ** fixed amount of payload can be carried directly on the database
  45365. ** page. If the payload is larger than the preset amount then surplus
  45366. ** bytes are stored on overflow pages. The payload for an entry
  45367. ** and the preceding pointer are combined to form a "Cell". Each
  45368. ** page has a small header which contains the Ptr(N) pointer and other
  45369. ** information such as the size of key and data.
  45370. **
  45371. ** FORMAT DETAILS
  45372. **
  45373. ** The file is divided into pages. The first page is called page 1,
  45374. ** the second is page 2, and so forth. A page number of zero indicates
  45375. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  45376. ** Each page can be either a btree page, a freelist page, an overflow
  45377. ** page, or a pointer-map page.
  45378. **
  45379. ** The first page is always a btree page. The first 100 bytes of the first
  45380. ** page contain a special header (the "file header") that describes the file.
  45381. ** The format of the file header is as follows:
  45382. **
  45383. ** OFFSET SIZE DESCRIPTION
  45384. ** 0 16 Header string: "SQLite format 3\000"
  45385. ** 16 2 Page size in bytes.
  45386. ** 18 1 File format write version
  45387. ** 19 1 File format read version
  45388. ** 20 1 Bytes of unused space at the end of each page
  45389. ** 21 1 Max embedded payload fraction
  45390. ** 22 1 Min embedded payload fraction
  45391. ** 23 1 Min leaf payload fraction
  45392. ** 24 4 File change counter
  45393. ** 28 4 Reserved for future use
  45394. ** 32 4 First freelist page
  45395. ** 36 4 Number of freelist pages in the file
  45396. ** 40 60 15 4-byte meta values passed to higher layers
  45397. **
  45398. ** 40 4 Schema cookie
  45399. ** 44 4 File format of schema layer
  45400. ** 48 4 Size of page cache
  45401. ** 52 4 Largest root-page (auto/incr_vacuum)
  45402. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  45403. ** 60 4 User version
  45404. ** 64 4 Incremental vacuum mode
  45405. ** 68 4 unused
  45406. ** 72 4 unused
  45407. ** 76 4 unused
  45408. **
  45409. ** All of the integer values are big-endian (most significant byte first).
  45410. **
  45411. ** The file change counter is incremented when the database is changed
  45412. ** This counter allows other processes to know when the file has changed
  45413. ** and thus when they need to flush their cache.
  45414. **
  45415. ** The max embedded payload fraction is the amount of the total usable
  45416. ** space in a page that can be consumed by a single cell for standard
  45417. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  45418. ** is to limit the maximum cell size so that at least 4 cells will fit
  45419. ** on one page. Thus the default max embedded payload fraction is 64.
  45420. **
  45421. ** If the payload for a cell is larger than the max payload, then extra
  45422. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  45423. ** as many bytes as possible are moved into the overflow pages without letting
  45424. ** the cell size drop below the min embedded payload fraction.
  45425. **
  45426. ** The min leaf payload fraction is like the min embedded payload fraction
  45427. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  45428. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  45429. ** not specified in the header.
  45430. **
  45431. ** Each btree pages is divided into three sections: The header, the
  45432. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  45433. ** file header that occurs before the page header.
  45434. **
  45435. ** |----------------|
  45436. ** | file header | 100 bytes. Page 1 only.
  45437. ** |----------------|
  45438. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  45439. ** |----------------|
  45440. ** | cell pointer | | 2 bytes per cell. Sorted order.
  45441. ** | array | | Grows downward
  45442. ** | | v
  45443. ** |----------------|
  45444. ** | unallocated |
  45445. ** | space |
  45446. ** |----------------| ^ Grows upwards
  45447. ** | cell content | | Arbitrary order interspersed with freeblocks.
  45448. ** | area | | and free space fragments.
  45449. ** |----------------|
  45450. **
  45451. ** The page headers looks like this:
  45452. **
  45453. ** OFFSET SIZE DESCRIPTION
  45454. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  45455. ** 1 2 byte offset to the first freeblock
  45456. ** 3 2 number of cells on this page
  45457. ** 5 2 first byte of the cell content area
  45458. ** 7 1 number of fragmented free bytes
  45459. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  45460. **
  45461. ** The flags define the format of this btree page. The leaf flag means that
  45462. ** this page has no children. The zerodata flag means that this page carries
  45463. ** only keys and no data. The intkey flag means that the key is a integer
  45464. ** which is stored in the key size entry of the cell header rather than in
  45465. ** the payload area.
  45466. **
  45467. ** The cell pointer array begins on the first byte after the page header.
  45468. ** The cell pointer array contains zero or more 2-byte numbers which are
  45469. ** offsets from the beginning of the page to the cell content in the cell
  45470. ** content area. The cell pointers occur in sorted order. The system strives
  45471. ** to keep free space after the last cell pointer so that new cells can
  45472. ** be easily added without having to defragment the page.
  45473. **
  45474. ** Cell content is stored at the very end of the page and grows toward the
  45475. ** beginning of the page.
  45476. **
  45477. ** Unused space within the cell content area is collected into a linked list of
  45478. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  45479. ** to the first freeblock is given in the header. Freeblocks occur in
  45480. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  45481. ** any group of 3 or fewer unused bytes in the cell content area cannot
  45482. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  45483. ** a fragment. The total number of bytes in all fragments is recorded.
  45484. ** in the page header at offset 7.
  45485. **
  45486. ** SIZE DESCRIPTION
  45487. ** 2 Byte offset of the next freeblock
  45488. ** 2 Bytes in this freeblock
  45489. **
  45490. ** Cells are of variable length. Cells are stored in the cell content area at
  45491. ** the end of the page. Pointers to the cells are in the cell pointer array
  45492. ** that immediately follows the page header. Cells is not necessarily
  45493. ** contiguous or in order, but cell pointers are contiguous and in order.
  45494. **
  45495. ** Cell content makes use of variable length integers. A variable
  45496. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  45497. ** byte are used. The integer consists of all bytes that have bit 8 set and
  45498. ** the first byte with bit 8 clear. The most significant byte of the integer
  45499. ** appears first. A variable-length integer may not be more than 9 bytes long.
  45500. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  45501. ** allows a 64-bit integer to be encoded in 9 bytes.
  45502. **
  45503. ** 0x00 becomes 0x00000000
  45504. ** 0x7f becomes 0x0000007f
  45505. ** 0x81 0x00 becomes 0x00000080
  45506. ** 0x82 0x00 becomes 0x00000100
  45507. ** 0x80 0x7f becomes 0x0000007f
  45508. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  45509. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  45510. **
  45511. ** Variable length integers are used for rowids and to hold the number of
  45512. ** bytes of key and data in a btree cell.
  45513. **
  45514. ** The content of a cell looks like this:
  45515. **
  45516. ** SIZE DESCRIPTION
  45517. ** 4 Page number of the left child. Omitted if leaf flag is set.
  45518. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  45519. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  45520. ** * Payload
  45521. ** 4 First page of the overflow chain. Omitted if no overflow
  45522. **
  45523. ** Overflow pages form a linked list. Each page except the last is completely
  45524. ** filled with data (pagesize - 4 bytes). The last page can have as little
  45525. ** as 1 byte of data.
  45526. **
  45527. ** SIZE DESCRIPTION
  45528. ** 4 Page number of next overflow page
  45529. ** * Data
  45530. **
  45531. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  45532. ** file header points to the first in a linked list of trunk page. Each trunk
  45533. ** page points to multiple leaf pages. The content of a leaf page is
  45534. ** unspecified. A trunk page looks like this:
  45535. **
  45536. ** SIZE DESCRIPTION
  45537. ** 4 Page number of next trunk page
  45538. ** 4 Number of leaf pointers on this page
  45539. ** * zero or more pages numbers of leaves
  45540. */
  45541. /* The following value is the maximum cell size assuming a maximum page
  45542. ** size give above.
  45543. */
  45544. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  45545. /* The maximum number of cells on a single page of the database. This
  45546. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  45547. ** plus 2 bytes for the index to the cell in the page header). Such
  45548. ** small cells will be rare, but they are possible.
  45549. */
  45550. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  45551. /* Forward declarations */
  45552. typedef struct MemPage MemPage;
  45553. typedef struct BtLock BtLock;
  45554. /*
  45555. ** This is a magic string that appears at the beginning of every
  45556. ** SQLite database in order to identify the file as a real database.
  45557. **
  45558. ** You can change this value at compile-time by specifying a
  45559. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  45560. ** header must be exactly 16 bytes including the zero-terminator so
  45561. ** the string itself should be 15 characters long. If you change
  45562. ** the header, then your custom library will not be able to read
  45563. ** databases generated by the standard tools and the standard tools
  45564. ** will not be able to read databases created by your custom library.
  45565. */
  45566. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  45567. # define SQLITE_FILE_HEADER "SQLite format 3"
  45568. #endif
  45569. /*
  45570. ** Page type flags. An ORed combination of these flags appear as the
  45571. ** first byte of on-disk image of every BTree page.
  45572. */
  45573. #define PTF_INTKEY 0x01
  45574. #define PTF_ZERODATA 0x02
  45575. #define PTF_LEAFDATA 0x04
  45576. #define PTF_LEAF 0x08
  45577. /*
  45578. ** As each page of the file is loaded into memory, an instance of the following
  45579. ** structure is appended and initialized to zero. This structure stores
  45580. ** information about the page that is decoded from the raw file page.
  45581. **
  45582. ** The pParent field points back to the parent page. This allows us to
  45583. ** walk up the BTree from any leaf to the root. Care must be taken to
  45584. ** unref() the parent page pointer when this page is no longer referenced.
  45585. ** The pageDestructor() routine handles that chore.
  45586. **
  45587. ** Access to all fields of this structure is controlled by the mutex
  45588. ** stored in MemPage.pBt->mutex.
  45589. */
  45590. struct MemPage {
  45591. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  45592. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  45593. u8 intKey; /* True if intkey flag is set */
  45594. u8 leaf; /* True if leaf flag is set */
  45595. u8 hasData; /* True if this page stores data */
  45596. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  45597. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  45598. u8 max1bytePayload; /* min(maxLocal,127) */
  45599. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  45600. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  45601. u16 cellOffset; /* Index in aData of first cell pointer */
  45602. u16 nFree; /* Number of free bytes on the page */
  45603. u16 nCell; /* Number of cells on this page, local and ovfl */
  45604. u16 maskPage; /* Mask for page offset */
  45605. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  45606. ** non-overflow cell */
  45607. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  45608. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  45609. u8 *aData; /* Pointer to disk image of the page data */
  45610. u8 *aDataEnd; /* One byte past the end of usable data */
  45611. u8 *aCellIdx; /* The cell index area */
  45612. DbPage *pDbPage; /* Pager page handle */
  45613. Pgno pgno; /* Page number for this page */
  45614. };
  45615. /*
  45616. ** The in-memory image of a disk page has the auxiliary information appended
  45617. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  45618. ** that extra information.
  45619. */
  45620. #define EXTRA_SIZE sizeof(MemPage)
  45621. /*
  45622. ** A linked list of the following structures is stored at BtShared.pLock.
  45623. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  45624. ** is opened on the table with root page BtShared.iTable. Locks are removed
  45625. ** from this list when a transaction is committed or rolled back, or when
  45626. ** a btree handle is closed.
  45627. */
  45628. struct BtLock {
  45629. Btree *pBtree; /* Btree handle holding this lock */
  45630. Pgno iTable; /* Root page of table */
  45631. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  45632. BtLock *pNext; /* Next in BtShared.pLock list */
  45633. };
  45634. /* Candidate values for BtLock.eLock */
  45635. #define READ_LOCK 1
  45636. #define WRITE_LOCK 2
  45637. /* A Btree handle
  45638. **
  45639. ** A database connection contains a pointer to an instance of
  45640. ** this object for every database file that it has open. This structure
  45641. ** is opaque to the database connection. The database connection cannot
  45642. ** see the internals of this structure and only deals with pointers to
  45643. ** this structure.
  45644. **
  45645. ** For some database files, the same underlying database cache might be
  45646. ** shared between multiple connections. In that case, each connection
  45647. ** has it own instance of this object. But each instance of this object
  45648. ** points to the same BtShared object. The database cache and the
  45649. ** schema associated with the database file are all contained within
  45650. ** the BtShared object.
  45651. **
  45652. ** All fields in this structure are accessed under sqlite3.mutex.
  45653. ** The pBt pointer itself may not be changed while there exists cursors
  45654. ** in the referenced BtShared that point back to this Btree since those
  45655. ** cursors have to go through this Btree to find their BtShared and
  45656. ** they often do so without holding sqlite3.mutex.
  45657. */
  45658. struct Btree {
  45659. sqlite3 *db; /* The database connection holding this btree */
  45660. BtShared *pBt; /* Sharable content of this btree */
  45661. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  45662. u8 sharable; /* True if we can share pBt with another db */
  45663. u8 locked; /* True if db currently has pBt locked */
  45664. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  45665. int nBackup; /* Number of backup operations reading this btree */
  45666. Btree *pNext; /* List of other sharable Btrees from the same db */
  45667. Btree *pPrev; /* Back pointer of the same list */
  45668. #ifndef SQLITE_OMIT_SHARED_CACHE
  45669. BtLock lock; /* Object used to lock page 1 */
  45670. #endif
  45671. };
  45672. /*
  45673. ** Btree.inTrans may take one of the following values.
  45674. **
  45675. ** If the shared-data extension is enabled, there may be multiple users
  45676. ** of the Btree structure. At most one of these may open a write transaction,
  45677. ** but any number may have active read transactions.
  45678. */
  45679. #define TRANS_NONE 0
  45680. #define TRANS_READ 1
  45681. #define TRANS_WRITE 2
  45682. /*
  45683. ** An instance of this object represents a single database file.
  45684. **
  45685. ** A single database file can be in use at the same time by two
  45686. ** or more database connections. When two or more connections are
  45687. ** sharing the same database file, each connection has it own
  45688. ** private Btree object for the file and each of those Btrees points
  45689. ** to this one BtShared object. BtShared.nRef is the number of
  45690. ** connections currently sharing this database file.
  45691. **
  45692. ** Fields in this structure are accessed under the BtShared.mutex
  45693. ** mutex, except for nRef and pNext which are accessed under the
  45694. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  45695. ** may not be modified once it is initially set as long as nRef>0.
  45696. ** The pSchema field may be set once under BtShared.mutex and
  45697. ** thereafter is unchanged as long as nRef>0.
  45698. **
  45699. ** isPending:
  45700. **
  45701. ** If a BtShared client fails to obtain a write-lock on a database
  45702. ** table (because there exists one or more read-locks on the table),
  45703. ** the shared-cache enters 'pending-lock' state and isPending is
  45704. ** set to true.
  45705. **
  45706. ** The shared-cache leaves the 'pending lock' state when either of
  45707. ** the following occur:
  45708. **
  45709. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  45710. ** 2) The number of locks held by other connections drops to zero.
  45711. **
  45712. ** while in the 'pending-lock' state, no connection may start a new
  45713. ** transaction.
  45714. **
  45715. ** This feature is included to help prevent writer-starvation.
  45716. */
  45717. struct BtShared {
  45718. Pager *pPager; /* The page cache */
  45719. sqlite3 *db; /* Database connection currently using this Btree */
  45720. BtCursor *pCursor; /* A list of all open cursors */
  45721. MemPage *pPage1; /* First page of the database */
  45722. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  45723. #ifndef SQLITE_OMIT_AUTOVACUUM
  45724. u8 autoVacuum; /* True if auto-vacuum is enabled */
  45725. u8 incrVacuum; /* True if incr-vacuum is enabled */
  45726. u8 bDoTruncate; /* True to truncate db on commit */
  45727. #endif
  45728. u8 inTransaction; /* Transaction state */
  45729. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  45730. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  45731. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  45732. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  45733. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  45734. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  45735. u32 pageSize; /* Total number of bytes on a page */
  45736. u32 usableSize; /* Number of usable bytes on each page */
  45737. int nTransaction; /* Number of open transactions (read + write) */
  45738. u32 nPage; /* Number of pages in the database */
  45739. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  45740. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  45741. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  45742. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  45743. #ifndef SQLITE_OMIT_SHARED_CACHE
  45744. int nRef; /* Number of references to this structure */
  45745. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  45746. BtLock *pLock; /* List of locks held on this shared-btree struct */
  45747. Btree *pWriter; /* Btree with currently open write transaction */
  45748. #endif
  45749. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  45750. };
  45751. /*
  45752. ** Allowed values for BtShared.btsFlags
  45753. */
  45754. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  45755. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  45756. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  45757. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  45758. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  45759. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  45760. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  45761. /*
  45762. ** An instance of the following structure is used to hold information
  45763. ** about a cell. The parseCellPtr() function fills in this structure
  45764. ** based on information extract from the raw disk page.
  45765. */
  45766. typedef struct CellInfo CellInfo;
  45767. struct CellInfo {
  45768. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  45769. u8 *pCell; /* Pointer to the start of cell content */
  45770. u32 nData; /* Number of bytes of data */
  45771. u32 nPayload; /* Total amount of payload */
  45772. u16 nHeader; /* Size of the cell content header in bytes */
  45773. u16 nLocal; /* Amount of payload held locally */
  45774. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  45775. u16 nSize; /* Size of the cell content on the main b-tree page */
  45776. };
  45777. /*
  45778. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  45779. ** this will be declared corrupt. This value is calculated based on a
  45780. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  45781. ** root-node and 3 for all other internal nodes.
  45782. **
  45783. ** If a tree that appears to be taller than this is encountered, it is
  45784. ** assumed that the database is corrupt.
  45785. */
  45786. #define BTCURSOR_MAX_DEPTH 20
  45787. /*
  45788. ** A cursor is a pointer to a particular entry within a particular
  45789. ** b-tree within a database file.
  45790. **
  45791. ** The entry is identified by its MemPage and the index in
  45792. ** MemPage.aCell[] of the entry.
  45793. **
  45794. ** A single database file can be shared by two more database connections,
  45795. ** but cursors cannot be shared. Each cursor is associated with a
  45796. ** particular database connection identified BtCursor.pBtree.db.
  45797. **
  45798. ** Fields in this structure are accessed under the BtShared.mutex
  45799. ** found at self->pBt->mutex.
  45800. */
  45801. struct BtCursor {
  45802. Btree *pBtree; /* The Btree to which this cursor belongs */
  45803. BtShared *pBt; /* The BtShared this cursor points to */
  45804. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  45805. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  45806. #ifndef SQLITE_OMIT_INCRBLOB
  45807. Pgno *aOverflow; /* Cache of overflow page locations */
  45808. #endif
  45809. Pgno pgnoRoot; /* The root page of this tree */
  45810. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  45811. CellInfo info; /* A parse of the cell we are pointing at */
  45812. i64 nKey; /* Size of pKey, or last integer key */
  45813. void *pKey; /* Saved key that was cursor's last known position */
  45814. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  45815. u8 wrFlag; /* True if writable */
  45816. u8 atLast; /* Cursor pointing to the last entry */
  45817. u8 validNKey; /* True if info.nKey is valid */
  45818. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  45819. #ifndef SQLITE_OMIT_INCRBLOB
  45820. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  45821. #endif
  45822. u8 hints; /* As configured by CursorSetHints() */
  45823. i16 iPage; /* Index of current page in apPage */
  45824. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  45825. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  45826. };
  45827. /*
  45828. ** Potential values for BtCursor.eState.
  45829. **
  45830. ** CURSOR_VALID:
  45831. ** Cursor points to a valid entry. getPayload() etc. may be called.
  45832. **
  45833. ** CURSOR_INVALID:
  45834. ** Cursor does not point to a valid entry. This can happen (for example)
  45835. ** because the table is empty or because BtreeCursorFirst() has not been
  45836. ** called.
  45837. **
  45838. ** CURSOR_REQUIRESEEK:
  45839. ** The table that this cursor was opened on still exists, but has been
  45840. ** modified since the cursor was last used. The cursor position is saved
  45841. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  45842. ** this state, restoreCursorPosition() can be called to attempt to
  45843. ** seek the cursor to the saved position.
  45844. **
  45845. ** CURSOR_FAULT:
  45846. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  45847. ** on a different connection that shares the BtShared cache with this
  45848. ** cursor. The error has left the cache in an inconsistent state.
  45849. ** Do nothing else with this cursor. Any attempt to use the cursor
  45850. ** should return the error code stored in BtCursor.skip
  45851. */
  45852. #define CURSOR_INVALID 0
  45853. #define CURSOR_VALID 1
  45854. #define CURSOR_REQUIRESEEK 2
  45855. #define CURSOR_FAULT 3
  45856. /*
  45857. ** The database page the PENDING_BYTE occupies. This page is never used.
  45858. */
  45859. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  45860. /*
  45861. ** These macros define the location of the pointer-map entry for a
  45862. ** database page. The first argument to each is the number of usable
  45863. ** bytes on each page of the database (often 1024). The second is the
  45864. ** page number to look up in the pointer map.
  45865. **
  45866. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  45867. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  45868. ** the offset of the requested map entry.
  45869. **
  45870. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  45871. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  45872. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  45873. ** this test.
  45874. */
  45875. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  45876. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  45877. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  45878. /*
  45879. ** The pointer map is a lookup table that identifies the parent page for
  45880. ** each child page in the database file. The parent page is the page that
  45881. ** contains a pointer to the child. Every page in the database contains
  45882. ** 0 or 1 parent pages. (In this context 'database page' refers
  45883. ** to any page that is not part of the pointer map itself.) Each pointer map
  45884. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  45885. ** The PTRMAP_XXX identifiers below are the valid types.
  45886. **
  45887. ** The purpose of the pointer map is to facility moving pages from one
  45888. ** position in the file to another as part of autovacuum. When a page
  45889. ** is moved, the pointer in its parent must be updated to point to the
  45890. ** new location. The pointer map is used to locate the parent page quickly.
  45891. **
  45892. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  45893. ** used in this case.
  45894. **
  45895. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  45896. ** is not used in this case.
  45897. **
  45898. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  45899. ** overflow pages. The page number identifies the page that
  45900. ** contains the cell with a pointer to this overflow page.
  45901. **
  45902. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  45903. ** overflow pages. The page-number identifies the previous
  45904. ** page in the overflow page list.
  45905. **
  45906. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  45907. ** identifies the parent page in the btree.
  45908. */
  45909. #define PTRMAP_ROOTPAGE 1
  45910. #define PTRMAP_FREEPAGE 2
  45911. #define PTRMAP_OVERFLOW1 3
  45912. #define PTRMAP_OVERFLOW2 4
  45913. #define PTRMAP_BTREE 5
  45914. /* A bunch of assert() statements to check the transaction state variables
  45915. ** of handle p (type Btree*) are internally consistent.
  45916. */
  45917. #define btreeIntegrity(p) \
  45918. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  45919. assert( p->pBt->inTransaction>=p->inTrans );
  45920. /*
  45921. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  45922. ** if the database supports auto-vacuum or not. Because it is used
  45923. ** within an expression that is an argument to another macro
  45924. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  45925. ** So, this macro is defined instead.
  45926. */
  45927. #ifndef SQLITE_OMIT_AUTOVACUUM
  45928. #define ISAUTOVACUUM (pBt->autoVacuum)
  45929. #else
  45930. #define ISAUTOVACUUM 0
  45931. #endif
  45932. /*
  45933. ** This structure is passed around through all the sanity checking routines
  45934. ** in order to keep track of some global state information.
  45935. **
  45936. ** The aRef[] array is allocated so that there is 1 bit for each page in
  45937. ** the database. As the integrity-check proceeds, for each page used in
  45938. ** the database the corresponding bit is set. This allows integrity-check to
  45939. ** detect pages that are used twice and orphaned pages (both of which
  45940. ** indicate corruption).
  45941. */
  45942. typedef struct IntegrityCk IntegrityCk;
  45943. struct IntegrityCk {
  45944. BtShared *pBt; /* The tree being checked out */
  45945. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  45946. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  45947. Pgno nPage; /* Number of pages in the database */
  45948. int mxErr; /* Stop accumulating errors when this reaches zero */
  45949. int nErr; /* Number of messages written to zErrMsg so far */
  45950. int mallocFailed; /* A memory allocation error has occurred */
  45951. StrAccum errMsg; /* Accumulate the error message text here */
  45952. };
  45953. /*
  45954. ** Routines to read or write a two- and four-byte big-endian integer values.
  45955. */
  45956. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  45957. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  45958. #define get4byte sqlite3Get4byte
  45959. #define put4byte sqlite3Put4byte
  45960. /************** End of btreeInt.h ********************************************/
  45961. /************** Continuing where we left off in btmutex.c ********************/
  45962. #ifndef SQLITE_OMIT_SHARED_CACHE
  45963. #if SQLITE_THREADSAFE
  45964. /*
  45965. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  45966. ** set BtShared.db to the database handle associated with p and the
  45967. ** p->locked boolean to true.
  45968. */
  45969. static void lockBtreeMutex(Btree *p){
  45970. assert( p->locked==0 );
  45971. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  45972. assert( sqlite3_mutex_held(p->db->mutex) );
  45973. sqlite3_mutex_enter(p->pBt->mutex);
  45974. p->pBt->db = p->db;
  45975. p->locked = 1;
  45976. }
  45977. /*
  45978. ** Release the BtShared mutex associated with B-Tree handle p and
  45979. ** clear the p->locked boolean.
  45980. */
  45981. static void unlockBtreeMutex(Btree *p){
  45982. BtShared *pBt = p->pBt;
  45983. assert( p->locked==1 );
  45984. assert( sqlite3_mutex_held(pBt->mutex) );
  45985. assert( sqlite3_mutex_held(p->db->mutex) );
  45986. assert( p->db==pBt->db );
  45987. sqlite3_mutex_leave(pBt->mutex);
  45988. p->locked = 0;
  45989. }
  45990. /*
  45991. ** Enter a mutex on the given BTree object.
  45992. **
  45993. ** If the object is not sharable, then no mutex is ever required
  45994. ** and this routine is a no-op. The underlying mutex is non-recursive.
  45995. ** But we keep a reference count in Btree.wantToLock so the behavior
  45996. ** of this interface is recursive.
  45997. **
  45998. ** To avoid deadlocks, multiple Btrees are locked in the same order
  45999. ** by all database connections. The p->pNext is a list of other
  46000. ** Btrees belonging to the same database connection as the p Btree
  46001. ** which need to be locked after p. If we cannot get a lock on
  46002. ** p, then first unlock all of the others on p->pNext, then wait
  46003. ** for the lock to become available on p, then relock all of the
  46004. ** subsequent Btrees that desire a lock.
  46005. */
  46006. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  46007. Btree *pLater;
  46008. /* Some basic sanity checking on the Btree. The list of Btrees
  46009. ** connected by pNext and pPrev should be in sorted order by
  46010. ** Btree.pBt value. All elements of the list should belong to
  46011. ** the same connection. Only shared Btrees are on the list. */
  46012. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  46013. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  46014. assert( p->pNext==0 || p->pNext->db==p->db );
  46015. assert( p->pPrev==0 || p->pPrev->db==p->db );
  46016. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  46017. /* Check for locking consistency */
  46018. assert( !p->locked || p->wantToLock>0 );
  46019. assert( p->sharable || p->wantToLock==0 );
  46020. /* We should already hold a lock on the database connection */
  46021. assert( sqlite3_mutex_held(p->db->mutex) );
  46022. /* Unless the database is sharable and unlocked, then BtShared.db
  46023. ** should already be set correctly. */
  46024. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  46025. if( !p->sharable ) return;
  46026. p->wantToLock++;
  46027. if( p->locked ) return;
  46028. /* In most cases, we should be able to acquire the lock we
  46029. ** want without having to go throught the ascending lock
  46030. ** procedure that follows. Just be sure not to block.
  46031. */
  46032. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  46033. p->pBt->db = p->db;
  46034. p->locked = 1;
  46035. return;
  46036. }
  46037. /* To avoid deadlock, first release all locks with a larger
  46038. ** BtShared address. Then acquire our lock. Then reacquire
  46039. ** the other BtShared locks that we used to hold in ascending
  46040. ** order.
  46041. */
  46042. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  46043. assert( pLater->sharable );
  46044. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  46045. assert( !pLater->locked || pLater->wantToLock>0 );
  46046. if( pLater->locked ){
  46047. unlockBtreeMutex(pLater);
  46048. }
  46049. }
  46050. lockBtreeMutex(p);
  46051. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  46052. if( pLater->wantToLock ){
  46053. lockBtreeMutex(pLater);
  46054. }
  46055. }
  46056. }
  46057. /*
  46058. ** Exit the recursive mutex on a Btree.
  46059. */
  46060. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  46061. if( p->sharable ){
  46062. assert( p->wantToLock>0 );
  46063. p->wantToLock--;
  46064. if( p->wantToLock==0 ){
  46065. unlockBtreeMutex(p);
  46066. }
  46067. }
  46068. }
  46069. #ifndef NDEBUG
  46070. /*
  46071. ** Return true if the BtShared mutex is held on the btree, or if the
  46072. ** B-Tree is not marked as sharable.
  46073. **
  46074. ** This routine is used only from within assert() statements.
  46075. */
  46076. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  46077. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  46078. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  46079. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  46080. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  46081. return (p->sharable==0 || p->locked);
  46082. }
  46083. #endif
  46084. #ifndef SQLITE_OMIT_INCRBLOB
  46085. /*
  46086. ** Enter and leave a mutex on a Btree given a cursor owned by that
  46087. ** Btree. These entry points are used by incremental I/O and can be
  46088. ** omitted if that module is not used.
  46089. */
  46090. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  46091. sqlite3BtreeEnter(pCur->pBtree);
  46092. }
  46093. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  46094. sqlite3BtreeLeave(pCur->pBtree);
  46095. }
  46096. #endif /* SQLITE_OMIT_INCRBLOB */
  46097. /*
  46098. ** Enter the mutex on every Btree associated with a database
  46099. ** connection. This is needed (for example) prior to parsing
  46100. ** a statement since we will be comparing table and column names
  46101. ** against all schemas and we do not want those schemas being
  46102. ** reset out from under us.
  46103. **
  46104. ** There is a corresponding leave-all procedures.
  46105. **
  46106. ** Enter the mutexes in accending order by BtShared pointer address
  46107. ** to avoid the possibility of deadlock when two threads with
  46108. ** two or more btrees in common both try to lock all their btrees
  46109. ** at the same instant.
  46110. */
  46111. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  46112. int i;
  46113. Btree *p;
  46114. assert( sqlite3_mutex_held(db->mutex) );
  46115. for(i=0; i<db->nDb; i++){
  46116. p = db->aDb[i].pBt;
  46117. if( p ) sqlite3BtreeEnter(p);
  46118. }
  46119. }
  46120. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  46121. int i;
  46122. Btree *p;
  46123. assert( sqlite3_mutex_held(db->mutex) );
  46124. for(i=0; i<db->nDb; i++){
  46125. p = db->aDb[i].pBt;
  46126. if( p ) sqlite3BtreeLeave(p);
  46127. }
  46128. }
  46129. /*
  46130. ** Return true if a particular Btree requires a lock. Return FALSE if
  46131. ** no lock is ever required since it is not sharable.
  46132. */
  46133. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  46134. return p->sharable;
  46135. }
  46136. #ifndef NDEBUG
  46137. /*
  46138. ** Return true if the current thread holds the database connection
  46139. ** mutex and all required BtShared mutexes.
  46140. **
  46141. ** This routine is used inside assert() statements only.
  46142. */
  46143. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  46144. int i;
  46145. if( !sqlite3_mutex_held(db->mutex) ){
  46146. return 0;
  46147. }
  46148. for(i=0; i<db->nDb; i++){
  46149. Btree *p;
  46150. p = db->aDb[i].pBt;
  46151. if( p && p->sharable &&
  46152. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  46153. return 0;
  46154. }
  46155. }
  46156. return 1;
  46157. }
  46158. #endif /* NDEBUG */
  46159. #ifndef NDEBUG
  46160. /*
  46161. ** Return true if the correct mutexes are held for accessing the
  46162. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  46163. ** access are:
  46164. **
  46165. ** (1) The mutex on db
  46166. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  46167. **
  46168. ** If pSchema is not NULL, then iDb is computed from pSchema and
  46169. ** db using sqlite3SchemaToIndex().
  46170. */
  46171. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  46172. Btree *p;
  46173. assert( db!=0 );
  46174. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  46175. assert( iDb>=0 && iDb<db->nDb );
  46176. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  46177. if( iDb==1 ) return 1;
  46178. p = db->aDb[iDb].pBt;
  46179. assert( p!=0 );
  46180. return p->sharable==0 || p->locked==1;
  46181. }
  46182. #endif /* NDEBUG */
  46183. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  46184. /*
  46185. ** The following are special cases for mutex enter routines for use
  46186. ** in single threaded applications that use shared cache. Except for
  46187. ** these two routines, all mutex operations are no-ops in that case and
  46188. ** are null #defines in btree.h.
  46189. **
  46190. ** If shared cache is disabled, then all btree mutex routines, including
  46191. ** the ones below, are no-ops and are null #defines in btree.h.
  46192. */
  46193. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  46194. p->pBt->db = p->db;
  46195. }
  46196. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  46197. int i;
  46198. for(i=0; i<db->nDb; i++){
  46199. Btree *p = db->aDb[i].pBt;
  46200. if( p ){
  46201. p->pBt->db = p->db;
  46202. }
  46203. }
  46204. }
  46205. #endif /* if SQLITE_THREADSAFE */
  46206. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  46207. /************** End of btmutex.c *********************************************/
  46208. /************** Begin file btree.c *******************************************/
  46209. /*
  46210. ** 2004 April 6
  46211. **
  46212. ** The author disclaims copyright to this source code. In place of
  46213. ** a legal notice, here is a blessing:
  46214. **
  46215. ** May you do good and not evil.
  46216. ** May you find forgiveness for yourself and forgive others.
  46217. ** May you share freely, never taking more than you give.
  46218. **
  46219. *************************************************************************
  46220. ** This file implements a external (disk-based) database using BTrees.
  46221. ** See the header comment on "btreeInt.h" for additional information.
  46222. ** Including a description of file format and an overview of operation.
  46223. */
  46224. /*
  46225. ** The header string that appears at the beginning of every
  46226. ** SQLite database.
  46227. */
  46228. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  46229. /*
  46230. ** Set this global variable to 1 to enable tracing using the TRACE
  46231. ** macro.
  46232. */
  46233. #if 0
  46234. int sqlite3BtreeTrace=1; /* True to enable tracing */
  46235. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  46236. #else
  46237. # define TRACE(X)
  46238. #endif
  46239. /*
  46240. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  46241. ** But if the value is zero, make it 65536.
  46242. **
  46243. ** This routine is used to extract the "offset to cell content area" value
  46244. ** from the header of a btree page. If the page size is 65536 and the page
  46245. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  46246. ** This routine makes the necessary adjustment to 65536.
  46247. */
  46248. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  46249. /*
  46250. ** Values passed as the 5th argument to allocateBtreePage()
  46251. */
  46252. #define BTALLOC_ANY 0 /* Allocate any page */
  46253. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  46254. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  46255. /*
  46256. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  46257. ** defined, or 0 if it is. For example:
  46258. **
  46259. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  46260. */
  46261. #ifndef SQLITE_OMIT_AUTOVACUUM
  46262. #define IfNotOmitAV(expr) (expr)
  46263. #else
  46264. #define IfNotOmitAV(expr) 0
  46265. #endif
  46266. #ifndef SQLITE_OMIT_SHARED_CACHE
  46267. /*
  46268. ** A list of BtShared objects that are eligible for participation
  46269. ** in shared cache. This variable has file scope during normal builds,
  46270. ** but the test harness needs to access it so we make it global for
  46271. ** test builds.
  46272. **
  46273. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  46274. */
  46275. #ifdef SQLITE_TEST
  46276. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  46277. #else
  46278. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  46279. #endif
  46280. #endif /* SQLITE_OMIT_SHARED_CACHE */
  46281. #ifndef SQLITE_OMIT_SHARED_CACHE
  46282. /*
  46283. ** Enable or disable the shared pager and schema features.
  46284. **
  46285. ** This routine has no effect on existing database connections.
  46286. ** The shared cache setting effects only future calls to
  46287. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  46288. */
  46289. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  46290. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  46291. return SQLITE_OK;
  46292. }
  46293. #endif
  46294. #ifdef SQLITE_OMIT_SHARED_CACHE
  46295. /*
  46296. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  46297. ** and clearAllSharedCacheTableLocks()
  46298. ** manipulate entries in the BtShared.pLock linked list used to store
  46299. ** shared-cache table level locks. If the library is compiled with the
  46300. ** shared-cache feature disabled, then there is only ever one user
  46301. ** of each BtShared structure and so this locking is not necessary.
  46302. ** So define the lock related functions as no-ops.
  46303. */
  46304. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  46305. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  46306. #define clearAllSharedCacheTableLocks(a)
  46307. #define downgradeAllSharedCacheTableLocks(a)
  46308. #define hasSharedCacheTableLock(a,b,c,d) 1
  46309. #define hasReadConflicts(a, b) 0
  46310. #endif
  46311. #ifndef SQLITE_OMIT_SHARED_CACHE
  46312. #ifdef SQLITE_DEBUG
  46313. /*
  46314. **** This function is only used as part of an assert() statement. ***
  46315. **
  46316. ** Check to see if pBtree holds the required locks to read or write to the
  46317. ** table with root page iRoot. Return 1 if it does and 0 if not.
  46318. **
  46319. ** For example, when writing to a table with root-page iRoot via
  46320. ** Btree connection pBtree:
  46321. **
  46322. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  46323. **
  46324. ** When writing to an index that resides in a sharable database, the
  46325. ** caller should have first obtained a lock specifying the root page of
  46326. ** the corresponding table. This makes things a bit more complicated,
  46327. ** as this module treats each table as a separate structure. To determine
  46328. ** the table corresponding to the index being written, this
  46329. ** function has to search through the database schema.
  46330. **
  46331. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  46332. ** hold a write-lock on the schema table (root page 1). This is also
  46333. ** acceptable.
  46334. */
  46335. static int hasSharedCacheTableLock(
  46336. Btree *pBtree, /* Handle that must hold lock */
  46337. Pgno iRoot, /* Root page of b-tree */
  46338. int isIndex, /* True if iRoot is the root of an index b-tree */
  46339. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  46340. ){
  46341. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  46342. Pgno iTab = 0;
  46343. BtLock *pLock;
  46344. /* If this database is not shareable, or if the client is reading
  46345. ** and has the read-uncommitted flag set, then no lock is required.
  46346. ** Return true immediately.
  46347. */
  46348. if( (pBtree->sharable==0)
  46349. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  46350. ){
  46351. return 1;
  46352. }
  46353. /* If the client is reading or writing an index and the schema is
  46354. ** not loaded, then it is too difficult to actually check to see if
  46355. ** the correct locks are held. So do not bother - just return true.
  46356. ** This case does not come up very often anyhow.
  46357. */
  46358. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  46359. return 1;
  46360. }
  46361. /* Figure out the root-page that the lock should be held on. For table
  46362. ** b-trees, this is just the root page of the b-tree being read or
  46363. ** written. For index b-trees, it is the root page of the associated
  46364. ** table. */
  46365. if( isIndex ){
  46366. HashElem *p;
  46367. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  46368. Index *pIdx = (Index *)sqliteHashData(p);
  46369. if( pIdx->tnum==(int)iRoot ){
  46370. iTab = pIdx->pTable->tnum;
  46371. }
  46372. }
  46373. }else{
  46374. iTab = iRoot;
  46375. }
  46376. /* Search for the required lock. Either a write-lock on root-page iTab, a
  46377. ** write-lock on the schema table, or (if the client is reading) a
  46378. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  46379. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  46380. if( pLock->pBtree==pBtree
  46381. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  46382. && pLock->eLock>=eLockType
  46383. ){
  46384. return 1;
  46385. }
  46386. }
  46387. /* Failed to find the required lock. */
  46388. return 0;
  46389. }
  46390. #endif /* SQLITE_DEBUG */
  46391. #ifdef SQLITE_DEBUG
  46392. /*
  46393. **** This function may be used as part of assert() statements only. ****
  46394. **
  46395. ** Return true if it would be illegal for pBtree to write into the
  46396. ** table or index rooted at iRoot because other shared connections are
  46397. ** simultaneously reading that same table or index.
  46398. **
  46399. ** It is illegal for pBtree to write if some other Btree object that
  46400. ** shares the same BtShared object is currently reading or writing
  46401. ** the iRoot table. Except, if the other Btree object has the
  46402. ** read-uncommitted flag set, then it is OK for the other object to
  46403. ** have a read cursor.
  46404. **
  46405. ** For example, before writing to any part of the table or index
  46406. ** rooted at page iRoot, one should call:
  46407. **
  46408. ** assert( !hasReadConflicts(pBtree, iRoot) );
  46409. */
  46410. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  46411. BtCursor *p;
  46412. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  46413. if( p->pgnoRoot==iRoot
  46414. && p->pBtree!=pBtree
  46415. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  46416. ){
  46417. return 1;
  46418. }
  46419. }
  46420. return 0;
  46421. }
  46422. #endif /* #ifdef SQLITE_DEBUG */
  46423. /*
  46424. ** Query to see if Btree handle p may obtain a lock of type eLock
  46425. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  46426. ** SQLITE_OK if the lock may be obtained (by calling
  46427. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  46428. */
  46429. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  46430. BtShared *pBt = p->pBt;
  46431. BtLock *pIter;
  46432. assert( sqlite3BtreeHoldsMutex(p) );
  46433. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  46434. assert( p->db!=0 );
  46435. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  46436. /* If requesting a write-lock, then the Btree must have an open write
  46437. ** transaction on this file. And, obviously, for this to be so there
  46438. ** must be an open write transaction on the file itself.
  46439. */
  46440. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  46441. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  46442. /* This routine is a no-op if the shared-cache is not enabled */
  46443. if( !p->sharable ){
  46444. return SQLITE_OK;
  46445. }
  46446. /* If some other connection is holding an exclusive lock, the
  46447. ** requested lock may not be obtained.
  46448. */
  46449. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  46450. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  46451. return SQLITE_LOCKED_SHAREDCACHE;
  46452. }
  46453. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  46454. /* The condition (pIter->eLock!=eLock) in the following if(...)
  46455. ** statement is a simplification of:
  46456. **
  46457. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  46458. **
  46459. ** since we know that if eLock==WRITE_LOCK, then no other connection
  46460. ** may hold a WRITE_LOCK on any table in this file (since there can
  46461. ** only be a single writer).
  46462. */
  46463. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  46464. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  46465. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  46466. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  46467. if( eLock==WRITE_LOCK ){
  46468. assert( p==pBt->pWriter );
  46469. pBt->btsFlags |= BTS_PENDING;
  46470. }
  46471. return SQLITE_LOCKED_SHAREDCACHE;
  46472. }
  46473. }
  46474. return SQLITE_OK;
  46475. }
  46476. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  46477. #ifndef SQLITE_OMIT_SHARED_CACHE
  46478. /*
  46479. ** Add a lock on the table with root-page iTable to the shared-btree used
  46480. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  46481. ** WRITE_LOCK.
  46482. **
  46483. ** This function assumes the following:
  46484. **
  46485. ** (a) The specified Btree object p is connected to a sharable
  46486. ** database (one with the BtShared.sharable flag set), and
  46487. **
  46488. ** (b) No other Btree objects hold a lock that conflicts
  46489. ** with the requested lock (i.e. querySharedCacheTableLock() has
  46490. ** already been called and returned SQLITE_OK).
  46491. **
  46492. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  46493. ** is returned if a malloc attempt fails.
  46494. */
  46495. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  46496. BtShared *pBt = p->pBt;
  46497. BtLock *pLock = 0;
  46498. BtLock *pIter;
  46499. assert( sqlite3BtreeHoldsMutex(p) );
  46500. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  46501. assert( p->db!=0 );
  46502. /* A connection with the read-uncommitted flag set will never try to
  46503. ** obtain a read-lock using this function. The only read-lock obtained
  46504. ** by a connection in read-uncommitted mode is on the sqlite_master
  46505. ** table, and that lock is obtained in BtreeBeginTrans(). */
  46506. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  46507. /* This function should only be called on a sharable b-tree after it
  46508. ** has been determined that no other b-tree holds a conflicting lock. */
  46509. assert( p->sharable );
  46510. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  46511. /* First search the list for an existing lock on this table. */
  46512. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  46513. if( pIter->iTable==iTable && pIter->pBtree==p ){
  46514. pLock = pIter;
  46515. break;
  46516. }
  46517. }
  46518. /* If the above search did not find a BtLock struct associating Btree p
  46519. ** with table iTable, allocate one and link it into the list.
  46520. */
  46521. if( !pLock ){
  46522. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  46523. if( !pLock ){
  46524. return SQLITE_NOMEM;
  46525. }
  46526. pLock->iTable = iTable;
  46527. pLock->pBtree = p;
  46528. pLock->pNext = pBt->pLock;
  46529. pBt->pLock = pLock;
  46530. }
  46531. /* Set the BtLock.eLock variable to the maximum of the current lock
  46532. ** and the requested lock. This means if a write-lock was already held
  46533. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  46534. */
  46535. assert( WRITE_LOCK>READ_LOCK );
  46536. if( eLock>pLock->eLock ){
  46537. pLock->eLock = eLock;
  46538. }
  46539. return SQLITE_OK;
  46540. }
  46541. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  46542. #ifndef SQLITE_OMIT_SHARED_CACHE
  46543. /*
  46544. ** Release all the table locks (locks obtained via calls to
  46545. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  46546. **
  46547. ** This function assumes that Btree p has an open read or write
  46548. ** transaction. If it does not, then the BTS_PENDING flag
  46549. ** may be incorrectly cleared.
  46550. */
  46551. static void clearAllSharedCacheTableLocks(Btree *p){
  46552. BtShared *pBt = p->pBt;
  46553. BtLock **ppIter = &pBt->pLock;
  46554. assert( sqlite3BtreeHoldsMutex(p) );
  46555. assert( p->sharable || 0==*ppIter );
  46556. assert( p->inTrans>0 );
  46557. while( *ppIter ){
  46558. BtLock *pLock = *ppIter;
  46559. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  46560. assert( pLock->pBtree->inTrans>=pLock->eLock );
  46561. if( pLock->pBtree==p ){
  46562. *ppIter = pLock->pNext;
  46563. assert( pLock->iTable!=1 || pLock==&p->lock );
  46564. if( pLock->iTable!=1 ){
  46565. sqlite3_free(pLock);
  46566. }
  46567. }else{
  46568. ppIter = &pLock->pNext;
  46569. }
  46570. }
  46571. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  46572. if( pBt->pWriter==p ){
  46573. pBt->pWriter = 0;
  46574. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  46575. }else if( pBt->nTransaction==2 ){
  46576. /* This function is called when Btree p is concluding its
  46577. ** transaction. If there currently exists a writer, and p is not
  46578. ** that writer, then the number of locks held by connections other
  46579. ** than the writer must be about to drop to zero. In this case
  46580. ** set the BTS_PENDING flag to 0.
  46581. **
  46582. ** If there is not currently a writer, then BTS_PENDING must
  46583. ** be zero already. So this next line is harmless in that case.
  46584. */
  46585. pBt->btsFlags &= ~BTS_PENDING;
  46586. }
  46587. }
  46588. /*
  46589. ** This function changes all write-locks held by Btree p into read-locks.
  46590. */
  46591. static void downgradeAllSharedCacheTableLocks(Btree *p){
  46592. BtShared *pBt = p->pBt;
  46593. if( pBt->pWriter==p ){
  46594. BtLock *pLock;
  46595. pBt->pWriter = 0;
  46596. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  46597. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  46598. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  46599. pLock->eLock = READ_LOCK;
  46600. }
  46601. }
  46602. }
  46603. #endif /* SQLITE_OMIT_SHARED_CACHE */
  46604. static void releasePage(MemPage *pPage); /* Forward reference */
  46605. /*
  46606. ***** This routine is used inside of assert() only ****
  46607. **
  46608. ** Verify that the cursor holds the mutex on its BtShared
  46609. */
  46610. #ifdef SQLITE_DEBUG
  46611. static int cursorHoldsMutex(BtCursor *p){
  46612. return sqlite3_mutex_held(p->pBt->mutex);
  46613. }
  46614. #endif
  46615. #ifndef SQLITE_OMIT_INCRBLOB
  46616. /*
  46617. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  46618. */
  46619. static void invalidateOverflowCache(BtCursor *pCur){
  46620. assert( cursorHoldsMutex(pCur) );
  46621. sqlite3_free(pCur->aOverflow);
  46622. pCur->aOverflow = 0;
  46623. }
  46624. /*
  46625. ** Invalidate the overflow page-list cache for all cursors opened
  46626. ** on the shared btree structure pBt.
  46627. */
  46628. static void invalidateAllOverflowCache(BtShared *pBt){
  46629. BtCursor *p;
  46630. assert( sqlite3_mutex_held(pBt->mutex) );
  46631. for(p=pBt->pCursor; p; p=p->pNext){
  46632. invalidateOverflowCache(p);
  46633. }
  46634. }
  46635. /*
  46636. ** This function is called before modifying the contents of a table
  46637. ** to invalidate any incrblob cursors that are open on the
  46638. ** row or one of the rows being modified.
  46639. **
  46640. ** If argument isClearTable is true, then the entire contents of the
  46641. ** table is about to be deleted. In this case invalidate all incrblob
  46642. ** cursors open on any row within the table with root-page pgnoRoot.
  46643. **
  46644. ** Otherwise, if argument isClearTable is false, then the row with
  46645. ** rowid iRow is being replaced or deleted. In this case invalidate
  46646. ** only those incrblob cursors open on that specific row.
  46647. */
  46648. static void invalidateIncrblobCursors(
  46649. Btree *pBtree, /* The database file to check */
  46650. i64 iRow, /* The rowid that might be changing */
  46651. int isClearTable /* True if all rows are being deleted */
  46652. ){
  46653. BtCursor *p;
  46654. BtShared *pBt = pBtree->pBt;
  46655. assert( sqlite3BtreeHoldsMutex(pBtree) );
  46656. for(p=pBt->pCursor; p; p=p->pNext){
  46657. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  46658. p->eState = CURSOR_INVALID;
  46659. }
  46660. }
  46661. }
  46662. #else
  46663. /* Stub functions when INCRBLOB is omitted */
  46664. #define invalidateOverflowCache(x)
  46665. #define invalidateAllOverflowCache(x)
  46666. #define invalidateIncrblobCursors(x,y,z)
  46667. #endif /* SQLITE_OMIT_INCRBLOB */
  46668. /*
  46669. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  46670. ** when a page that previously contained data becomes a free-list leaf
  46671. ** page.
  46672. **
  46673. ** The BtShared.pHasContent bitvec exists to work around an obscure
  46674. ** bug caused by the interaction of two useful IO optimizations surrounding
  46675. ** free-list leaf pages:
  46676. **
  46677. ** 1) When all data is deleted from a page and the page becomes
  46678. ** a free-list leaf page, the page is not written to the database
  46679. ** (as free-list leaf pages contain no meaningful data). Sometimes
  46680. ** such a page is not even journalled (as it will not be modified,
  46681. ** why bother journalling it?).
  46682. **
  46683. ** 2) When a free-list leaf page is reused, its content is not read
  46684. ** from the database or written to the journal file (why should it
  46685. ** be, if it is not at all meaningful?).
  46686. **
  46687. ** By themselves, these optimizations work fine and provide a handy
  46688. ** performance boost to bulk delete or insert operations. However, if
  46689. ** a page is moved to the free-list and then reused within the same
  46690. ** transaction, a problem comes up. If the page is not journalled when
  46691. ** it is moved to the free-list and it is also not journalled when it
  46692. ** is extracted from the free-list and reused, then the original data
  46693. ** may be lost. In the event of a rollback, it may not be possible
  46694. ** to restore the database to its original configuration.
  46695. **
  46696. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  46697. ** moved to become a free-list leaf page, the corresponding bit is
  46698. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  46699. ** optimization 2 above is omitted if the corresponding bit is already
  46700. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  46701. ** at the end of every transaction.
  46702. */
  46703. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  46704. int rc = SQLITE_OK;
  46705. if( !pBt->pHasContent ){
  46706. assert( pgno<=pBt->nPage );
  46707. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  46708. if( !pBt->pHasContent ){
  46709. rc = SQLITE_NOMEM;
  46710. }
  46711. }
  46712. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  46713. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  46714. }
  46715. return rc;
  46716. }
  46717. /*
  46718. ** Query the BtShared.pHasContent vector.
  46719. **
  46720. ** This function is called when a free-list leaf page is removed from the
  46721. ** free-list for reuse. It returns false if it is safe to retrieve the
  46722. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  46723. */
  46724. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  46725. Bitvec *p = pBt->pHasContent;
  46726. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  46727. }
  46728. /*
  46729. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  46730. ** invoked at the conclusion of each write-transaction.
  46731. */
  46732. static void btreeClearHasContent(BtShared *pBt){
  46733. sqlite3BitvecDestroy(pBt->pHasContent);
  46734. pBt->pHasContent = 0;
  46735. }
  46736. /*
  46737. ** Release all of the apPage[] pages for a cursor.
  46738. */
  46739. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  46740. int i;
  46741. for(i=0; i<=pCur->iPage; i++){
  46742. releasePage(pCur->apPage[i]);
  46743. pCur->apPage[i] = 0;
  46744. }
  46745. pCur->iPage = -1;
  46746. }
  46747. /*
  46748. ** Save the current cursor position in the variables BtCursor.nKey
  46749. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  46750. **
  46751. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  46752. ** prior to calling this routine.
  46753. */
  46754. static int saveCursorPosition(BtCursor *pCur){
  46755. int rc;
  46756. assert( CURSOR_VALID==pCur->eState );
  46757. assert( 0==pCur->pKey );
  46758. assert( cursorHoldsMutex(pCur) );
  46759. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  46760. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  46761. /* If this is an intKey table, then the above call to BtreeKeySize()
  46762. ** stores the integer key in pCur->nKey. In this case this value is
  46763. ** all that is required. Otherwise, if pCur is not open on an intKey
  46764. ** table, then malloc space for and store the pCur->nKey bytes of key
  46765. ** data.
  46766. */
  46767. if( 0==pCur->apPage[0]->intKey ){
  46768. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  46769. if( pKey ){
  46770. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  46771. if( rc==SQLITE_OK ){
  46772. pCur->pKey = pKey;
  46773. }else{
  46774. sqlite3_free(pKey);
  46775. }
  46776. }else{
  46777. rc = SQLITE_NOMEM;
  46778. }
  46779. }
  46780. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  46781. if( rc==SQLITE_OK ){
  46782. btreeReleaseAllCursorPages(pCur);
  46783. pCur->eState = CURSOR_REQUIRESEEK;
  46784. }
  46785. invalidateOverflowCache(pCur);
  46786. return rc;
  46787. }
  46788. /*
  46789. ** Save the positions of all cursors (except pExcept) that are open on
  46790. ** the table with root-page iRoot. Usually, this is called just before cursor
  46791. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  46792. */
  46793. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  46794. BtCursor *p;
  46795. assert( sqlite3_mutex_held(pBt->mutex) );
  46796. assert( pExcept==0 || pExcept->pBt==pBt );
  46797. for(p=pBt->pCursor; p; p=p->pNext){
  46798. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  46799. if( p->eState==CURSOR_VALID ){
  46800. int rc = saveCursorPosition(p);
  46801. if( SQLITE_OK!=rc ){
  46802. return rc;
  46803. }
  46804. }else{
  46805. testcase( p->iPage>0 );
  46806. btreeReleaseAllCursorPages(p);
  46807. }
  46808. }
  46809. }
  46810. return SQLITE_OK;
  46811. }
  46812. /*
  46813. ** Clear the current cursor position.
  46814. */
  46815. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  46816. assert( cursorHoldsMutex(pCur) );
  46817. sqlite3_free(pCur->pKey);
  46818. pCur->pKey = 0;
  46819. pCur->eState = CURSOR_INVALID;
  46820. }
  46821. /*
  46822. ** In this version of BtreeMoveto, pKey is a packed index record
  46823. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  46824. ** record and then call BtreeMovetoUnpacked() to do the work.
  46825. */
  46826. static int btreeMoveto(
  46827. BtCursor *pCur, /* Cursor open on the btree to be searched */
  46828. const void *pKey, /* Packed key if the btree is an index */
  46829. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  46830. int bias, /* Bias search to the high end */
  46831. int *pRes /* Write search results here */
  46832. ){
  46833. int rc; /* Status code */
  46834. UnpackedRecord *pIdxKey; /* Unpacked index key */
  46835. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  46836. char *pFree = 0;
  46837. if( pKey ){
  46838. assert( nKey==(i64)(int)nKey );
  46839. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  46840. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  46841. );
  46842. if( pIdxKey==0 ) return SQLITE_NOMEM;
  46843. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  46844. }else{
  46845. pIdxKey = 0;
  46846. }
  46847. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  46848. if( pFree ){
  46849. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  46850. }
  46851. return rc;
  46852. }
  46853. /*
  46854. ** Restore the cursor to the position it was in (or as close to as possible)
  46855. ** when saveCursorPosition() was called. Note that this call deletes the
  46856. ** saved position info stored by saveCursorPosition(), so there can be
  46857. ** at most one effective restoreCursorPosition() call after each
  46858. ** saveCursorPosition().
  46859. */
  46860. static int btreeRestoreCursorPosition(BtCursor *pCur){
  46861. int rc;
  46862. assert( cursorHoldsMutex(pCur) );
  46863. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  46864. if( pCur->eState==CURSOR_FAULT ){
  46865. return pCur->skipNext;
  46866. }
  46867. pCur->eState = CURSOR_INVALID;
  46868. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  46869. if( rc==SQLITE_OK ){
  46870. sqlite3_free(pCur->pKey);
  46871. pCur->pKey = 0;
  46872. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  46873. }
  46874. return rc;
  46875. }
  46876. #define restoreCursorPosition(p) \
  46877. (p->eState>=CURSOR_REQUIRESEEK ? \
  46878. btreeRestoreCursorPosition(p) : \
  46879. SQLITE_OK)
  46880. /*
  46881. ** Determine whether or not a cursor has moved from the position it
  46882. ** was last placed at. Cursors can move when the row they are pointing
  46883. ** at is deleted out from under them.
  46884. **
  46885. ** This routine returns an error code if something goes wrong. The
  46886. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  46887. */
  46888. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  46889. int rc;
  46890. rc = restoreCursorPosition(pCur);
  46891. if( rc ){
  46892. *pHasMoved = 1;
  46893. return rc;
  46894. }
  46895. if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
  46896. *pHasMoved = 1;
  46897. }else{
  46898. *pHasMoved = 0;
  46899. }
  46900. return SQLITE_OK;
  46901. }
  46902. #ifndef SQLITE_OMIT_AUTOVACUUM
  46903. /*
  46904. ** Given a page number of a regular database page, return the page
  46905. ** number for the pointer-map page that contains the entry for the
  46906. ** input page number.
  46907. **
  46908. ** Return 0 (not a valid page) for pgno==1 since there is
  46909. ** no pointer map associated with page 1. The integrity_check logic
  46910. ** requires that ptrmapPageno(*,1)!=1.
  46911. */
  46912. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  46913. int nPagesPerMapPage;
  46914. Pgno iPtrMap, ret;
  46915. assert( sqlite3_mutex_held(pBt->mutex) );
  46916. if( pgno<2 ) return 0;
  46917. nPagesPerMapPage = (pBt->usableSize/5)+1;
  46918. iPtrMap = (pgno-2)/nPagesPerMapPage;
  46919. ret = (iPtrMap*nPagesPerMapPage) + 2;
  46920. if( ret==PENDING_BYTE_PAGE(pBt) ){
  46921. ret++;
  46922. }
  46923. return ret;
  46924. }
  46925. /*
  46926. ** Write an entry into the pointer map.
  46927. **
  46928. ** This routine updates the pointer map entry for page number 'key'
  46929. ** so that it maps to type 'eType' and parent page number 'pgno'.
  46930. **
  46931. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  46932. ** a no-op. If an error occurs, the appropriate error code is written
  46933. ** into *pRC.
  46934. */
  46935. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  46936. DbPage *pDbPage; /* The pointer map page */
  46937. u8 *pPtrmap; /* The pointer map data */
  46938. Pgno iPtrmap; /* The pointer map page number */
  46939. int offset; /* Offset in pointer map page */
  46940. int rc; /* Return code from subfunctions */
  46941. if( *pRC ) return;
  46942. assert( sqlite3_mutex_held(pBt->mutex) );
  46943. /* The master-journal page number must never be used as a pointer map page */
  46944. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  46945. assert( pBt->autoVacuum );
  46946. if( key==0 ){
  46947. *pRC = SQLITE_CORRUPT_BKPT;
  46948. return;
  46949. }
  46950. iPtrmap = PTRMAP_PAGENO(pBt, key);
  46951. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  46952. if( rc!=SQLITE_OK ){
  46953. *pRC = rc;
  46954. return;
  46955. }
  46956. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  46957. if( offset<0 ){
  46958. *pRC = SQLITE_CORRUPT_BKPT;
  46959. goto ptrmap_exit;
  46960. }
  46961. assert( offset <= (int)pBt->usableSize-5 );
  46962. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  46963. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  46964. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  46965. *pRC= rc = sqlite3PagerWrite(pDbPage);
  46966. if( rc==SQLITE_OK ){
  46967. pPtrmap[offset] = eType;
  46968. put4byte(&pPtrmap[offset+1], parent);
  46969. }
  46970. }
  46971. ptrmap_exit:
  46972. sqlite3PagerUnref(pDbPage);
  46973. }
  46974. /*
  46975. ** Read an entry from the pointer map.
  46976. **
  46977. ** This routine retrieves the pointer map entry for page 'key', writing
  46978. ** the type and parent page number to *pEType and *pPgno respectively.
  46979. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  46980. */
  46981. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  46982. DbPage *pDbPage; /* The pointer map page */
  46983. int iPtrmap; /* Pointer map page index */
  46984. u8 *pPtrmap; /* Pointer map page data */
  46985. int offset; /* Offset of entry in pointer map */
  46986. int rc;
  46987. assert( sqlite3_mutex_held(pBt->mutex) );
  46988. iPtrmap = PTRMAP_PAGENO(pBt, key);
  46989. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  46990. if( rc!=0 ){
  46991. return rc;
  46992. }
  46993. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  46994. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  46995. if( offset<0 ){
  46996. sqlite3PagerUnref(pDbPage);
  46997. return SQLITE_CORRUPT_BKPT;
  46998. }
  46999. assert( offset <= (int)pBt->usableSize-5 );
  47000. assert( pEType!=0 );
  47001. *pEType = pPtrmap[offset];
  47002. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  47003. sqlite3PagerUnref(pDbPage);
  47004. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  47005. return SQLITE_OK;
  47006. }
  47007. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  47008. #define ptrmapPut(w,x,y,z,rc)
  47009. #define ptrmapGet(w,x,y,z) SQLITE_OK
  47010. #define ptrmapPutOvflPtr(x, y, rc)
  47011. #endif
  47012. /*
  47013. ** Given a btree page and a cell index (0 means the first cell on
  47014. ** the page, 1 means the second cell, and so forth) return a pointer
  47015. ** to the cell content.
  47016. **
  47017. ** This routine works only for pages that do not contain overflow cells.
  47018. */
  47019. #define findCell(P,I) \
  47020. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  47021. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  47022. /*
  47023. ** This a more complex version of findCell() that works for
  47024. ** pages that do contain overflow cells.
  47025. */
  47026. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  47027. int i;
  47028. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47029. for(i=pPage->nOverflow-1; i>=0; i--){
  47030. int k;
  47031. k = pPage->aiOvfl[i];
  47032. if( k<=iCell ){
  47033. if( k==iCell ){
  47034. return pPage->apOvfl[i];
  47035. }
  47036. iCell--;
  47037. }
  47038. }
  47039. return findCell(pPage, iCell);
  47040. }
  47041. /*
  47042. ** Parse a cell content block and fill in the CellInfo structure. There
  47043. ** are two versions of this function. btreeParseCell() takes a
  47044. ** cell index as the second argument and btreeParseCellPtr()
  47045. ** takes a pointer to the body of the cell as its second argument.
  47046. **
  47047. ** Within this file, the parseCell() macro can be called instead of
  47048. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  47049. */
  47050. static void btreeParseCellPtr(
  47051. MemPage *pPage, /* Page containing the cell */
  47052. u8 *pCell, /* Pointer to the cell text. */
  47053. CellInfo *pInfo /* Fill in this structure */
  47054. ){
  47055. u16 n; /* Number bytes in cell content header */
  47056. u32 nPayload; /* Number of bytes of cell payload */
  47057. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47058. pInfo->pCell = pCell;
  47059. assert( pPage->leaf==0 || pPage->leaf==1 );
  47060. n = pPage->childPtrSize;
  47061. assert( n==4-4*pPage->leaf );
  47062. if( pPage->intKey ){
  47063. if( pPage->hasData ){
  47064. n += getVarint32(&pCell[n], nPayload);
  47065. }else{
  47066. nPayload = 0;
  47067. }
  47068. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  47069. pInfo->nData = nPayload;
  47070. }else{
  47071. pInfo->nData = 0;
  47072. n += getVarint32(&pCell[n], nPayload);
  47073. pInfo->nKey = nPayload;
  47074. }
  47075. pInfo->nPayload = nPayload;
  47076. pInfo->nHeader = n;
  47077. testcase( nPayload==pPage->maxLocal );
  47078. testcase( nPayload==pPage->maxLocal+1 );
  47079. if( likely(nPayload<=pPage->maxLocal) ){
  47080. /* This is the (easy) common case where the entire payload fits
  47081. ** on the local page. No overflow is required.
  47082. */
  47083. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  47084. pInfo->nLocal = (u16)nPayload;
  47085. pInfo->iOverflow = 0;
  47086. }else{
  47087. /* If the payload will not fit completely on the local page, we have
  47088. ** to decide how much to store locally and how much to spill onto
  47089. ** overflow pages. The strategy is to minimize the amount of unused
  47090. ** space on overflow pages while keeping the amount of local storage
  47091. ** in between minLocal and maxLocal.
  47092. **
  47093. ** Warning: changing the way overflow payload is distributed in any
  47094. ** way will result in an incompatible file format.
  47095. */
  47096. int minLocal; /* Minimum amount of payload held locally */
  47097. int maxLocal; /* Maximum amount of payload held locally */
  47098. int surplus; /* Overflow payload available for local storage */
  47099. minLocal = pPage->minLocal;
  47100. maxLocal = pPage->maxLocal;
  47101. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  47102. testcase( surplus==maxLocal );
  47103. testcase( surplus==maxLocal+1 );
  47104. if( surplus <= maxLocal ){
  47105. pInfo->nLocal = (u16)surplus;
  47106. }else{
  47107. pInfo->nLocal = (u16)minLocal;
  47108. }
  47109. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  47110. pInfo->nSize = pInfo->iOverflow + 4;
  47111. }
  47112. }
  47113. #define parseCell(pPage, iCell, pInfo) \
  47114. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  47115. static void btreeParseCell(
  47116. MemPage *pPage, /* Page containing the cell */
  47117. int iCell, /* The cell index. First cell is 0 */
  47118. CellInfo *pInfo /* Fill in this structure */
  47119. ){
  47120. parseCell(pPage, iCell, pInfo);
  47121. }
  47122. /*
  47123. ** Compute the total number of bytes that a Cell needs in the cell
  47124. ** data area of the btree-page. The return number includes the cell
  47125. ** data header and the local payload, but not any overflow page or
  47126. ** the space used by the cell pointer.
  47127. */
  47128. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  47129. u8 *pIter = &pCell[pPage->childPtrSize];
  47130. u32 nSize;
  47131. #ifdef SQLITE_DEBUG
  47132. /* The value returned by this function should always be the same as
  47133. ** the (CellInfo.nSize) value found by doing a full parse of the
  47134. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  47135. ** this function verifies that this invariant is not violated. */
  47136. CellInfo debuginfo;
  47137. btreeParseCellPtr(pPage, pCell, &debuginfo);
  47138. #endif
  47139. if( pPage->intKey ){
  47140. u8 *pEnd;
  47141. if( pPage->hasData ){
  47142. pIter += getVarint32(pIter, nSize);
  47143. }else{
  47144. nSize = 0;
  47145. }
  47146. /* pIter now points at the 64-bit integer key value, a variable length
  47147. ** integer. The following block moves pIter to point at the first byte
  47148. ** past the end of the key value. */
  47149. pEnd = &pIter[9];
  47150. while( (*pIter++)&0x80 && pIter<pEnd );
  47151. }else{
  47152. pIter += getVarint32(pIter, nSize);
  47153. }
  47154. testcase( nSize==pPage->maxLocal );
  47155. testcase( nSize==pPage->maxLocal+1 );
  47156. if( nSize>pPage->maxLocal ){
  47157. int minLocal = pPage->minLocal;
  47158. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  47159. testcase( nSize==pPage->maxLocal );
  47160. testcase( nSize==pPage->maxLocal+1 );
  47161. if( nSize>pPage->maxLocal ){
  47162. nSize = minLocal;
  47163. }
  47164. nSize += 4;
  47165. }
  47166. nSize += (u32)(pIter - pCell);
  47167. /* The minimum size of any cell is 4 bytes. */
  47168. if( nSize<4 ){
  47169. nSize = 4;
  47170. }
  47171. assert( nSize==debuginfo.nSize );
  47172. return (u16)nSize;
  47173. }
  47174. #ifdef SQLITE_DEBUG
  47175. /* This variation on cellSizePtr() is used inside of assert() statements
  47176. ** only. */
  47177. static u16 cellSize(MemPage *pPage, int iCell){
  47178. return cellSizePtr(pPage, findCell(pPage, iCell));
  47179. }
  47180. #endif
  47181. #ifndef SQLITE_OMIT_AUTOVACUUM
  47182. /*
  47183. ** If the cell pCell, part of page pPage contains a pointer
  47184. ** to an overflow page, insert an entry into the pointer-map
  47185. ** for the overflow page.
  47186. */
  47187. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  47188. CellInfo info;
  47189. if( *pRC ) return;
  47190. assert( pCell!=0 );
  47191. btreeParseCellPtr(pPage, pCell, &info);
  47192. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  47193. if( info.iOverflow ){
  47194. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  47195. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  47196. }
  47197. }
  47198. #endif
  47199. /*
  47200. ** Defragment the page given. All Cells are moved to the
  47201. ** end of the page and all free space is collected into one
  47202. ** big FreeBlk that occurs in between the header and cell
  47203. ** pointer array and the cell content area.
  47204. */
  47205. static int defragmentPage(MemPage *pPage){
  47206. int i; /* Loop counter */
  47207. int pc; /* Address of a i-th cell */
  47208. int hdr; /* Offset to the page header */
  47209. int size; /* Size of a cell */
  47210. int usableSize; /* Number of usable bytes on a page */
  47211. int cellOffset; /* Offset to the cell pointer array */
  47212. int cbrk; /* Offset to the cell content area */
  47213. int nCell; /* Number of cells on the page */
  47214. unsigned char *data; /* The page data */
  47215. unsigned char *temp; /* Temp area for cell content */
  47216. int iCellFirst; /* First allowable cell index */
  47217. int iCellLast; /* Last possible cell index */
  47218. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47219. assert( pPage->pBt!=0 );
  47220. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  47221. assert( pPage->nOverflow==0 );
  47222. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47223. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  47224. data = pPage->aData;
  47225. hdr = pPage->hdrOffset;
  47226. cellOffset = pPage->cellOffset;
  47227. nCell = pPage->nCell;
  47228. assert( nCell==get2byte(&data[hdr+3]) );
  47229. usableSize = pPage->pBt->usableSize;
  47230. cbrk = get2byte(&data[hdr+5]);
  47231. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  47232. cbrk = usableSize;
  47233. iCellFirst = cellOffset + 2*nCell;
  47234. iCellLast = usableSize - 4;
  47235. for(i=0; i<nCell; i++){
  47236. u8 *pAddr; /* The i-th cell pointer */
  47237. pAddr = &data[cellOffset + i*2];
  47238. pc = get2byte(pAddr);
  47239. testcase( pc==iCellFirst );
  47240. testcase( pc==iCellLast );
  47241. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47242. /* These conditions have already been verified in btreeInitPage()
  47243. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  47244. */
  47245. if( pc<iCellFirst || pc>iCellLast ){
  47246. return SQLITE_CORRUPT_BKPT;
  47247. }
  47248. #endif
  47249. assert( pc>=iCellFirst && pc<=iCellLast );
  47250. size = cellSizePtr(pPage, &temp[pc]);
  47251. cbrk -= size;
  47252. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47253. if( cbrk<iCellFirst ){
  47254. return SQLITE_CORRUPT_BKPT;
  47255. }
  47256. #else
  47257. if( cbrk<iCellFirst || pc+size>usableSize ){
  47258. return SQLITE_CORRUPT_BKPT;
  47259. }
  47260. #endif
  47261. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  47262. testcase( cbrk+size==usableSize );
  47263. testcase( pc+size==usableSize );
  47264. memcpy(&data[cbrk], &temp[pc], size);
  47265. put2byte(pAddr, cbrk);
  47266. }
  47267. assert( cbrk>=iCellFirst );
  47268. put2byte(&data[hdr+5], cbrk);
  47269. data[hdr+1] = 0;
  47270. data[hdr+2] = 0;
  47271. data[hdr+7] = 0;
  47272. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  47273. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47274. if( cbrk-iCellFirst!=pPage->nFree ){
  47275. return SQLITE_CORRUPT_BKPT;
  47276. }
  47277. return SQLITE_OK;
  47278. }
  47279. /*
  47280. ** Allocate nByte bytes of space from within the B-Tree page passed
  47281. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  47282. ** of the first byte of allocated space. Return either SQLITE_OK or
  47283. ** an error code (usually SQLITE_CORRUPT).
  47284. **
  47285. ** The caller guarantees that there is sufficient space to make the
  47286. ** allocation. This routine might need to defragment in order to bring
  47287. ** all the space together, however. This routine will avoid using
  47288. ** the first two bytes past the cell pointer area since presumably this
  47289. ** allocation is being made in order to insert a new cell, so we will
  47290. ** also end up needing a new cell pointer.
  47291. */
  47292. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  47293. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  47294. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  47295. int nFrag; /* Number of fragmented bytes on pPage */
  47296. int top; /* First byte of cell content area */
  47297. int gap; /* First byte of gap between cell pointers and cell content */
  47298. int rc; /* Integer return code */
  47299. int usableSize; /* Usable size of the page */
  47300. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47301. assert( pPage->pBt );
  47302. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47303. assert( nByte>=0 ); /* Minimum cell size is 4 */
  47304. assert( pPage->nFree>=nByte );
  47305. assert( pPage->nOverflow==0 );
  47306. usableSize = pPage->pBt->usableSize;
  47307. assert( nByte < usableSize-8 );
  47308. nFrag = data[hdr+7];
  47309. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  47310. gap = pPage->cellOffset + 2*pPage->nCell;
  47311. top = get2byteNotZero(&data[hdr+5]);
  47312. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  47313. testcase( gap+2==top );
  47314. testcase( gap+1==top );
  47315. testcase( gap==top );
  47316. if( nFrag>=60 ){
  47317. /* Always defragment highly fragmented pages */
  47318. rc = defragmentPage(pPage);
  47319. if( rc ) return rc;
  47320. top = get2byteNotZero(&data[hdr+5]);
  47321. }else if( gap+2<=top ){
  47322. /* Search the freelist looking for a free slot big enough to satisfy
  47323. ** the request. The allocation is made from the first free slot in
  47324. ** the list that is large enough to accomadate it.
  47325. */
  47326. int pc, addr;
  47327. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  47328. int size; /* Size of the free slot */
  47329. if( pc>usableSize-4 || pc<addr+4 ){
  47330. return SQLITE_CORRUPT_BKPT;
  47331. }
  47332. size = get2byte(&data[pc+2]);
  47333. if( size>=nByte ){
  47334. int x = size - nByte;
  47335. testcase( x==4 );
  47336. testcase( x==3 );
  47337. if( x<4 ){
  47338. /* Remove the slot from the free-list. Update the number of
  47339. ** fragmented bytes within the page. */
  47340. memcpy(&data[addr], &data[pc], 2);
  47341. data[hdr+7] = (u8)(nFrag + x);
  47342. }else if( size+pc > usableSize ){
  47343. return SQLITE_CORRUPT_BKPT;
  47344. }else{
  47345. /* The slot remains on the free-list. Reduce its size to account
  47346. ** for the portion used by the new allocation. */
  47347. put2byte(&data[pc+2], x);
  47348. }
  47349. *pIdx = pc + x;
  47350. return SQLITE_OK;
  47351. }
  47352. }
  47353. }
  47354. /* Check to make sure there is enough space in the gap to satisfy
  47355. ** the allocation. If not, defragment.
  47356. */
  47357. testcase( gap+2+nByte==top );
  47358. if( gap+2+nByte>top ){
  47359. rc = defragmentPage(pPage);
  47360. if( rc ) return rc;
  47361. top = get2byteNotZero(&data[hdr+5]);
  47362. assert( gap+nByte<=top );
  47363. }
  47364. /* Allocate memory from the gap in between the cell pointer array
  47365. ** and the cell content area. The btreeInitPage() call has already
  47366. ** validated the freelist. Given that the freelist is valid, there
  47367. ** is no way that the allocation can extend off the end of the page.
  47368. ** The assert() below verifies the previous sentence.
  47369. */
  47370. top -= nByte;
  47371. put2byte(&data[hdr+5], top);
  47372. assert( top+nByte <= (int)pPage->pBt->usableSize );
  47373. *pIdx = top;
  47374. return SQLITE_OK;
  47375. }
  47376. /*
  47377. ** Return a section of the pPage->aData to the freelist.
  47378. ** The first byte of the new free block is pPage->aDisk[start]
  47379. ** and the size of the block is "size" bytes.
  47380. **
  47381. ** Most of the effort here is involved in coalesing adjacent
  47382. ** free blocks into a single big free block.
  47383. */
  47384. static int freeSpace(MemPage *pPage, int start, int size){
  47385. int addr, pbegin, hdr;
  47386. int iLast; /* Largest possible freeblock offset */
  47387. unsigned char *data = pPage->aData;
  47388. assert( pPage->pBt!=0 );
  47389. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47390. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  47391. assert( (start + size) <= (int)pPage->pBt->usableSize );
  47392. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47393. assert( size>=0 ); /* Minimum cell size is 4 */
  47394. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  47395. /* Overwrite deleted information with zeros when the secure_delete
  47396. ** option is enabled */
  47397. memset(&data[start], 0, size);
  47398. }
  47399. /* Add the space back into the linked list of freeblocks. Note that
  47400. ** even though the freeblock list was checked by btreeInitPage(),
  47401. ** btreeInitPage() did not detect overlapping cells or
  47402. ** freeblocks that overlapped cells. Nor does it detect when the
  47403. ** cell content area exceeds the value in the page header. If these
  47404. ** situations arise, then subsequent insert operations might corrupt
  47405. ** the freelist. So we do need to check for corruption while scanning
  47406. ** the freelist.
  47407. */
  47408. hdr = pPage->hdrOffset;
  47409. addr = hdr + 1;
  47410. iLast = pPage->pBt->usableSize - 4;
  47411. assert( start<=iLast );
  47412. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  47413. if( pbegin<addr+4 ){
  47414. return SQLITE_CORRUPT_BKPT;
  47415. }
  47416. addr = pbegin;
  47417. }
  47418. if( pbegin>iLast ){
  47419. return SQLITE_CORRUPT_BKPT;
  47420. }
  47421. assert( pbegin>addr || pbegin==0 );
  47422. put2byte(&data[addr], start);
  47423. put2byte(&data[start], pbegin);
  47424. put2byte(&data[start+2], size);
  47425. pPage->nFree = pPage->nFree + (u16)size;
  47426. /* Coalesce adjacent free blocks */
  47427. addr = hdr + 1;
  47428. while( (pbegin = get2byte(&data[addr]))>0 ){
  47429. int pnext, psize, x;
  47430. assert( pbegin>addr );
  47431. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  47432. pnext = get2byte(&data[pbegin]);
  47433. psize = get2byte(&data[pbegin+2]);
  47434. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  47435. int frag = pnext - (pbegin+psize);
  47436. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  47437. return SQLITE_CORRUPT_BKPT;
  47438. }
  47439. data[hdr+7] -= (u8)frag;
  47440. x = get2byte(&data[pnext]);
  47441. put2byte(&data[pbegin], x);
  47442. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  47443. put2byte(&data[pbegin+2], x);
  47444. }else{
  47445. addr = pbegin;
  47446. }
  47447. }
  47448. /* If the cell content area begins with a freeblock, remove it. */
  47449. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  47450. int top;
  47451. pbegin = get2byte(&data[hdr+1]);
  47452. memcpy(&data[hdr+1], &data[pbegin], 2);
  47453. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  47454. put2byte(&data[hdr+5], top);
  47455. }
  47456. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47457. return SQLITE_OK;
  47458. }
  47459. /*
  47460. ** Decode the flags byte (the first byte of the header) for a page
  47461. ** and initialize fields of the MemPage structure accordingly.
  47462. **
  47463. ** Only the following combinations are supported. Anything different
  47464. ** indicates a corrupt database files:
  47465. **
  47466. ** PTF_ZERODATA
  47467. ** PTF_ZERODATA | PTF_LEAF
  47468. ** PTF_LEAFDATA | PTF_INTKEY
  47469. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  47470. */
  47471. static int decodeFlags(MemPage *pPage, int flagByte){
  47472. BtShared *pBt; /* A copy of pPage->pBt */
  47473. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  47474. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47475. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  47476. flagByte &= ~PTF_LEAF;
  47477. pPage->childPtrSize = 4-4*pPage->leaf;
  47478. pBt = pPage->pBt;
  47479. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  47480. pPage->intKey = 1;
  47481. pPage->hasData = pPage->leaf;
  47482. pPage->maxLocal = pBt->maxLeaf;
  47483. pPage->minLocal = pBt->minLeaf;
  47484. }else if( flagByte==PTF_ZERODATA ){
  47485. pPage->intKey = 0;
  47486. pPage->hasData = 0;
  47487. pPage->maxLocal = pBt->maxLocal;
  47488. pPage->minLocal = pBt->minLocal;
  47489. }else{
  47490. return SQLITE_CORRUPT_BKPT;
  47491. }
  47492. pPage->max1bytePayload = pBt->max1bytePayload;
  47493. return SQLITE_OK;
  47494. }
  47495. /*
  47496. ** Initialize the auxiliary information for a disk block.
  47497. **
  47498. ** Return SQLITE_OK on success. If we see that the page does
  47499. ** not contain a well-formed database page, then return
  47500. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  47501. ** guarantee that the page is well-formed. It only shows that
  47502. ** we failed to detect any corruption.
  47503. */
  47504. static int btreeInitPage(MemPage *pPage){
  47505. assert( pPage->pBt!=0 );
  47506. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47507. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  47508. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  47509. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  47510. if( !pPage->isInit ){
  47511. u16 pc; /* Address of a freeblock within pPage->aData[] */
  47512. u8 hdr; /* Offset to beginning of page header */
  47513. u8 *data; /* Equal to pPage->aData */
  47514. BtShared *pBt; /* The main btree structure */
  47515. int usableSize; /* Amount of usable space on each page */
  47516. u16 cellOffset; /* Offset from start of page to first cell pointer */
  47517. int nFree; /* Number of unused bytes on the page */
  47518. int top; /* First byte of the cell content area */
  47519. int iCellFirst; /* First allowable cell or freeblock offset */
  47520. int iCellLast; /* Last possible cell or freeblock offset */
  47521. pBt = pPage->pBt;
  47522. hdr = pPage->hdrOffset;
  47523. data = pPage->aData;
  47524. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  47525. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  47526. pPage->maskPage = (u16)(pBt->pageSize - 1);
  47527. pPage->nOverflow = 0;
  47528. usableSize = pBt->usableSize;
  47529. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  47530. pPage->aDataEnd = &data[usableSize];
  47531. pPage->aCellIdx = &data[cellOffset];
  47532. top = get2byteNotZero(&data[hdr+5]);
  47533. pPage->nCell = get2byte(&data[hdr+3]);
  47534. if( pPage->nCell>MX_CELL(pBt) ){
  47535. /* To many cells for a single page. The page must be corrupt */
  47536. return SQLITE_CORRUPT_BKPT;
  47537. }
  47538. testcase( pPage->nCell==MX_CELL(pBt) );
  47539. /* A malformed database page might cause us to read past the end
  47540. ** of page when parsing a cell.
  47541. **
  47542. ** The following block of code checks early to see if a cell extends
  47543. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  47544. ** returned if it does.
  47545. */
  47546. iCellFirst = cellOffset + 2*pPage->nCell;
  47547. iCellLast = usableSize - 4;
  47548. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  47549. {
  47550. int i; /* Index into the cell pointer array */
  47551. int sz; /* Size of a cell */
  47552. if( !pPage->leaf ) iCellLast--;
  47553. for(i=0; i<pPage->nCell; i++){
  47554. pc = get2byte(&data[cellOffset+i*2]);
  47555. testcase( pc==iCellFirst );
  47556. testcase( pc==iCellLast );
  47557. if( pc<iCellFirst || pc>iCellLast ){
  47558. return SQLITE_CORRUPT_BKPT;
  47559. }
  47560. sz = cellSizePtr(pPage, &data[pc]);
  47561. testcase( pc+sz==usableSize );
  47562. if( pc+sz>usableSize ){
  47563. return SQLITE_CORRUPT_BKPT;
  47564. }
  47565. }
  47566. if( !pPage->leaf ) iCellLast++;
  47567. }
  47568. #endif
  47569. /* Compute the total free space on the page */
  47570. pc = get2byte(&data[hdr+1]);
  47571. nFree = data[hdr+7] + top;
  47572. while( pc>0 ){
  47573. u16 next, size;
  47574. if( pc<iCellFirst || pc>iCellLast ){
  47575. /* Start of free block is off the page */
  47576. return SQLITE_CORRUPT_BKPT;
  47577. }
  47578. next = get2byte(&data[pc]);
  47579. size = get2byte(&data[pc+2]);
  47580. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  47581. /* Free blocks must be in ascending order. And the last byte of
  47582. ** the free-block must lie on the database page. */
  47583. return SQLITE_CORRUPT_BKPT;
  47584. }
  47585. nFree = nFree + size;
  47586. pc = next;
  47587. }
  47588. /* At this point, nFree contains the sum of the offset to the start
  47589. ** of the cell-content area plus the number of free bytes within
  47590. ** the cell-content area. If this is greater than the usable-size
  47591. ** of the page, then the page must be corrupted. This check also
  47592. ** serves to verify that the offset to the start of the cell-content
  47593. ** area, according to the page header, lies within the page.
  47594. */
  47595. if( nFree>usableSize ){
  47596. return SQLITE_CORRUPT_BKPT;
  47597. }
  47598. pPage->nFree = (u16)(nFree - iCellFirst);
  47599. pPage->isInit = 1;
  47600. }
  47601. return SQLITE_OK;
  47602. }
  47603. /*
  47604. ** Set up a raw page so that it looks like a database page holding
  47605. ** no entries.
  47606. */
  47607. static void zeroPage(MemPage *pPage, int flags){
  47608. unsigned char *data = pPage->aData;
  47609. BtShared *pBt = pPage->pBt;
  47610. u8 hdr = pPage->hdrOffset;
  47611. u16 first;
  47612. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  47613. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  47614. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  47615. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47616. assert( sqlite3_mutex_held(pBt->mutex) );
  47617. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  47618. memset(&data[hdr], 0, pBt->usableSize - hdr);
  47619. }
  47620. data[hdr] = (char)flags;
  47621. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  47622. memset(&data[hdr+1], 0, 4);
  47623. data[hdr+7] = 0;
  47624. put2byte(&data[hdr+5], pBt->usableSize);
  47625. pPage->nFree = (u16)(pBt->usableSize - first);
  47626. decodeFlags(pPage, flags);
  47627. pPage->hdrOffset = hdr;
  47628. pPage->cellOffset = first;
  47629. pPage->aDataEnd = &data[pBt->usableSize];
  47630. pPage->aCellIdx = &data[first];
  47631. pPage->nOverflow = 0;
  47632. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  47633. pPage->maskPage = (u16)(pBt->pageSize - 1);
  47634. pPage->nCell = 0;
  47635. pPage->isInit = 1;
  47636. }
  47637. /*
  47638. ** Convert a DbPage obtained from the pager into a MemPage used by
  47639. ** the btree layer.
  47640. */
  47641. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  47642. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  47643. pPage->aData = sqlite3PagerGetData(pDbPage);
  47644. pPage->pDbPage = pDbPage;
  47645. pPage->pBt = pBt;
  47646. pPage->pgno = pgno;
  47647. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  47648. return pPage;
  47649. }
  47650. /*
  47651. ** Get a page from the pager. Initialize the MemPage.pBt and
  47652. ** MemPage.aData elements if needed.
  47653. **
  47654. ** If the noContent flag is set, it means that we do not care about
  47655. ** the content of the page at this time. So do not go to the disk
  47656. ** to fetch the content. Just fill in the content with zeros for now.
  47657. ** If in the future we call sqlite3PagerWrite() on this page, that
  47658. ** means we have started to be concerned about content and the disk
  47659. ** read should occur at that point.
  47660. */
  47661. static int btreeGetPage(
  47662. BtShared *pBt, /* The btree */
  47663. Pgno pgno, /* Number of the page to fetch */
  47664. MemPage **ppPage, /* Return the page in this parameter */
  47665. int noContent, /* Do not load page content if true */
  47666. int bReadonly /* True if a read-only (mmap) page is ok */
  47667. ){
  47668. int rc;
  47669. DbPage *pDbPage;
  47670. int flags = (noContent ? PAGER_ACQUIRE_NOCONTENT : 0)
  47671. | (bReadonly ? PAGER_ACQUIRE_READONLY : 0);
  47672. assert( noContent==0 || bReadonly==0 );
  47673. assert( sqlite3_mutex_held(pBt->mutex) );
  47674. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  47675. if( rc ) return rc;
  47676. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  47677. return SQLITE_OK;
  47678. }
  47679. /*
  47680. ** Retrieve a page from the pager cache. If the requested page is not
  47681. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  47682. ** MemPage.aData elements if needed.
  47683. */
  47684. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  47685. DbPage *pDbPage;
  47686. assert( sqlite3_mutex_held(pBt->mutex) );
  47687. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  47688. if( pDbPage ){
  47689. return btreePageFromDbPage(pDbPage, pgno, pBt);
  47690. }
  47691. return 0;
  47692. }
  47693. /*
  47694. ** Return the size of the database file in pages. If there is any kind of
  47695. ** error, return ((unsigned int)-1).
  47696. */
  47697. static Pgno btreePagecount(BtShared *pBt){
  47698. return pBt->nPage;
  47699. }
  47700. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  47701. assert( sqlite3BtreeHoldsMutex(p) );
  47702. assert( ((p->pBt->nPage)&0x8000000)==0 );
  47703. return (int)btreePagecount(p->pBt);
  47704. }
  47705. /*
  47706. ** Get a page from the pager and initialize it. This routine is just a
  47707. ** convenience wrapper around separate calls to btreeGetPage() and
  47708. ** btreeInitPage().
  47709. **
  47710. ** If an error occurs, then the value *ppPage is set to is undefined. It
  47711. ** may remain unchanged, or it may be set to an invalid value.
  47712. */
  47713. static int getAndInitPage(
  47714. BtShared *pBt, /* The database file */
  47715. Pgno pgno, /* Number of the page to get */
  47716. MemPage **ppPage, /* Write the page pointer here */
  47717. int bReadonly /* True if a read-only (mmap) page is ok */
  47718. ){
  47719. int rc;
  47720. assert( sqlite3_mutex_held(pBt->mutex) );
  47721. if( pgno>btreePagecount(pBt) ){
  47722. rc = SQLITE_CORRUPT_BKPT;
  47723. }else{
  47724. rc = btreeGetPage(pBt, pgno, ppPage, 0, bReadonly);
  47725. if( rc==SQLITE_OK ){
  47726. rc = btreeInitPage(*ppPage);
  47727. if( rc!=SQLITE_OK ){
  47728. releasePage(*ppPage);
  47729. }
  47730. }
  47731. }
  47732. testcase( pgno==0 );
  47733. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  47734. return rc;
  47735. }
  47736. /*
  47737. ** Release a MemPage. This should be called once for each prior
  47738. ** call to btreeGetPage.
  47739. */
  47740. static void releasePage(MemPage *pPage){
  47741. if( pPage ){
  47742. assert( pPage->aData );
  47743. assert( pPage->pBt );
  47744. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  47745. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  47746. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47747. sqlite3PagerUnref(pPage->pDbPage);
  47748. }
  47749. }
  47750. /*
  47751. ** During a rollback, when the pager reloads information into the cache
  47752. ** so that the cache is restored to its original state at the start of
  47753. ** the transaction, for each page restored this routine is called.
  47754. **
  47755. ** This routine needs to reset the extra data section at the end of the
  47756. ** page to agree with the restored data.
  47757. */
  47758. static void pageReinit(DbPage *pData){
  47759. MemPage *pPage;
  47760. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  47761. assert( sqlite3PagerPageRefcount(pData)>0 );
  47762. if( pPage->isInit ){
  47763. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47764. pPage->isInit = 0;
  47765. if( sqlite3PagerPageRefcount(pData)>1 ){
  47766. /* pPage might not be a btree page; it might be an overflow page
  47767. ** or ptrmap page or a free page. In those cases, the following
  47768. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  47769. ** But no harm is done by this. And it is very important that
  47770. ** btreeInitPage() be called on every btree page so we make
  47771. ** the call for every page that comes in for re-initing. */
  47772. btreeInitPage(pPage);
  47773. }
  47774. }
  47775. }
  47776. /*
  47777. ** Invoke the busy handler for a btree.
  47778. */
  47779. static int btreeInvokeBusyHandler(void *pArg){
  47780. BtShared *pBt = (BtShared*)pArg;
  47781. assert( pBt->db );
  47782. assert( sqlite3_mutex_held(pBt->db->mutex) );
  47783. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  47784. }
  47785. /*
  47786. ** Open a database file.
  47787. **
  47788. ** zFilename is the name of the database file. If zFilename is NULL
  47789. ** then an ephemeral database is created. The ephemeral database might
  47790. ** be exclusively in memory, or it might use a disk-based memory cache.
  47791. ** Either way, the ephemeral database will be automatically deleted
  47792. ** when sqlite3BtreeClose() is called.
  47793. **
  47794. ** If zFilename is ":memory:" then an in-memory database is created
  47795. ** that is automatically destroyed when it is closed.
  47796. **
  47797. ** The "flags" parameter is a bitmask that might contain bits like
  47798. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  47799. **
  47800. ** If the database is already opened in the same database connection
  47801. ** and we are in shared cache mode, then the open will fail with an
  47802. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  47803. ** objects in the same database connection since doing so will lead
  47804. ** to problems with locking.
  47805. */
  47806. SQLITE_PRIVATE int sqlite3BtreeOpen(
  47807. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  47808. const char *zFilename, /* Name of the file containing the BTree database */
  47809. sqlite3 *db, /* Associated database handle */
  47810. Btree **ppBtree, /* Pointer to new Btree object written here */
  47811. int flags, /* Options */
  47812. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  47813. ){
  47814. BtShared *pBt = 0; /* Shared part of btree structure */
  47815. Btree *p; /* Handle to return */
  47816. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  47817. int rc = SQLITE_OK; /* Result code from this function */
  47818. u8 nReserve; /* Byte of unused space on each page */
  47819. unsigned char zDbHeader[100]; /* Database header content */
  47820. /* True if opening an ephemeral, temporary database */
  47821. const int isTempDb = zFilename==0 || zFilename[0]==0;
  47822. /* Set the variable isMemdb to true for an in-memory database, or
  47823. ** false for a file-based database.
  47824. */
  47825. #ifdef SQLITE_OMIT_MEMORYDB
  47826. const int isMemdb = 0;
  47827. #else
  47828. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  47829. || (isTempDb && sqlite3TempInMemory(db))
  47830. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  47831. #endif
  47832. assert( db!=0 );
  47833. assert( pVfs!=0 );
  47834. assert( sqlite3_mutex_held(db->mutex) );
  47835. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  47836. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  47837. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  47838. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  47839. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  47840. if( isMemdb ){
  47841. flags |= BTREE_MEMORY;
  47842. }
  47843. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  47844. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  47845. }
  47846. p = sqlite3MallocZero(sizeof(Btree));
  47847. if( !p ){
  47848. return SQLITE_NOMEM;
  47849. }
  47850. p->inTrans = TRANS_NONE;
  47851. p->db = db;
  47852. #ifndef SQLITE_OMIT_SHARED_CACHE
  47853. p->lock.pBtree = p;
  47854. p->lock.iTable = 1;
  47855. #endif
  47856. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  47857. /*
  47858. ** If this Btree is a candidate for shared cache, try to find an
  47859. ** existing BtShared object that we can share with
  47860. */
  47861. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  47862. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  47863. int nFullPathname = pVfs->mxPathname+1;
  47864. char *zFullPathname = sqlite3Malloc(nFullPathname);
  47865. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  47866. p->sharable = 1;
  47867. if( !zFullPathname ){
  47868. sqlite3_free(p);
  47869. return SQLITE_NOMEM;
  47870. }
  47871. if( isMemdb ){
  47872. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  47873. }else{
  47874. rc = sqlite3OsFullPathname(pVfs, zFilename,
  47875. nFullPathname, zFullPathname);
  47876. if( rc ){
  47877. sqlite3_free(zFullPathname);
  47878. sqlite3_free(p);
  47879. return rc;
  47880. }
  47881. }
  47882. #if SQLITE_THREADSAFE
  47883. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  47884. sqlite3_mutex_enter(mutexOpen);
  47885. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  47886. sqlite3_mutex_enter(mutexShared);
  47887. #endif
  47888. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  47889. assert( pBt->nRef>0 );
  47890. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  47891. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  47892. int iDb;
  47893. for(iDb=db->nDb-1; iDb>=0; iDb--){
  47894. Btree *pExisting = db->aDb[iDb].pBt;
  47895. if( pExisting && pExisting->pBt==pBt ){
  47896. sqlite3_mutex_leave(mutexShared);
  47897. sqlite3_mutex_leave(mutexOpen);
  47898. sqlite3_free(zFullPathname);
  47899. sqlite3_free(p);
  47900. return SQLITE_CONSTRAINT;
  47901. }
  47902. }
  47903. p->pBt = pBt;
  47904. pBt->nRef++;
  47905. break;
  47906. }
  47907. }
  47908. sqlite3_mutex_leave(mutexShared);
  47909. sqlite3_free(zFullPathname);
  47910. }
  47911. #ifdef SQLITE_DEBUG
  47912. else{
  47913. /* In debug mode, we mark all persistent databases as sharable
  47914. ** even when they are not. This exercises the locking code and
  47915. ** gives more opportunity for asserts(sqlite3_mutex_held())
  47916. ** statements to find locking problems.
  47917. */
  47918. p->sharable = 1;
  47919. }
  47920. #endif
  47921. }
  47922. #endif
  47923. if( pBt==0 ){
  47924. /*
  47925. ** The following asserts make sure that structures used by the btree are
  47926. ** the right size. This is to guard against size changes that result
  47927. ** when compiling on a different architecture.
  47928. */
  47929. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  47930. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  47931. assert( sizeof(u32)==4 );
  47932. assert( sizeof(u16)==2 );
  47933. assert( sizeof(Pgno)==4 );
  47934. pBt = sqlite3MallocZero( sizeof(*pBt) );
  47935. if( pBt==0 ){
  47936. rc = SQLITE_NOMEM;
  47937. goto btree_open_out;
  47938. }
  47939. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  47940. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  47941. if( rc==SQLITE_OK ){
  47942. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  47943. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  47944. }
  47945. if( rc!=SQLITE_OK ){
  47946. goto btree_open_out;
  47947. }
  47948. pBt->openFlags = (u8)flags;
  47949. pBt->db = db;
  47950. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  47951. p->pBt = pBt;
  47952. pBt->pCursor = 0;
  47953. pBt->pPage1 = 0;
  47954. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  47955. #ifdef SQLITE_SECURE_DELETE
  47956. pBt->btsFlags |= BTS_SECURE_DELETE;
  47957. #endif
  47958. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  47959. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  47960. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  47961. pBt->pageSize = 0;
  47962. #ifndef SQLITE_OMIT_AUTOVACUUM
  47963. /* If the magic name ":memory:" will create an in-memory database, then
  47964. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  47965. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  47966. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  47967. ** regular file-name. In this case the auto-vacuum applies as per normal.
  47968. */
  47969. if( zFilename && !isMemdb ){
  47970. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  47971. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  47972. }
  47973. #endif
  47974. nReserve = 0;
  47975. }else{
  47976. nReserve = zDbHeader[20];
  47977. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  47978. #ifndef SQLITE_OMIT_AUTOVACUUM
  47979. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  47980. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  47981. #endif
  47982. }
  47983. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  47984. if( rc ) goto btree_open_out;
  47985. pBt->usableSize = pBt->pageSize - nReserve;
  47986. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  47987. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  47988. /* Add the new BtShared object to the linked list sharable BtShareds.
  47989. */
  47990. if( p->sharable ){
  47991. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  47992. pBt->nRef = 1;
  47993. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  47994. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  47995. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  47996. if( pBt->mutex==0 ){
  47997. rc = SQLITE_NOMEM;
  47998. db->mallocFailed = 0;
  47999. goto btree_open_out;
  48000. }
  48001. }
  48002. sqlite3_mutex_enter(mutexShared);
  48003. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  48004. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  48005. sqlite3_mutex_leave(mutexShared);
  48006. }
  48007. #endif
  48008. }
  48009. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  48010. /* If the new Btree uses a sharable pBtShared, then link the new
  48011. ** Btree into the list of all sharable Btrees for the same connection.
  48012. ** The list is kept in ascending order by pBt address.
  48013. */
  48014. if( p->sharable ){
  48015. int i;
  48016. Btree *pSib;
  48017. for(i=0; i<db->nDb; i++){
  48018. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  48019. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  48020. if( p->pBt<pSib->pBt ){
  48021. p->pNext = pSib;
  48022. p->pPrev = 0;
  48023. pSib->pPrev = p;
  48024. }else{
  48025. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  48026. pSib = pSib->pNext;
  48027. }
  48028. p->pNext = pSib->pNext;
  48029. p->pPrev = pSib;
  48030. if( p->pNext ){
  48031. p->pNext->pPrev = p;
  48032. }
  48033. pSib->pNext = p;
  48034. }
  48035. break;
  48036. }
  48037. }
  48038. }
  48039. #endif
  48040. *ppBtree = p;
  48041. btree_open_out:
  48042. if( rc!=SQLITE_OK ){
  48043. if( pBt && pBt->pPager ){
  48044. sqlite3PagerClose(pBt->pPager);
  48045. }
  48046. sqlite3_free(pBt);
  48047. sqlite3_free(p);
  48048. *ppBtree = 0;
  48049. }else{
  48050. /* If the B-Tree was successfully opened, set the pager-cache size to the
  48051. ** default value. Except, when opening on an existing shared pager-cache,
  48052. ** do not change the pager-cache size.
  48053. */
  48054. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  48055. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  48056. }
  48057. }
  48058. if( mutexOpen ){
  48059. assert( sqlite3_mutex_held(mutexOpen) );
  48060. sqlite3_mutex_leave(mutexOpen);
  48061. }
  48062. return rc;
  48063. }
  48064. /*
  48065. ** Decrement the BtShared.nRef counter. When it reaches zero,
  48066. ** remove the BtShared structure from the sharing list. Return
  48067. ** true if the BtShared.nRef counter reaches zero and return
  48068. ** false if it is still positive.
  48069. */
  48070. static int removeFromSharingList(BtShared *pBt){
  48071. #ifndef SQLITE_OMIT_SHARED_CACHE
  48072. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  48073. BtShared *pList;
  48074. int removed = 0;
  48075. assert( sqlite3_mutex_notheld(pBt->mutex) );
  48076. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  48077. sqlite3_mutex_enter(pMaster);
  48078. pBt->nRef--;
  48079. if( pBt->nRef<=0 ){
  48080. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  48081. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  48082. }else{
  48083. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  48084. while( ALWAYS(pList) && pList->pNext!=pBt ){
  48085. pList=pList->pNext;
  48086. }
  48087. if( ALWAYS(pList) ){
  48088. pList->pNext = pBt->pNext;
  48089. }
  48090. }
  48091. if( SQLITE_THREADSAFE ){
  48092. sqlite3_mutex_free(pBt->mutex);
  48093. }
  48094. removed = 1;
  48095. }
  48096. sqlite3_mutex_leave(pMaster);
  48097. return removed;
  48098. #else
  48099. return 1;
  48100. #endif
  48101. }
  48102. /*
  48103. ** Make sure pBt->pTmpSpace points to an allocation of
  48104. ** MX_CELL_SIZE(pBt) bytes.
  48105. */
  48106. static void allocateTempSpace(BtShared *pBt){
  48107. if( !pBt->pTmpSpace ){
  48108. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  48109. }
  48110. }
  48111. /*
  48112. ** Free the pBt->pTmpSpace allocation
  48113. */
  48114. static void freeTempSpace(BtShared *pBt){
  48115. sqlite3PageFree( pBt->pTmpSpace);
  48116. pBt->pTmpSpace = 0;
  48117. }
  48118. /*
  48119. ** Close an open database and invalidate all cursors.
  48120. */
  48121. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  48122. BtShared *pBt = p->pBt;
  48123. BtCursor *pCur;
  48124. /* Close all cursors opened via this handle. */
  48125. assert( sqlite3_mutex_held(p->db->mutex) );
  48126. sqlite3BtreeEnter(p);
  48127. pCur = pBt->pCursor;
  48128. while( pCur ){
  48129. BtCursor *pTmp = pCur;
  48130. pCur = pCur->pNext;
  48131. if( pTmp->pBtree==p ){
  48132. sqlite3BtreeCloseCursor(pTmp);
  48133. }
  48134. }
  48135. /* Rollback any active transaction and free the handle structure.
  48136. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  48137. ** this handle.
  48138. */
  48139. sqlite3BtreeRollback(p, SQLITE_OK);
  48140. sqlite3BtreeLeave(p);
  48141. /* If there are still other outstanding references to the shared-btree
  48142. ** structure, return now. The remainder of this procedure cleans
  48143. ** up the shared-btree.
  48144. */
  48145. assert( p->wantToLock==0 && p->locked==0 );
  48146. if( !p->sharable || removeFromSharingList(pBt) ){
  48147. /* The pBt is no longer on the sharing list, so we can access
  48148. ** it without having to hold the mutex.
  48149. **
  48150. ** Clean out and delete the BtShared object.
  48151. */
  48152. assert( !pBt->pCursor );
  48153. sqlite3PagerClose(pBt->pPager);
  48154. if( pBt->xFreeSchema && pBt->pSchema ){
  48155. pBt->xFreeSchema(pBt->pSchema);
  48156. }
  48157. sqlite3DbFree(0, pBt->pSchema);
  48158. freeTempSpace(pBt);
  48159. sqlite3_free(pBt);
  48160. }
  48161. #ifndef SQLITE_OMIT_SHARED_CACHE
  48162. assert( p->wantToLock==0 );
  48163. assert( p->locked==0 );
  48164. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  48165. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  48166. #endif
  48167. sqlite3_free(p);
  48168. return SQLITE_OK;
  48169. }
  48170. /*
  48171. ** Change the limit on the number of pages allowed in the cache.
  48172. **
  48173. ** The maximum number of cache pages is set to the absolute
  48174. ** value of mxPage. If mxPage is negative, the pager will
  48175. ** operate asynchronously - it will not stop to do fsync()s
  48176. ** to insure data is written to the disk surface before
  48177. ** continuing. Transactions still work if synchronous is off,
  48178. ** and the database cannot be corrupted if this program
  48179. ** crashes. But if the operating system crashes or there is
  48180. ** an abrupt power failure when synchronous is off, the database
  48181. ** could be left in an inconsistent and unrecoverable state.
  48182. ** Synchronous is on by default so database corruption is not
  48183. ** normally a worry.
  48184. */
  48185. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  48186. BtShared *pBt = p->pBt;
  48187. assert( sqlite3_mutex_held(p->db->mutex) );
  48188. sqlite3BtreeEnter(p);
  48189. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  48190. sqlite3BtreeLeave(p);
  48191. return SQLITE_OK;
  48192. }
  48193. /*
  48194. ** Change the limit on the amount of the database file that may be
  48195. ** memory mapped.
  48196. */
  48197. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  48198. BtShared *pBt = p->pBt;
  48199. assert( sqlite3_mutex_held(p->db->mutex) );
  48200. sqlite3BtreeEnter(p);
  48201. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  48202. sqlite3BtreeLeave(p);
  48203. return SQLITE_OK;
  48204. }
  48205. /*
  48206. ** Change the way data is synced to disk in order to increase or decrease
  48207. ** how well the database resists damage due to OS crashes and power
  48208. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  48209. ** there is a high probability of damage) Level 2 is the default. There
  48210. ** is a very low but non-zero probability of damage. Level 3 reduces the
  48211. ** probability of damage to near zero but with a write performance reduction.
  48212. */
  48213. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  48214. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
  48215. Btree *p, /* The btree to set the safety level on */
  48216. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  48217. int fullSync, /* PRAGMA fullfsync. */
  48218. int ckptFullSync /* PRAGMA checkpoint_fullfync */
  48219. ){
  48220. BtShared *pBt = p->pBt;
  48221. assert( sqlite3_mutex_held(p->db->mutex) );
  48222. assert( level>=1 && level<=3 );
  48223. sqlite3BtreeEnter(p);
  48224. sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
  48225. sqlite3BtreeLeave(p);
  48226. return SQLITE_OK;
  48227. }
  48228. #endif
  48229. /*
  48230. ** Return TRUE if the given btree is set to safety level 1. In other
  48231. ** words, return TRUE if no sync() occurs on the disk files.
  48232. */
  48233. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  48234. BtShared *pBt = p->pBt;
  48235. int rc;
  48236. assert( sqlite3_mutex_held(p->db->mutex) );
  48237. sqlite3BtreeEnter(p);
  48238. assert( pBt && pBt->pPager );
  48239. rc = sqlite3PagerNosync(pBt->pPager);
  48240. sqlite3BtreeLeave(p);
  48241. return rc;
  48242. }
  48243. /*
  48244. ** Change the default pages size and the number of reserved bytes per page.
  48245. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  48246. ** without changing anything.
  48247. **
  48248. ** The page size must be a power of 2 between 512 and 65536. If the page
  48249. ** size supplied does not meet this constraint then the page size is not
  48250. ** changed.
  48251. **
  48252. ** Page sizes are constrained to be a power of two so that the region
  48253. ** of the database file used for locking (beginning at PENDING_BYTE,
  48254. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  48255. ** at the beginning of a page.
  48256. **
  48257. ** If parameter nReserve is less than zero, then the number of reserved
  48258. ** bytes per page is left unchanged.
  48259. **
  48260. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  48261. ** and autovacuum mode can no longer be changed.
  48262. */
  48263. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  48264. int rc = SQLITE_OK;
  48265. BtShared *pBt = p->pBt;
  48266. assert( nReserve>=-1 && nReserve<=255 );
  48267. sqlite3BtreeEnter(p);
  48268. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  48269. sqlite3BtreeLeave(p);
  48270. return SQLITE_READONLY;
  48271. }
  48272. if( nReserve<0 ){
  48273. nReserve = pBt->pageSize - pBt->usableSize;
  48274. }
  48275. assert( nReserve>=0 && nReserve<=255 );
  48276. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  48277. ((pageSize-1)&pageSize)==0 ){
  48278. assert( (pageSize & 7)==0 );
  48279. assert( !pBt->pPage1 && !pBt->pCursor );
  48280. pBt->pageSize = (u32)pageSize;
  48281. freeTempSpace(pBt);
  48282. }
  48283. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  48284. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  48285. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  48286. sqlite3BtreeLeave(p);
  48287. return rc;
  48288. }
  48289. /*
  48290. ** Return the currently defined page size
  48291. */
  48292. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  48293. return p->pBt->pageSize;
  48294. }
  48295. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  48296. /*
  48297. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  48298. ** may only be called if it is guaranteed that the b-tree mutex is already
  48299. ** held.
  48300. **
  48301. ** This is useful in one special case in the backup API code where it is
  48302. ** known that the shared b-tree mutex is held, but the mutex on the
  48303. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  48304. ** were to be called, it might collide with some other operation on the
  48305. ** database handle that owns *p, causing undefined behavior.
  48306. */
  48307. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  48308. assert( sqlite3_mutex_held(p->pBt->mutex) );
  48309. return p->pBt->pageSize - p->pBt->usableSize;
  48310. }
  48311. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  48312. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  48313. /*
  48314. ** Return the number of bytes of space at the end of every page that
  48315. ** are intentually left unused. This is the "reserved" space that is
  48316. ** sometimes used by extensions.
  48317. */
  48318. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  48319. int n;
  48320. sqlite3BtreeEnter(p);
  48321. n = p->pBt->pageSize - p->pBt->usableSize;
  48322. sqlite3BtreeLeave(p);
  48323. return n;
  48324. }
  48325. /*
  48326. ** Set the maximum page count for a database if mxPage is positive.
  48327. ** No changes are made if mxPage is 0 or negative.
  48328. ** Regardless of the value of mxPage, return the maximum page count.
  48329. */
  48330. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  48331. int n;
  48332. sqlite3BtreeEnter(p);
  48333. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  48334. sqlite3BtreeLeave(p);
  48335. return n;
  48336. }
  48337. /*
  48338. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  48339. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  48340. ** setting after the change.
  48341. */
  48342. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  48343. int b;
  48344. if( p==0 ) return 0;
  48345. sqlite3BtreeEnter(p);
  48346. if( newFlag>=0 ){
  48347. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  48348. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  48349. }
  48350. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  48351. sqlite3BtreeLeave(p);
  48352. return b;
  48353. }
  48354. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  48355. /*
  48356. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  48357. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  48358. ** is disabled. The default value for the auto-vacuum property is
  48359. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  48360. */
  48361. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  48362. #ifdef SQLITE_OMIT_AUTOVACUUM
  48363. return SQLITE_READONLY;
  48364. #else
  48365. BtShared *pBt = p->pBt;
  48366. int rc = SQLITE_OK;
  48367. u8 av = (u8)autoVacuum;
  48368. sqlite3BtreeEnter(p);
  48369. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  48370. rc = SQLITE_READONLY;
  48371. }else{
  48372. pBt->autoVacuum = av ?1:0;
  48373. pBt->incrVacuum = av==2 ?1:0;
  48374. }
  48375. sqlite3BtreeLeave(p);
  48376. return rc;
  48377. #endif
  48378. }
  48379. /*
  48380. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  48381. ** enabled 1 is returned. Otherwise 0.
  48382. */
  48383. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  48384. #ifdef SQLITE_OMIT_AUTOVACUUM
  48385. return BTREE_AUTOVACUUM_NONE;
  48386. #else
  48387. int rc;
  48388. sqlite3BtreeEnter(p);
  48389. rc = (
  48390. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  48391. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  48392. BTREE_AUTOVACUUM_INCR
  48393. );
  48394. sqlite3BtreeLeave(p);
  48395. return rc;
  48396. #endif
  48397. }
  48398. /*
  48399. ** Get a reference to pPage1 of the database file. This will
  48400. ** also acquire a readlock on that file.
  48401. **
  48402. ** SQLITE_OK is returned on success. If the file is not a
  48403. ** well-formed database file, then SQLITE_CORRUPT is returned.
  48404. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  48405. ** is returned if we run out of memory.
  48406. */
  48407. static int lockBtree(BtShared *pBt){
  48408. int rc; /* Result code from subfunctions */
  48409. MemPage *pPage1; /* Page 1 of the database file */
  48410. int nPage; /* Number of pages in the database */
  48411. int nPageFile = 0; /* Number of pages in the database file */
  48412. int nPageHeader; /* Number of pages in the database according to hdr */
  48413. assert( sqlite3_mutex_held(pBt->mutex) );
  48414. assert( pBt->pPage1==0 );
  48415. rc = sqlite3PagerSharedLock(pBt->pPager);
  48416. if( rc!=SQLITE_OK ) return rc;
  48417. rc = btreeGetPage(pBt, 1, &pPage1, 0, 0);
  48418. if( rc!=SQLITE_OK ) return rc;
  48419. /* Do some checking to help insure the file we opened really is
  48420. ** a valid database file.
  48421. */
  48422. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  48423. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  48424. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  48425. nPage = nPageFile;
  48426. }
  48427. if( nPage>0 ){
  48428. u32 pageSize;
  48429. u32 usableSize;
  48430. u8 *page1 = pPage1->aData;
  48431. rc = SQLITE_NOTADB;
  48432. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  48433. goto page1_init_failed;
  48434. }
  48435. #ifdef SQLITE_OMIT_WAL
  48436. if( page1[18]>1 ){
  48437. pBt->btsFlags |= BTS_READ_ONLY;
  48438. }
  48439. if( page1[19]>1 ){
  48440. goto page1_init_failed;
  48441. }
  48442. #else
  48443. if( page1[18]>2 ){
  48444. pBt->btsFlags |= BTS_READ_ONLY;
  48445. }
  48446. if( page1[19]>2 ){
  48447. goto page1_init_failed;
  48448. }
  48449. /* If the write version is set to 2, this database should be accessed
  48450. ** in WAL mode. If the log is not already open, open it now. Then
  48451. ** return SQLITE_OK and return without populating BtShared.pPage1.
  48452. ** The caller detects this and calls this function again. This is
  48453. ** required as the version of page 1 currently in the page1 buffer
  48454. ** may not be the latest version - there may be a newer one in the log
  48455. ** file.
  48456. */
  48457. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  48458. int isOpen = 0;
  48459. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  48460. if( rc!=SQLITE_OK ){
  48461. goto page1_init_failed;
  48462. }else if( isOpen==0 ){
  48463. releasePage(pPage1);
  48464. return SQLITE_OK;
  48465. }
  48466. rc = SQLITE_NOTADB;
  48467. }
  48468. #endif
  48469. /* The maximum embedded fraction must be exactly 25%. And the minimum
  48470. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  48471. ** The original design allowed these amounts to vary, but as of
  48472. ** version 3.6.0, we require them to be fixed.
  48473. */
  48474. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  48475. goto page1_init_failed;
  48476. }
  48477. pageSize = (page1[16]<<8) | (page1[17]<<16);
  48478. if( ((pageSize-1)&pageSize)!=0
  48479. || pageSize>SQLITE_MAX_PAGE_SIZE
  48480. || pageSize<=256
  48481. ){
  48482. goto page1_init_failed;
  48483. }
  48484. assert( (pageSize & 7)==0 );
  48485. usableSize = pageSize - page1[20];
  48486. if( (u32)pageSize!=pBt->pageSize ){
  48487. /* After reading the first page of the database assuming a page size
  48488. ** of BtShared.pageSize, we have discovered that the page-size is
  48489. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  48490. ** zero and return SQLITE_OK. The caller will call this function
  48491. ** again with the correct page-size.
  48492. */
  48493. releasePage(pPage1);
  48494. pBt->usableSize = usableSize;
  48495. pBt->pageSize = pageSize;
  48496. freeTempSpace(pBt);
  48497. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  48498. pageSize-usableSize);
  48499. return rc;
  48500. }
  48501. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  48502. rc = SQLITE_CORRUPT_BKPT;
  48503. goto page1_init_failed;
  48504. }
  48505. if( usableSize<480 ){
  48506. goto page1_init_failed;
  48507. }
  48508. pBt->pageSize = pageSize;
  48509. pBt->usableSize = usableSize;
  48510. #ifndef SQLITE_OMIT_AUTOVACUUM
  48511. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  48512. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  48513. #endif
  48514. }
  48515. /* maxLocal is the maximum amount of payload to store locally for
  48516. ** a cell. Make sure it is small enough so that at least minFanout
  48517. ** cells can will fit on one page. We assume a 10-byte page header.
  48518. ** Besides the payload, the cell must store:
  48519. ** 2-byte pointer to the cell
  48520. ** 4-byte child pointer
  48521. ** 9-byte nKey value
  48522. ** 4-byte nData value
  48523. ** 4-byte overflow page pointer
  48524. ** So a cell consists of a 2-byte pointer, a header which is as much as
  48525. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  48526. ** page pointer.
  48527. */
  48528. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  48529. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  48530. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  48531. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  48532. if( pBt->maxLocal>127 ){
  48533. pBt->max1bytePayload = 127;
  48534. }else{
  48535. pBt->max1bytePayload = (u8)pBt->maxLocal;
  48536. }
  48537. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  48538. pBt->pPage1 = pPage1;
  48539. pBt->nPage = nPage;
  48540. return SQLITE_OK;
  48541. page1_init_failed:
  48542. releasePage(pPage1);
  48543. pBt->pPage1 = 0;
  48544. return rc;
  48545. }
  48546. #ifndef NDEBUG
  48547. /*
  48548. ** Return the number of cursors open on pBt. This is for use
  48549. ** in assert() expressions, so it is only compiled if NDEBUG is not
  48550. ** defined.
  48551. **
  48552. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  48553. ** false then all cursors are counted.
  48554. **
  48555. ** For the purposes of this routine, a cursor is any cursor that
  48556. ** is capable of reading or writing to the databse. Cursors that
  48557. ** have been tripped into the CURSOR_FAULT state are not counted.
  48558. */
  48559. static int countValidCursors(BtShared *pBt, int wrOnly){
  48560. BtCursor *pCur;
  48561. int r = 0;
  48562. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  48563. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  48564. }
  48565. return r;
  48566. }
  48567. #endif
  48568. /*
  48569. ** If there are no outstanding cursors and we are not in the middle
  48570. ** of a transaction but there is a read lock on the database, then
  48571. ** this routine unrefs the first page of the database file which
  48572. ** has the effect of releasing the read lock.
  48573. **
  48574. ** If there is a transaction in progress, this routine is a no-op.
  48575. */
  48576. static void unlockBtreeIfUnused(BtShared *pBt){
  48577. assert( sqlite3_mutex_held(pBt->mutex) );
  48578. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  48579. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  48580. assert( pBt->pPage1->aData );
  48581. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  48582. assert( pBt->pPage1->aData );
  48583. releasePage(pBt->pPage1);
  48584. pBt->pPage1 = 0;
  48585. }
  48586. }
  48587. /*
  48588. ** If pBt points to an empty file then convert that empty file
  48589. ** into a new empty database by initializing the first page of
  48590. ** the database.
  48591. */
  48592. static int newDatabase(BtShared *pBt){
  48593. MemPage *pP1;
  48594. unsigned char *data;
  48595. int rc;
  48596. assert( sqlite3_mutex_held(pBt->mutex) );
  48597. if( pBt->nPage>0 ){
  48598. return SQLITE_OK;
  48599. }
  48600. pP1 = pBt->pPage1;
  48601. assert( pP1!=0 );
  48602. data = pP1->aData;
  48603. rc = sqlite3PagerWrite(pP1->pDbPage);
  48604. if( rc ) return rc;
  48605. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  48606. assert( sizeof(zMagicHeader)==16 );
  48607. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  48608. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  48609. data[18] = 1;
  48610. data[19] = 1;
  48611. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  48612. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  48613. data[21] = 64;
  48614. data[22] = 32;
  48615. data[23] = 32;
  48616. memset(&data[24], 0, 100-24);
  48617. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  48618. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  48619. #ifndef SQLITE_OMIT_AUTOVACUUM
  48620. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  48621. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  48622. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  48623. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  48624. #endif
  48625. pBt->nPage = 1;
  48626. data[31] = 1;
  48627. return SQLITE_OK;
  48628. }
  48629. /*
  48630. ** Initialize the first page of the database file (creating a database
  48631. ** consisting of a single page and no schema objects). Return SQLITE_OK
  48632. ** if successful, or an SQLite error code otherwise.
  48633. */
  48634. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  48635. int rc;
  48636. sqlite3BtreeEnter(p);
  48637. p->pBt->nPage = 0;
  48638. rc = newDatabase(p->pBt);
  48639. sqlite3BtreeLeave(p);
  48640. return rc;
  48641. }
  48642. /*
  48643. ** Attempt to start a new transaction. A write-transaction
  48644. ** is started if the second argument is nonzero, otherwise a read-
  48645. ** transaction. If the second argument is 2 or more and exclusive
  48646. ** transaction is started, meaning that no other process is allowed
  48647. ** to access the database. A preexisting transaction may not be
  48648. ** upgraded to exclusive by calling this routine a second time - the
  48649. ** exclusivity flag only works for a new transaction.
  48650. **
  48651. ** A write-transaction must be started before attempting any
  48652. ** changes to the database. None of the following routines
  48653. ** will work unless a transaction is started first:
  48654. **
  48655. ** sqlite3BtreeCreateTable()
  48656. ** sqlite3BtreeCreateIndex()
  48657. ** sqlite3BtreeClearTable()
  48658. ** sqlite3BtreeDropTable()
  48659. ** sqlite3BtreeInsert()
  48660. ** sqlite3BtreeDelete()
  48661. ** sqlite3BtreeUpdateMeta()
  48662. **
  48663. ** If an initial attempt to acquire the lock fails because of lock contention
  48664. ** and the database was previously unlocked, then invoke the busy handler
  48665. ** if there is one. But if there was previously a read-lock, do not
  48666. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  48667. ** returned when there is already a read-lock in order to avoid a deadlock.
  48668. **
  48669. ** Suppose there are two processes A and B. A has a read lock and B has
  48670. ** a reserved lock. B tries to promote to exclusive but is blocked because
  48671. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  48672. ** One or the other of the two processes must give way or there can be
  48673. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  48674. ** when A already has a read lock, we encourage A to give up and let B
  48675. ** proceed.
  48676. */
  48677. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  48678. sqlite3 *pBlock = 0;
  48679. BtShared *pBt = p->pBt;
  48680. int rc = SQLITE_OK;
  48681. sqlite3BtreeEnter(p);
  48682. btreeIntegrity(p);
  48683. /* If the btree is already in a write-transaction, or it
  48684. ** is already in a read-transaction and a read-transaction
  48685. ** is requested, this is a no-op.
  48686. */
  48687. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  48688. goto trans_begun;
  48689. }
  48690. assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
  48691. /* Write transactions are not possible on a read-only database */
  48692. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  48693. rc = SQLITE_READONLY;
  48694. goto trans_begun;
  48695. }
  48696. #ifndef SQLITE_OMIT_SHARED_CACHE
  48697. /* If another database handle has already opened a write transaction
  48698. ** on this shared-btree structure and a second write transaction is
  48699. ** requested, return SQLITE_LOCKED.
  48700. */
  48701. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  48702. || (pBt->btsFlags & BTS_PENDING)!=0
  48703. ){
  48704. pBlock = pBt->pWriter->db;
  48705. }else if( wrflag>1 ){
  48706. BtLock *pIter;
  48707. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  48708. if( pIter->pBtree!=p ){
  48709. pBlock = pIter->pBtree->db;
  48710. break;
  48711. }
  48712. }
  48713. }
  48714. if( pBlock ){
  48715. sqlite3ConnectionBlocked(p->db, pBlock);
  48716. rc = SQLITE_LOCKED_SHAREDCACHE;
  48717. goto trans_begun;
  48718. }
  48719. #endif
  48720. /* Any read-only or read-write transaction implies a read-lock on
  48721. ** page 1. So if some other shared-cache client already has a write-lock
  48722. ** on page 1, the transaction cannot be opened. */
  48723. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  48724. if( SQLITE_OK!=rc ) goto trans_begun;
  48725. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  48726. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  48727. do {
  48728. /* Call lockBtree() until either pBt->pPage1 is populated or
  48729. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  48730. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  48731. ** reading page 1 it discovers that the page-size of the database
  48732. ** file is not pBt->pageSize. In this case lockBtree() will update
  48733. ** pBt->pageSize to the page-size of the file on disk.
  48734. */
  48735. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  48736. if( rc==SQLITE_OK && wrflag ){
  48737. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  48738. rc = SQLITE_READONLY;
  48739. }else{
  48740. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  48741. if( rc==SQLITE_OK ){
  48742. rc = newDatabase(pBt);
  48743. }
  48744. }
  48745. }
  48746. if( rc!=SQLITE_OK ){
  48747. unlockBtreeIfUnused(pBt);
  48748. }
  48749. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  48750. btreeInvokeBusyHandler(pBt) );
  48751. if( rc==SQLITE_OK ){
  48752. if( p->inTrans==TRANS_NONE ){
  48753. pBt->nTransaction++;
  48754. #ifndef SQLITE_OMIT_SHARED_CACHE
  48755. if( p->sharable ){
  48756. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  48757. p->lock.eLock = READ_LOCK;
  48758. p->lock.pNext = pBt->pLock;
  48759. pBt->pLock = &p->lock;
  48760. }
  48761. #endif
  48762. }
  48763. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  48764. if( p->inTrans>pBt->inTransaction ){
  48765. pBt->inTransaction = p->inTrans;
  48766. }
  48767. if( wrflag ){
  48768. MemPage *pPage1 = pBt->pPage1;
  48769. #ifndef SQLITE_OMIT_SHARED_CACHE
  48770. assert( !pBt->pWriter );
  48771. pBt->pWriter = p;
  48772. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  48773. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  48774. #endif
  48775. /* If the db-size header field is incorrect (as it may be if an old
  48776. ** client has been writing the database file), update it now. Doing
  48777. ** this sooner rather than later means the database size can safely
  48778. ** re-read the database size from page 1 if a savepoint or transaction
  48779. ** rollback occurs within the transaction.
  48780. */
  48781. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  48782. rc = sqlite3PagerWrite(pPage1->pDbPage);
  48783. if( rc==SQLITE_OK ){
  48784. put4byte(&pPage1->aData[28], pBt->nPage);
  48785. }
  48786. }
  48787. }
  48788. }
  48789. trans_begun:
  48790. if( rc==SQLITE_OK && wrflag ){
  48791. /* This call makes sure that the pager has the correct number of
  48792. ** open savepoints. If the second parameter is greater than 0 and
  48793. ** the sub-journal is not already open, then it will be opened here.
  48794. */
  48795. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  48796. }
  48797. btreeIntegrity(p);
  48798. sqlite3BtreeLeave(p);
  48799. return rc;
  48800. }
  48801. #ifndef SQLITE_OMIT_AUTOVACUUM
  48802. /*
  48803. ** Set the pointer-map entries for all children of page pPage. Also, if
  48804. ** pPage contains cells that point to overflow pages, set the pointer
  48805. ** map entries for the overflow pages as well.
  48806. */
  48807. static int setChildPtrmaps(MemPage *pPage){
  48808. int i; /* Counter variable */
  48809. int nCell; /* Number of cells in page pPage */
  48810. int rc; /* Return code */
  48811. BtShared *pBt = pPage->pBt;
  48812. u8 isInitOrig = pPage->isInit;
  48813. Pgno pgno = pPage->pgno;
  48814. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48815. rc = btreeInitPage(pPage);
  48816. if( rc!=SQLITE_OK ){
  48817. goto set_child_ptrmaps_out;
  48818. }
  48819. nCell = pPage->nCell;
  48820. for(i=0; i<nCell; i++){
  48821. u8 *pCell = findCell(pPage, i);
  48822. ptrmapPutOvflPtr(pPage, pCell, &rc);
  48823. if( !pPage->leaf ){
  48824. Pgno childPgno = get4byte(pCell);
  48825. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  48826. }
  48827. }
  48828. if( !pPage->leaf ){
  48829. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  48830. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  48831. }
  48832. set_child_ptrmaps_out:
  48833. pPage->isInit = isInitOrig;
  48834. return rc;
  48835. }
  48836. /*
  48837. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  48838. ** that it points to iTo. Parameter eType describes the type of pointer to
  48839. ** be modified, as follows:
  48840. **
  48841. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  48842. ** page of pPage.
  48843. **
  48844. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  48845. ** page pointed to by one of the cells on pPage.
  48846. **
  48847. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  48848. ** overflow page in the list.
  48849. */
  48850. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  48851. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48852. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  48853. if( eType==PTRMAP_OVERFLOW2 ){
  48854. /* The pointer is always the first 4 bytes of the page in this case. */
  48855. if( get4byte(pPage->aData)!=iFrom ){
  48856. return SQLITE_CORRUPT_BKPT;
  48857. }
  48858. put4byte(pPage->aData, iTo);
  48859. }else{
  48860. u8 isInitOrig = pPage->isInit;
  48861. int i;
  48862. int nCell;
  48863. btreeInitPage(pPage);
  48864. nCell = pPage->nCell;
  48865. for(i=0; i<nCell; i++){
  48866. u8 *pCell = findCell(pPage, i);
  48867. if( eType==PTRMAP_OVERFLOW1 ){
  48868. CellInfo info;
  48869. btreeParseCellPtr(pPage, pCell, &info);
  48870. if( info.iOverflow
  48871. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  48872. && iFrom==get4byte(&pCell[info.iOverflow])
  48873. ){
  48874. put4byte(&pCell[info.iOverflow], iTo);
  48875. break;
  48876. }
  48877. }else{
  48878. if( get4byte(pCell)==iFrom ){
  48879. put4byte(pCell, iTo);
  48880. break;
  48881. }
  48882. }
  48883. }
  48884. if( i==nCell ){
  48885. if( eType!=PTRMAP_BTREE ||
  48886. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  48887. return SQLITE_CORRUPT_BKPT;
  48888. }
  48889. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  48890. }
  48891. pPage->isInit = isInitOrig;
  48892. }
  48893. return SQLITE_OK;
  48894. }
  48895. /*
  48896. ** Move the open database page pDbPage to location iFreePage in the
  48897. ** database. The pDbPage reference remains valid.
  48898. **
  48899. ** The isCommit flag indicates that there is no need to remember that
  48900. ** the journal needs to be sync()ed before database page pDbPage->pgno
  48901. ** can be written to. The caller has already promised not to write to that
  48902. ** page.
  48903. */
  48904. static int relocatePage(
  48905. BtShared *pBt, /* Btree */
  48906. MemPage *pDbPage, /* Open page to move */
  48907. u8 eType, /* Pointer map 'type' entry for pDbPage */
  48908. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  48909. Pgno iFreePage, /* The location to move pDbPage to */
  48910. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  48911. ){
  48912. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  48913. Pgno iDbPage = pDbPage->pgno;
  48914. Pager *pPager = pBt->pPager;
  48915. int rc;
  48916. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  48917. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  48918. assert( sqlite3_mutex_held(pBt->mutex) );
  48919. assert( pDbPage->pBt==pBt );
  48920. /* Move page iDbPage from its current location to page number iFreePage */
  48921. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  48922. iDbPage, iFreePage, iPtrPage, eType));
  48923. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  48924. if( rc!=SQLITE_OK ){
  48925. return rc;
  48926. }
  48927. pDbPage->pgno = iFreePage;
  48928. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  48929. ** that point to overflow pages. The pointer map entries for all these
  48930. ** pages need to be changed.
  48931. **
  48932. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  48933. ** pointer to a subsequent overflow page. If this is the case, then
  48934. ** the pointer map needs to be updated for the subsequent overflow page.
  48935. */
  48936. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  48937. rc = setChildPtrmaps(pDbPage);
  48938. if( rc!=SQLITE_OK ){
  48939. return rc;
  48940. }
  48941. }else{
  48942. Pgno nextOvfl = get4byte(pDbPage->aData);
  48943. if( nextOvfl!=0 ){
  48944. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  48945. if( rc!=SQLITE_OK ){
  48946. return rc;
  48947. }
  48948. }
  48949. }
  48950. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  48951. ** that it points at iFreePage. Also fix the pointer map entry for
  48952. ** iPtrPage.
  48953. */
  48954. if( eType!=PTRMAP_ROOTPAGE ){
  48955. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0, 0);
  48956. if( rc!=SQLITE_OK ){
  48957. return rc;
  48958. }
  48959. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  48960. if( rc!=SQLITE_OK ){
  48961. releasePage(pPtrPage);
  48962. return rc;
  48963. }
  48964. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  48965. releasePage(pPtrPage);
  48966. if( rc==SQLITE_OK ){
  48967. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  48968. }
  48969. }
  48970. return rc;
  48971. }
  48972. /* Forward declaration required by incrVacuumStep(). */
  48973. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  48974. /*
  48975. ** Perform a single step of an incremental-vacuum. If successful, return
  48976. ** SQLITE_OK. If there is no work to do (and therefore no point in
  48977. ** calling this function again), return SQLITE_DONE. Or, if an error
  48978. ** occurs, return some other error code.
  48979. **
  48980. ** More specificly, this function attempts to re-organize the database so
  48981. ** that the last page of the file currently in use is no longer in use.
  48982. **
  48983. ** Parameter nFin is the number of pages that this database would contain
  48984. ** were this function called until it returns SQLITE_DONE.
  48985. **
  48986. ** If the bCommit parameter is non-zero, this function assumes that the
  48987. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  48988. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  48989. ** operation, or false for an incremental vacuum.
  48990. */
  48991. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  48992. Pgno nFreeList; /* Number of pages still on the free-list */
  48993. int rc;
  48994. assert( sqlite3_mutex_held(pBt->mutex) );
  48995. assert( iLastPg>nFin );
  48996. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  48997. u8 eType;
  48998. Pgno iPtrPage;
  48999. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  49000. if( nFreeList==0 ){
  49001. return SQLITE_DONE;
  49002. }
  49003. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  49004. if( rc!=SQLITE_OK ){
  49005. return rc;
  49006. }
  49007. if( eType==PTRMAP_ROOTPAGE ){
  49008. return SQLITE_CORRUPT_BKPT;
  49009. }
  49010. if( eType==PTRMAP_FREEPAGE ){
  49011. if( bCommit==0 ){
  49012. /* Remove the page from the files free-list. This is not required
  49013. ** if bCommit is non-zero. In that case, the free-list will be
  49014. ** truncated to zero after this function returns, so it doesn't
  49015. ** matter if it still contains some garbage entries.
  49016. */
  49017. Pgno iFreePg;
  49018. MemPage *pFreePg;
  49019. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  49020. if( rc!=SQLITE_OK ){
  49021. return rc;
  49022. }
  49023. assert( iFreePg==iLastPg );
  49024. releasePage(pFreePg);
  49025. }
  49026. } else {
  49027. Pgno iFreePg; /* Index of free page to move pLastPg to */
  49028. MemPage *pLastPg;
  49029. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  49030. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  49031. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0, 0);
  49032. if( rc!=SQLITE_OK ){
  49033. return rc;
  49034. }
  49035. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  49036. ** is swapped with the first free page pulled off the free list.
  49037. **
  49038. ** On the other hand, if bCommit is greater than zero, then keep
  49039. ** looping until a free-page located within the first nFin pages
  49040. ** of the file is found.
  49041. */
  49042. if( bCommit==0 ){
  49043. eMode = BTALLOC_LE;
  49044. iNear = nFin;
  49045. }
  49046. do {
  49047. MemPage *pFreePg;
  49048. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  49049. if( rc!=SQLITE_OK ){
  49050. releasePage(pLastPg);
  49051. return rc;
  49052. }
  49053. releasePage(pFreePg);
  49054. }while( bCommit && iFreePg>nFin );
  49055. assert( iFreePg<iLastPg );
  49056. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  49057. releasePage(pLastPg);
  49058. if( rc!=SQLITE_OK ){
  49059. return rc;
  49060. }
  49061. }
  49062. }
  49063. if( bCommit==0 ){
  49064. do {
  49065. iLastPg--;
  49066. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  49067. pBt->bDoTruncate = 1;
  49068. pBt->nPage = iLastPg;
  49069. }
  49070. return SQLITE_OK;
  49071. }
  49072. /*
  49073. ** The database opened by the first argument is an auto-vacuum database
  49074. ** nOrig pages in size containing nFree free pages. Return the expected
  49075. ** size of the database in pages following an auto-vacuum operation.
  49076. */
  49077. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  49078. int nEntry; /* Number of entries on one ptrmap page */
  49079. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  49080. Pgno nFin; /* Return value */
  49081. nEntry = pBt->usableSize/5;
  49082. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  49083. nFin = nOrig - nFree - nPtrmap;
  49084. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  49085. nFin--;
  49086. }
  49087. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  49088. nFin--;
  49089. }
  49090. return nFin;
  49091. }
  49092. /*
  49093. ** A write-transaction must be opened before calling this function.
  49094. ** It performs a single unit of work towards an incremental vacuum.
  49095. **
  49096. ** If the incremental vacuum is finished after this function has run,
  49097. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  49098. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  49099. */
  49100. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  49101. int rc;
  49102. BtShared *pBt = p->pBt;
  49103. sqlite3BtreeEnter(p);
  49104. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  49105. if( !pBt->autoVacuum ){
  49106. rc = SQLITE_DONE;
  49107. }else{
  49108. Pgno nOrig = btreePagecount(pBt);
  49109. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  49110. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  49111. if( nOrig<nFin ){
  49112. rc = SQLITE_CORRUPT_BKPT;
  49113. }else if( nFree>0 ){
  49114. rc = saveAllCursors(pBt, 0, 0);
  49115. if( rc==SQLITE_OK ){
  49116. invalidateAllOverflowCache(pBt);
  49117. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  49118. }
  49119. if( rc==SQLITE_OK ){
  49120. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  49121. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  49122. }
  49123. }else{
  49124. rc = SQLITE_DONE;
  49125. }
  49126. }
  49127. sqlite3BtreeLeave(p);
  49128. return rc;
  49129. }
  49130. /*
  49131. ** This routine is called prior to sqlite3PagerCommit when a transaction
  49132. ** is commited for an auto-vacuum database.
  49133. **
  49134. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  49135. ** the database file should be truncated to during the commit process.
  49136. ** i.e. the database has been reorganized so that only the first *pnTrunc
  49137. ** pages are in use.
  49138. */
  49139. static int autoVacuumCommit(BtShared *pBt){
  49140. int rc = SQLITE_OK;
  49141. Pager *pPager = pBt->pPager;
  49142. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  49143. assert( sqlite3_mutex_held(pBt->mutex) );
  49144. invalidateAllOverflowCache(pBt);
  49145. assert(pBt->autoVacuum);
  49146. if( !pBt->incrVacuum ){
  49147. Pgno nFin; /* Number of pages in database after autovacuuming */
  49148. Pgno nFree; /* Number of pages on the freelist initially */
  49149. Pgno iFree; /* The next page to be freed */
  49150. Pgno nOrig; /* Database size before freeing */
  49151. nOrig = btreePagecount(pBt);
  49152. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  49153. /* It is not possible to create a database for which the final page
  49154. ** is either a pointer-map page or the pending-byte page. If one
  49155. ** is encountered, this indicates corruption.
  49156. */
  49157. return SQLITE_CORRUPT_BKPT;
  49158. }
  49159. nFree = get4byte(&pBt->pPage1->aData[36]);
  49160. nFin = finalDbSize(pBt, nOrig, nFree);
  49161. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  49162. if( nFin<nOrig ){
  49163. rc = saveAllCursors(pBt, 0, 0);
  49164. }
  49165. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  49166. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  49167. }
  49168. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  49169. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  49170. put4byte(&pBt->pPage1->aData[32], 0);
  49171. put4byte(&pBt->pPage1->aData[36], 0);
  49172. put4byte(&pBt->pPage1->aData[28], nFin);
  49173. pBt->bDoTruncate = 1;
  49174. pBt->nPage = nFin;
  49175. }
  49176. if( rc!=SQLITE_OK ){
  49177. sqlite3PagerRollback(pPager);
  49178. }
  49179. }
  49180. assert( nRef>=sqlite3PagerRefcount(pPager) );
  49181. return rc;
  49182. }
  49183. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  49184. # define setChildPtrmaps(x) SQLITE_OK
  49185. #endif
  49186. /*
  49187. ** This routine does the first phase of a two-phase commit. This routine
  49188. ** causes a rollback journal to be created (if it does not already exist)
  49189. ** and populated with enough information so that if a power loss occurs
  49190. ** the database can be restored to its original state by playing back
  49191. ** the journal. Then the contents of the journal are flushed out to
  49192. ** the disk. After the journal is safely on oxide, the changes to the
  49193. ** database are written into the database file and flushed to oxide.
  49194. ** At the end of this call, the rollback journal still exists on the
  49195. ** disk and we are still holding all locks, so the transaction has not
  49196. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  49197. ** commit process.
  49198. **
  49199. ** This call is a no-op if no write-transaction is currently active on pBt.
  49200. **
  49201. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  49202. ** the name of a master journal file that should be written into the
  49203. ** individual journal file, or is NULL, indicating no master journal file
  49204. ** (single database transaction).
  49205. **
  49206. ** When this is called, the master journal should already have been
  49207. ** created, populated with this journal pointer and synced to disk.
  49208. **
  49209. ** Once this is routine has returned, the only thing required to commit
  49210. ** the write-transaction for this database file is to delete the journal.
  49211. */
  49212. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  49213. int rc = SQLITE_OK;
  49214. if( p->inTrans==TRANS_WRITE ){
  49215. BtShared *pBt = p->pBt;
  49216. sqlite3BtreeEnter(p);
  49217. #ifndef SQLITE_OMIT_AUTOVACUUM
  49218. if( pBt->autoVacuum ){
  49219. rc = autoVacuumCommit(pBt);
  49220. if( rc!=SQLITE_OK ){
  49221. sqlite3BtreeLeave(p);
  49222. return rc;
  49223. }
  49224. }
  49225. if( pBt->bDoTruncate ){
  49226. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  49227. }
  49228. #endif
  49229. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  49230. sqlite3BtreeLeave(p);
  49231. }
  49232. return rc;
  49233. }
  49234. /*
  49235. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  49236. ** at the conclusion of a transaction.
  49237. */
  49238. static void btreeEndTransaction(Btree *p){
  49239. BtShared *pBt = p->pBt;
  49240. assert( sqlite3BtreeHoldsMutex(p) );
  49241. #ifndef SQLITE_OMIT_AUTOVACUUM
  49242. pBt->bDoTruncate = 0;
  49243. #endif
  49244. if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
  49245. /* If there are other active statements that belong to this database
  49246. ** handle, downgrade to a read-only transaction. The other statements
  49247. ** may still be reading from the database. */
  49248. downgradeAllSharedCacheTableLocks(p);
  49249. p->inTrans = TRANS_READ;
  49250. }else{
  49251. /* If the handle had any kind of transaction open, decrement the
  49252. ** transaction count of the shared btree. If the transaction count
  49253. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  49254. ** call below will unlock the pager. */
  49255. if( p->inTrans!=TRANS_NONE ){
  49256. clearAllSharedCacheTableLocks(p);
  49257. pBt->nTransaction--;
  49258. if( 0==pBt->nTransaction ){
  49259. pBt->inTransaction = TRANS_NONE;
  49260. }
  49261. }
  49262. /* Set the current transaction state to TRANS_NONE and unlock the
  49263. ** pager if this call closed the only read or write transaction. */
  49264. p->inTrans = TRANS_NONE;
  49265. unlockBtreeIfUnused(pBt);
  49266. }
  49267. btreeIntegrity(p);
  49268. }
  49269. /*
  49270. ** Commit the transaction currently in progress.
  49271. **
  49272. ** This routine implements the second phase of a 2-phase commit. The
  49273. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  49274. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  49275. ** routine did all the work of writing information out to disk and flushing the
  49276. ** contents so that they are written onto the disk platter. All this
  49277. ** routine has to do is delete or truncate or zero the header in the
  49278. ** the rollback journal (which causes the transaction to commit) and
  49279. ** drop locks.
  49280. **
  49281. ** Normally, if an error occurs while the pager layer is attempting to
  49282. ** finalize the underlying journal file, this function returns an error and
  49283. ** the upper layer will attempt a rollback. However, if the second argument
  49284. ** is non-zero then this b-tree transaction is part of a multi-file
  49285. ** transaction. In this case, the transaction has already been committed
  49286. ** (by deleting a master journal file) and the caller will ignore this
  49287. ** functions return code. So, even if an error occurs in the pager layer,
  49288. ** reset the b-tree objects internal state to indicate that the write
  49289. ** transaction has been closed. This is quite safe, as the pager will have
  49290. ** transitioned to the error state.
  49291. **
  49292. ** This will release the write lock on the database file. If there
  49293. ** are no active cursors, it also releases the read lock.
  49294. */
  49295. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  49296. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  49297. sqlite3BtreeEnter(p);
  49298. btreeIntegrity(p);
  49299. /* If the handle has a write-transaction open, commit the shared-btrees
  49300. ** transaction and set the shared state to TRANS_READ.
  49301. */
  49302. if( p->inTrans==TRANS_WRITE ){
  49303. int rc;
  49304. BtShared *pBt = p->pBt;
  49305. assert( pBt->inTransaction==TRANS_WRITE );
  49306. assert( pBt->nTransaction>0 );
  49307. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  49308. if( rc!=SQLITE_OK && bCleanup==0 ){
  49309. sqlite3BtreeLeave(p);
  49310. return rc;
  49311. }
  49312. pBt->inTransaction = TRANS_READ;
  49313. btreeClearHasContent(pBt);
  49314. }
  49315. btreeEndTransaction(p);
  49316. sqlite3BtreeLeave(p);
  49317. return SQLITE_OK;
  49318. }
  49319. /*
  49320. ** Do both phases of a commit.
  49321. */
  49322. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  49323. int rc;
  49324. sqlite3BtreeEnter(p);
  49325. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  49326. if( rc==SQLITE_OK ){
  49327. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  49328. }
  49329. sqlite3BtreeLeave(p);
  49330. return rc;
  49331. }
  49332. /*
  49333. ** This routine sets the state to CURSOR_FAULT and the error
  49334. ** code to errCode for every cursor on BtShared that pBtree
  49335. ** references.
  49336. **
  49337. ** Every cursor is tripped, including cursors that belong
  49338. ** to other database connections that happen to be sharing
  49339. ** the cache with pBtree.
  49340. **
  49341. ** This routine gets called when a rollback occurs.
  49342. ** All cursors using the same cache must be tripped
  49343. ** to prevent them from trying to use the btree after
  49344. ** the rollback. The rollback may have deleted tables
  49345. ** or moved root pages, so it is not sufficient to
  49346. ** save the state of the cursor. The cursor must be
  49347. ** invalidated.
  49348. */
  49349. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  49350. BtCursor *p;
  49351. if( pBtree==0 ) return;
  49352. sqlite3BtreeEnter(pBtree);
  49353. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  49354. int i;
  49355. sqlite3BtreeClearCursor(p);
  49356. p->eState = CURSOR_FAULT;
  49357. p->skipNext = errCode;
  49358. for(i=0; i<=p->iPage; i++){
  49359. releasePage(p->apPage[i]);
  49360. p->apPage[i] = 0;
  49361. }
  49362. }
  49363. sqlite3BtreeLeave(pBtree);
  49364. }
  49365. /*
  49366. ** Rollback the transaction in progress. All cursors will be
  49367. ** invalided by this operation. Any attempt to use a cursor
  49368. ** that was open at the beginning of this operation will result
  49369. ** in an error.
  49370. **
  49371. ** This will release the write lock on the database file. If there
  49372. ** are no active cursors, it also releases the read lock.
  49373. */
  49374. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  49375. int rc;
  49376. BtShared *pBt = p->pBt;
  49377. MemPage *pPage1;
  49378. sqlite3BtreeEnter(p);
  49379. if( tripCode==SQLITE_OK ){
  49380. rc = tripCode = saveAllCursors(pBt, 0, 0);
  49381. }else{
  49382. rc = SQLITE_OK;
  49383. }
  49384. if( tripCode ){
  49385. sqlite3BtreeTripAllCursors(p, tripCode);
  49386. }
  49387. btreeIntegrity(p);
  49388. if( p->inTrans==TRANS_WRITE ){
  49389. int rc2;
  49390. assert( TRANS_WRITE==pBt->inTransaction );
  49391. rc2 = sqlite3PagerRollback(pBt->pPager);
  49392. if( rc2!=SQLITE_OK ){
  49393. rc = rc2;
  49394. }
  49395. /* The rollback may have destroyed the pPage1->aData value. So
  49396. ** call btreeGetPage() on page 1 again to make
  49397. ** sure pPage1->aData is set correctly. */
  49398. if( btreeGetPage(pBt, 1, &pPage1, 0, 0)==SQLITE_OK ){
  49399. int nPage = get4byte(28+(u8*)pPage1->aData);
  49400. testcase( nPage==0 );
  49401. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  49402. testcase( pBt->nPage!=nPage );
  49403. pBt->nPage = nPage;
  49404. releasePage(pPage1);
  49405. }
  49406. assert( countValidCursors(pBt, 1)==0 );
  49407. pBt->inTransaction = TRANS_READ;
  49408. btreeClearHasContent(pBt);
  49409. }
  49410. btreeEndTransaction(p);
  49411. sqlite3BtreeLeave(p);
  49412. return rc;
  49413. }
  49414. /*
  49415. ** Start a statement subtransaction. The subtransaction can can be rolled
  49416. ** back independently of the main transaction. You must start a transaction
  49417. ** before starting a subtransaction. The subtransaction is ended automatically
  49418. ** if the main transaction commits or rolls back.
  49419. **
  49420. ** Statement subtransactions are used around individual SQL statements
  49421. ** that are contained within a BEGIN...COMMIT block. If a constraint
  49422. ** error occurs within the statement, the effect of that one statement
  49423. ** can be rolled back without having to rollback the entire transaction.
  49424. **
  49425. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  49426. ** value passed as the second parameter is the total number of savepoints,
  49427. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  49428. ** are no active savepoints and no other statement-transactions open,
  49429. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  49430. ** using the sqlite3BtreeSavepoint() function.
  49431. */
  49432. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  49433. int rc;
  49434. BtShared *pBt = p->pBt;
  49435. sqlite3BtreeEnter(p);
  49436. assert( p->inTrans==TRANS_WRITE );
  49437. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  49438. assert( iStatement>0 );
  49439. assert( iStatement>p->db->nSavepoint );
  49440. assert( pBt->inTransaction==TRANS_WRITE );
  49441. /* At the pager level, a statement transaction is a savepoint with
  49442. ** an index greater than all savepoints created explicitly using
  49443. ** SQL statements. It is illegal to open, release or rollback any
  49444. ** such savepoints while the statement transaction savepoint is active.
  49445. */
  49446. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  49447. sqlite3BtreeLeave(p);
  49448. return rc;
  49449. }
  49450. /*
  49451. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  49452. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  49453. ** savepoint identified by parameter iSavepoint, depending on the value
  49454. ** of op.
  49455. **
  49456. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  49457. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  49458. ** contents of the entire transaction are rolled back. This is different
  49459. ** from a normal transaction rollback, as no locks are released and the
  49460. ** transaction remains open.
  49461. */
  49462. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  49463. int rc = SQLITE_OK;
  49464. if( p && p->inTrans==TRANS_WRITE ){
  49465. BtShared *pBt = p->pBt;
  49466. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  49467. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  49468. sqlite3BtreeEnter(p);
  49469. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  49470. if( rc==SQLITE_OK ){
  49471. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  49472. pBt->nPage = 0;
  49473. }
  49474. rc = newDatabase(pBt);
  49475. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  49476. /* The database size was written into the offset 28 of the header
  49477. ** when the transaction started, so we know that the value at offset
  49478. ** 28 is nonzero. */
  49479. assert( pBt->nPage>0 );
  49480. }
  49481. sqlite3BtreeLeave(p);
  49482. }
  49483. return rc;
  49484. }
  49485. /*
  49486. ** Create a new cursor for the BTree whose root is on the page
  49487. ** iTable. If a read-only cursor is requested, it is assumed that
  49488. ** the caller already has at least a read-only transaction open
  49489. ** on the database already. If a write-cursor is requested, then
  49490. ** the caller is assumed to have an open write transaction.
  49491. **
  49492. ** If wrFlag==0, then the cursor can only be used for reading.
  49493. ** If wrFlag==1, then the cursor can be used for reading or for
  49494. ** writing if other conditions for writing are also met. These
  49495. ** are the conditions that must be met in order for writing to
  49496. ** be allowed:
  49497. **
  49498. ** 1: The cursor must have been opened with wrFlag==1
  49499. **
  49500. ** 2: Other database connections that share the same pager cache
  49501. ** but which are not in the READ_UNCOMMITTED state may not have
  49502. ** cursors open with wrFlag==0 on the same table. Otherwise
  49503. ** the changes made by this write cursor would be visible to
  49504. ** the read cursors in the other database connection.
  49505. **
  49506. ** 3: The database must be writable (not on read-only media)
  49507. **
  49508. ** 4: There must be an active transaction.
  49509. **
  49510. ** No checking is done to make sure that page iTable really is the
  49511. ** root page of a b-tree. If it is not, then the cursor acquired
  49512. ** will not work correctly.
  49513. **
  49514. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  49515. ** on pCur to initialize the memory space prior to invoking this routine.
  49516. */
  49517. static int btreeCursor(
  49518. Btree *p, /* The btree */
  49519. int iTable, /* Root page of table to open */
  49520. int wrFlag, /* 1 to write. 0 read-only */
  49521. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  49522. BtCursor *pCur /* Space for new cursor */
  49523. ){
  49524. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  49525. assert( sqlite3BtreeHoldsMutex(p) );
  49526. assert( wrFlag==0 || wrFlag==1 );
  49527. /* The following assert statements verify that if this is a sharable
  49528. ** b-tree database, the connection is holding the required table locks,
  49529. ** and that no other connection has any open cursor that conflicts with
  49530. ** this lock. */
  49531. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  49532. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  49533. /* Assert that the caller has opened the required transaction. */
  49534. assert( p->inTrans>TRANS_NONE );
  49535. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  49536. assert( pBt->pPage1 && pBt->pPage1->aData );
  49537. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  49538. return SQLITE_READONLY;
  49539. }
  49540. if( iTable==1 && btreePagecount(pBt)==0 ){
  49541. assert( wrFlag==0 );
  49542. iTable = 0;
  49543. }
  49544. /* Now that no other errors can occur, finish filling in the BtCursor
  49545. ** variables and link the cursor into the BtShared list. */
  49546. pCur->pgnoRoot = (Pgno)iTable;
  49547. pCur->iPage = -1;
  49548. pCur->pKeyInfo = pKeyInfo;
  49549. pCur->pBtree = p;
  49550. pCur->pBt = pBt;
  49551. pCur->wrFlag = (u8)wrFlag;
  49552. pCur->pNext = pBt->pCursor;
  49553. if( pCur->pNext ){
  49554. pCur->pNext->pPrev = pCur;
  49555. }
  49556. pBt->pCursor = pCur;
  49557. pCur->eState = CURSOR_INVALID;
  49558. pCur->cachedRowid = 0;
  49559. return SQLITE_OK;
  49560. }
  49561. SQLITE_PRIVATE int sqlite3BtreeCursor(
  49562. Btree *p, /* The btree */
  49563. int iTable, /* Root page of table to open */
  49564. int wrFlag, /* 1 to write. 0 read-only */
  49565. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  49566. BtCursor *pCur /* Write new cursor here */
  49567. ){
  49568. int rc;
  49569. sqlite3BtreeEnter(p);
  49570. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  49571. sqlite3BtreeLeave(p);
  49572. return rc;
  49573. }
  49574. /*
  49575. ** Return the size of a BtCursor object in bytes.
  49576. **
  49577. ** This interfaces is needed so that users of cursors can preallocate
  49578. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  49579. ** to users so they cannot do the sizeof() themselves - they must call
  49580. ** this routine.
  49581. */
  49582. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  49583. return ROUND8(sizeof(BtCursor));
  49584. }
  49585. /*
  49586. ** Initialize memory that will be converted into a BtCursor object.
  49587. **
  49588. ** The simple approach here would be to memset() the entire object
  49589. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  49590. ** do not need to be zeroed and they are large, so we can save a lot
  49591. ** of run-time by skipping the initialization of those elements.
  49592. */
  49593. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  49594. memset(p, 0, offsetof(BtCursor, iPage));
  49595. }
  49596. /*
  49597. ** Set the cached rowid value of every cursor in the same database file
  49598. ** as pCur and having the same root page number as pCur. The value is
  49599. ** set to iRowid.
  49600. **
  49601. ** Only positive rowid values are considered valid for this cache.
  49602. ** The cache is initialized to zero, indicating an invalid cache.
  49603. ** A btree will work fine with zero or negative rowids. We just cannot
  49604. ** cache zero or negative rowids, which means tables that use zero or
  49605. ** negative rowids might run a little slower. But in practice, zero
  49606. ** or negative rowids are very uncommon so this should not be a problem.
  49607. */
  49608. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  49609. BtCursor *p;
  49610. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  49611. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  49612. }
  49613. assert( pCur->cachedRowid==iRowid );
  49614. }
  49615. /*
  49616. ** Return the cached rowid for the given cursor. A negative or zero
  49617. ** return value indicates that the rowid cache is invalid and should be
  49618. ** ignored. If the rowid cache has never before been set, then a
  49619. ** zero is returned.
  49620. */
  49621. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  49622. return pCur->cachedRowid;
  49623. }
  49624. /*
  49625. ** Close a cursor. The read lock on the database file is released
  49626. ** when the last cursor is closed.
  49627. */
  49628. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  49629. Btree *pBtree = pCur->pBtree;
  49630. if( pBtree ){
  49631. int i;
  49632. BtShared *pBt = pCur->pBt;
  49633. sqlite3BtreeEnter(pBtree);
  49634. sqlite3BtreeClearCursor(pCur);
  49635. if( pCur->pPrev ){
  49636. pCur->pPrev->pNext = pCur->pNext;
  49637. }else{
  49638. pBt->pCursor = pCur->pNext;
  49639. }
  49640. if( pCur->pNext ){
  49641. pCur->pNext->pPrev = pCur->pPrev;
  49642. }
  49643. for(i=0; i<=pCur->iPage; i++){
  49644. releasePage(pCur->apPage[i]);
  49645. }
  49646. unlockBtreeIfUnused(pBt);
  49647. invalidateOverflowCache(pCur);
  49648. /* sqlite3_free(pCur); */
  49649. sqlite3BtreeLeave(pBtree);
  49650. }
  49651. return SQLITE_OK;
  49652. }
  49653. /*
  49654. ** Make sure the BtCursor* given in the argument has a valid
  49655. ** BtCursor.info structure. If it is not already valid, call
  49656. ** btreeParseCell() to fill it in.
  49657. **
  49658. ** BtCursor.info is a cache of the information in the current cell.
  49659. ** Using this cache reduces the number of calls to btreeParseCell().
  49660. **
  49661. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  49662. ** compiler to crash when getCellInfo() is implemented as a macro.
  49663. ** But there is a measureable speed advantage to using the macro on gcc
  49664. ** (when less compiler optimizations like -Os or -O0 are used and the
  49665. ** compiler is not doing agressive inlining.) So we use a real function
  49666. ** for MSVC and a macro for everything else. Ticket #2457.
  49667. */
  49668. #ifndef NDEBUG
  49669. static void assertCellInfo(BtCursor *pCur){
  49670. CellInfo info;
  49671. int iPage = pCur->iPage;
  49672. memset(&info, 0, sizeof(info));
  49673. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  49674. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  49675. }
  49676. #else
  49677. #define assertCellInfo(x)
  49678. #endif
  49679. #ifdef _MSC_VER
  49680. /* Use a real function in MSVC to work around bugs in that compiler. */
  49681. static void getCellInfo(BtCursor *pCur){
  49682. if( pCur->info.nSize==0 ){
  49683. int iPage = pCur->iPage;
  49684. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  49685. pCur->validNKey = 1;
  49686. }else{
  49687. assertCellInfo(pCur);
  49688. }
  49689. }
  49690. #else /* if not _MSC_VER */
  49691. /* Use a macro in all other compilers so that the function is inlined */
  49692. #define getCellInfo(pCur) \
  49693. if( pCur->info.nSize==0 ){ \
  49694. int iPage = pCur->iPage; \
  49695. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  49696. pCur->validNKey = 1; \
  49697. }else{ \
  49698. assertCellInfo(pCur); \
  49699. }
  49700. #endif /* _MSC_VER */
  49701. #ifndef NDEBUG /* The next routine used only within assert() statements */
  49702. /*
  49703. ** Return true if the given BtCursor is valid. A valid cursor is one
  49704. ** that is currently pointing to a row in a (non-empty) table.
  49705. ** This is a verification routine is used only within assert() statements.
  49706. */
  49707. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  49708. return pCur && pCur->eState==CURSOR_VALID;
  49709. }
  49710. #endif /* NDEBUG */
  49711. /*
  49712. ** Set *pSize to the size of the buffer needed to hold the value of
  49713. ** the key for the current entry. If the cursor is not pointing
  49714. ** to a valid entry, *pSize is set to 0.
  49715. **
  49716. ** For a table with the INTKEY flag set, this routine returns the key
  49717. ** itself, not the number of bytes in the key.
  49718. **
  49719. ** The caller must position the cursor prior to invoking this routine.
  49720. **
  49721. ** This routine cannot fail. It always returns SQLITE_OK.
  49722. */
  49723. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  49724. assert( cursorHoldsMutex(pCur) );
  49725. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  49726. if( pCur->eState!=CURSOR_VALID ){
  49727. *pSize = 0;
  49728. }else{
  49729. getCellInfo(pCur);
  49730. *pSize = pCur->info.nKey;
  49731. }
  49732. return SQLITE_OK;
  49733. }
  49734. /*
  49735. ** Set *pSize to the number of bytes of data in the entry the
  49736. ** cursor currently points to.
  49737. **
  49738. ** The caller must guarantee that the cursor is pointing to a non-NULL
  49739. ** valid entry. In other words, the calling procedure must guarantee
  49740. ** that the cursor has Cursor.eState==CURSOR_VALID.
  49741. **
  49742. ** Failure is not possible. This function always returns SQLITE_OK.
  49743. ** It might just as well be a procedure (returning void) but we continue
  49744. ** to return an integer result code for historical reasons.
  49745. */
  49746. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  49747. assert( cursorHoldsMutex(pCur) );
  49748. assert( pCur->eState==CURSOR_VALID );
  49749. getCellInfo(pCur);
  49750. *pSize = pCur->info.nData;
  49751. return SQLITE_OK;
  49752. }
  49753. /*
  49754. ** Given the page number of an overflow page in the database (parameter
  49755. ** ovfl), this function finds the page number of the next page in the
  49756. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  49757. ** pointer-map data instead of reading the content of page ovfl to do so.
  49758. **
  49759. ** If an error occurs an SQLite error code is returned. Otherwise:
  49760. **
  49761. ** The page number of the next overflow page in the linked list is
  49762. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  49763. ** list, *pPgnoNext is set to zero.
  49764. **
  49765. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  49766. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  49767. ** reference. It is the responsibility of the caller to call releasePage()
  49768. ** on *ppPage to free the reference. In no reference was obtained (because
  49769. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  49770. ** *ppPage is set to zero.
  49771. */
  49772. static int getOverflowPage(
  49773. BtShared *pBt, /* The database file */
  49774. Pgno ovfl, /* Current overflow page number */
  49775. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  49776. Pgno *pPgnoNext /* OUT: Next overflow page number */
  49777. ){
  49778. Pgno next = 0;
  49779. MemPage *pPage = 0;
  49780. int rc = SQLITE_OK;
  49781. assert( sqlite3_mutex_held(pBt->mutex) );
  49782. assert(pPgnoNext);
  49783. #ifndef SQLITE_OMIT_AUTOVACUUM
  49784. /* Try to find the next page in the overflow list using the
  49785. ** autovacuum pointer-map pages. Guess that the next page in
  49786. ** the overflow list is page number (ovfl+1). If that guess turns
  49787. ** out to be wrong, fall back to loading the data of page
  49788. ** number ovfl to determine the next page number.
  49789. */
  49790. if( pBt->autoVacuum ){
  49791. Pgno pgno;
  49792. Pgno iGuess = ovfl+1;
  49793. u8 eType;
  49794. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  49795. iGuess++;
  49796. }
  49797. if( iGuess<=btreePagecount(pBt) ){
  49798. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  49799. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  49800. next = iGuess;
  49801. rc = SQLITE_DONE;
  49802. }
  49803. }
  49804. }
  49805. #endif
  49806. assert( next==0 || rc==SQLITE_DONE );
  49807. if( rc==SQLITE_OK ){
  49808. rc = btreeGetPage(pBt, ovfl, &pPage, 0, (ppPage==0));
  49809. assert( rc==SQLITE_OK || pPage==0 );
  49810. if( rc==SQLITE_OK ){
  49811. next = get4byte(pPage->aData);
  49812. }
  49813. }
  49814. *pPgnoNext = next;
  49815. if( ppPage ){
  49816. *ppPage = pPage;
  49817. }else{
  49818. releasePage(pPage);
  49819. }
  49820. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  49821. }
  49822. /*
  49823. ** Copy data from a buffer to a page, or from a page to a buffer.
  49824. **
  49825. ** pPayload is a pointer to data stored on database page pDbPage.
  49826. ** If argument eOp is false, then nByte bytes of data are copied
  49827. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  49828. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  49829. ** of data are copied from the buffer pBuf to pPayload.
  49830. **
  49831. ** SQLITE_OK is returned on success, otherwise an error code.
  49832. */
  49833. static int copyPayload(
  49834. void *pPayload, /* Pointer to page data */
  49835. void *pBuf, /* Pointer to buffer */
  49836. int nByte, /* Number of bytes to copy */
  49837. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  49838. DbPage *pDbPage /* Page containing pPayload */
  49839. ){
  49840. if( eOp ){
  49841. /* Copy data from buffer to page (a write operation) */
  49842. int rc = sqlite3PagerWrite(pDbPage);
  49843. if( rc!=SQLITE_OK ){
  49844. return rc;
  49845. }
  49846. memcpy(pPayload, pBuf, nByte);
  49847. }else{
  49848. /* Copy data from page to buffer (a read operation) */
  49849. memcpy(pBuf, pPayload, nByte);
  49850. }
  49851. return SQLITE_OK;
  49852. }
  49853. /*
  49854. ** This function is used to read or overwrite payload information
  49855. ** for the entry that the pCur cursor is pointing to. If the eOp
  49856. ** parameter is 0, this is a read operation (data copied into
  49857. ** buffer pBuf). If it is non-zero, a write (data copied from
  49858. ** buffer pBuf).
  49859. **
  49860. ** A total of "amt" bytes are read or written beginning at "offset".
  49861. ** Data is read to or from the buffer pBuf.
  49862. **
  49863. ** The content being read or written might appear on the main page
  49864. ** or be scattered out on multiple overflow pages.
  49865. **
  49866. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  49867. ** cursor entry uses one or more overflow pages, this function
  49868. ** allocates space for and lazily popluates the overflow page-list
  49869. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  49870. ** cache to make seeking to the supplied offset more efficient.
  49871. **
  49872. ** Once an overflow page-list cache has been allocated, it may be
  49873. ** invalidated if some other cursor writes to the same table, or if
  49874. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  49875. ** mode, the following events may invalidate an overflow page-list cache.
  49876. **
  49877. ** * An incremental vacuum,
  49878. ** * A commit in auto_vacuum="full" mode,
  49879. ** * Creating a table (may require moving an overflow page).
  49880. */
  49881. static int accessPayload(
  49882. BtCursor *pCur, /* Cursor pointing to entry to read from */
  49883. u32 offset, /* Begin reading this far into payload */
  49884. u32 amt, /* Read this many bytes */
  49885. unsigned char *pBuf, /* Write the bytes into this buffer */
  49886. int eOp /* zero to read. non-zero to write. */
  49887. ){
  49888. unsigned char *aPayload;
  49889. int rc = SQLITE_OK;
  49890. u32 nKey;
  49891. int iIdx = 0;
  49892. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  49893. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  49894. assert( pPage );
  49895. assert( pCur->eState==CURSOR_VALID );
  49896. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  49897. assert( cursorHoldsMutex(pCur) );
  49898. getCellInfo(pCur);
  49899. aPayload = pCur->info.pCell + pCur->info.nHeader;
  49900. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  49901. if( NEVER(offset+amt > nKey+pCur->info.nData)
  49902. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  49903. ){
  49904. /* Trying to read or write past the end of the data is an error */
  49905. return SQLITE_CORRUPT_BKPT;
  49906. }
  49907. /* Check if data must be read/written to/from the btree page itself. */
  49908. if( offset<pCur->info.nLocal ){
  49909. int a = amt;
  49910. if( a+offset>pCur->info.nLocal ){
  49911. a = pCur->info.nLocal - offset;
  49912. }
  49913. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  49914. offset = 0;
  49915. pBuf += a;
  49916. amt -= a;
  49917. }else{
  49918. offset -= pCur->info.nLocal;
  49919. }
  49920. if( rc==SQLITE_OK && amt>0 ){
  49921. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  49922. Pgno nextPage;
  49923. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  49924. #ifndef SQLITE_OMIT_INCRBLOB
  49925. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  49926. ** has not been allocated, allocate it now. The array is sized at
  49927. ** one entry for each overflow page in the overflow chain. The
  49928. ** page number of the first overflow page is stored in aOverflow[0],
  49929. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  49930. ** (the cache is lazily populated).
  49931. */
  49932. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  49933. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  49934. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  49935. /* nOvfl is always positive. If it were zero, fetchPayload would have
  49936. ** been used instead of this routine. */
  49937. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  49938. rc = SQLITE_NOMEM;
  49939. }
  49940. }
  49941. /* If the overflow page-list cache has been allocated and the
  49942. ** entry for the first required overflow page is valid, skip
  49943. ** directly to it.
  49944. */
  49945. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  49946. iIdx = (offset/ovflSize);
  49947. nextPage = pCur->aOverflow[iIdx];
  49948. offset = (offset%ovflSize);
  49949. }
  49950. #endif
  49951. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  49952. #ifndef SQLITE_OMIT_INCRBLOB
  49953. /* If required, populate the overflow page-list cache. */
  49954. if( pCur->aOverflow ){
  49955. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  49956. pCur->aOverflow[iIdx] = nextPage;
  49957. }
  49958. #endif
  49959. if( offset>=ovflSize ){
  49960. /* The only reason to read this page is to obtain the page
  49961. ** number for the next page in the overflow chain. The page
  49962. ** data is not required. So first try to lookup the overflow
  49963. ** page-list cache, if any, then fall back to the getOverflowPage()
  49964. ** function.
  49965. */
  49966. #ifndef SQLITE_OMIT_INCRBLOB
  49967. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  49968. nextPage = pCur->aOverflow[iIdx+1];
  49969. } else
  49970. #endif
  49971. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  49972. offset -= ovflSize;
  49973. }else{
  49974. /* Need to read this page properly. It contains some of the
  49975. ** range of data that is being read (eOp==0) or written (eOp!=0).
  49976. */
  49977. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  49978. sqlite3_file *fd;
  49979. #endif
  49980. int a = amt;
  49981. if( a + offset > ovflSize ){
  49982. a = ovflSize - offset;
  49983. }
  49984. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  49985. /* If all the following are true:
  49986. **
  49987. ** 1) this is a read operation, and
  49988. ** 2) data is required from the start of this overflow page, and
  49989. ** 3) the database is file-backed, and
  49990. ** 4) there is no open write-transaction, and
  49991. ** 5) the database is not a WAL database,
  49992. **
  49993. ** then data can be read directly from the database file into the
  49994. ** output buffer, bypassing the page-cache altogether. This speeds
  49995. ** up loading large records that span many overflow pages.
  49996. */
  49997. if( eOp==0 /* (1) */
  49998. && offset==0 /* (2) */
  49999. && pBt->inTransaction==TRANS_READ /* (4) */
  50000. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  50001. && pBt->pPage1->aData[19]==0x01 /* (5) */
  50002. ){
  50003. u8 aSave[4];
  50004. u8 *aWrite = &pBuf[-4];
  50005. memcpy(aSave, aWrite, 4);
  50006. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  50007. nextPage = get4byte(aWrite);
  50008. memcpy(aWrite, aSave, 4);
  50009. }else
  50010. #endif
  50011. {
  50012. DbPage *pDbPage;
  50013. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  50014. (eOp==0 ? PAGER_ACQUIRE_READONLY : 0)
  50015. );
  50016. if( rc==SQLITE_OK ){
  50017. aPayload = sqlite3PagerGetData(pDbPage);
  50018. nextPage = get4byte(aPayload);
  50019. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  50020. sqlite3PagerUnref(pDbPage);
  50021. offset = 0;
  50022. }
  50023. }
  50024. amt -= a;
  50025. pBuf += a;
  50026. }
  50027. }
  50028. }
  50029. if( rc==SQLITE_OK && amt>0 ){
  50030. return SQLITE_CORRUPT_BKPT;
  50031. }
  50032. return rc;
  50033. }
  50034. /*
  50035. ** Read part of the key associated with cursor pCur. Exactly
  50036. ** "amt" bytes will be transfered into pBuf[]. The transfer
  50037. ** begins at "offset".
  50038. **
  50039. ** The caller must ensure that pCur is pointing to a valid row
  50040. ** in the table.
  50041. **
  50042. ** Return SQLITE_OK on success or an error code if anything goes
  50043. ** wrong. An error is returned if "offset+amt" is larger than
  50044. ** the available payload.
  50045. */
  50046. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  50047. assert( cursorHoldsMutex(pCur) );
  50048. assert( pCur->eState==CURSOR_VALID );
  50049. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  50050. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  50051. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  50052. }
  50053. /*
  50054. ** Read part of the data associated with cursor pCur. Exactly
  50055. ** "amt" bytes will be transfered into pBuf[]. The transfer
  50056. ** begins at "offset".
  50057. **
  50058. ** Return SQLITE_OK on success or an error code if anything goes
  50059. ** wrong. An error is returned if "offset+amt" is larger than
  50060. ** the available payload.
  50061. */
  50062. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  50063. int rc;
  50064. #ifndef SQLITE_OMIT_INCRBLOB
  50065. if ( pCur->eState==CURSOR_INVALID ){
  50066. return SQLITE_ABORT;
  50067. }
  50068. #endif
  50069. assert( cursorHoldsMutex(pCur) );
  50070. rc = restoreCursorPosition(pCur);
  50071. if( rc==SQLITE_OK ){
  50072. assert( pCur->eState==CURSOR_VALID );
  50073. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  50074. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  50075. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  50076. }
  50077. return rc;
  50078. }
  50079. /*
  50080. ** Return a pointer to payload information from the entry that the
  50081. ** pCur cursor is pointing to. The pointer is to the beginning of
  50082. ** the key if skipKey==0 and it points to the beginning of data if
  50083. ** skipKey==1. The number of bytes of available key/data is written
  50084. ** into *pAmt. If *pAmt==0, then the value returned will not be
  50085. ** a valid pointer.
  50086. **
  50087. ** This routine is an optimization. It is common for the entire key
  50088. ** and data to fit on the local page and for there to be no overflow
  50089. ** pages. When that is so, this routine can be used to access the
  50090. ** key and data without making a copy. If the key and/or data spills
  50091. ** onto overflow pages, then accessPayload() must be used to reassemble
  50092. ** the key/data and copy it into a preallocated buffer.
  50093. **
  50094. ** The pointer returned by this routine looks directly into the cached
  50095. ** page of the database. The data might change or move the next time
  50096. ** any btree routine is called.
  50097. */
  50098. static const unsigned char *fetchPayload(
  50099. BtCursor *pCur, /* Cursor pointing to entry to read from */
  50100. int *pAmt, /* Write the number of available bytes here */
  50101. int skipKey /* read beginning at data if this is true */
  50102. ){
  50103. unsigned char *aPayload;
  50104. MemPage *pPage;
  50105. u32 nKey;
  50106. u32 nLocal;
  50107. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  50108. assert( pCur->eState==CURSOR_VALID );
  50109. assert( cursorHoldsMutex(pCur) );
  50110. pPage = pCur->apPage[pCur->iPage];
  50111. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  50112. if( NEVER(pCur->info.nSize==0) ){
  50113. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  50114. &pCur->info);
  50115. }
  50116. aPayload = pCur->info.pCell;
  50117. aPayload += pCur->info.nHeader;
  50118. if( pPage->intKey ){
  50119. nKey = 0;
  50120. }else{
  50121. nKey = (int)pCur->info.nKey;
  50122. }
  50123. if( skipKey ){
  50124. aPayload += nKey;
  50125. nLocal = pCur->info.nLocal - nKey;
  50126. }else{
  50127. nLocal = pCur->info.nLocal;
  50128. assert( nLocal<=nKey );
  50129. }
  50130. *pAmt = nLocal;
  50131. return aPayload;
  50132. }
  50133. /*
  50134. ** For the entry that cursor pCur is point to, return as
  50135. ** many bytes of the key or data as are available on the local
  50136. ** b-tree page. Write the number of available bytes into *pAmt.
  50137. **
  50138. ** The pointer returned is ephemeral. The key/data may move
  50139. ** or be destroyed on the next call to any Btree routine,
  50140. ** including calls from other threads against the same cache.
  50141. ** Hence, a mutex on the BtShared should be held prior to calling
  50142. ** this routine.
  50143. **
  50144. ** These routines is used to get quick access to key and data
  50145. ** in the common case where no overflow pages are used.
  50146. */
  50147. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  50148. const void *p = 0;
  50149. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50150. assert( cursorHoldsMutex(pCur) );
  50151. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  50152. p = (const void*)fetchPayload(pCur, pAmt, 0);
  50153. }
  50154. return p;
  50155. }
  50156. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  50157. const void *p = 0;
  50158. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50159. assert( cursorHoldsMutex(pCur) );
  50160. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  50161. p = (const void*)fetchPayload(pCur, pAmt, 1);
  50162. }
  50163. return p;
  50164. }
  50165. /*
  50166. ** Move the cursor down to a new child page. The newPgno argument is the
  50167. ** page number of the child page to move to.
  50168. **
  50169. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  50170. ** the new child page does not match the flags field of the parent (i.e.
  50171. ** if an intkey page appears to be the parent of a non-intkey page, or
  50172. ** vice-versa).
  50173. */
  50174. static int moveToChild(BtCursor *pCur, u32 newPgno){
  50175. int rc;
  50176. int i = pCur->iPage;
  50177. MemPage *pNewPage;
  50178. BtShared *pBt = pCur->pBt;
  50179. assert( cursorHoldsMutex(pCur) );
  50180. assert( pCur->eState==CURSOR_VALID );
  50181. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  50182. assert( pCur->iPage>=0 );
  50183. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  50184. return SQLITE_CORRUPT_BKPT;
  50185. }
  50186. rc = getAndInitPage(pBt, newPgno, &pNewPage, (pCur->wrFlag==0));
  50187. if( rc ) return rc;
  50188. pCur->apPage[i+1] = pNewPage;
  50189. pCur->aiIdx[i+1] = 0;
  50190. pCur->iPage++;
  50191. pCur->info.nSize = 0;
  50192. pCur->validNKey = 0;
  50193. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  50194. return SQLITE_CORRUPT_BKPT;
  50195. }
  50196. return SQLITE_OK;
  50197. }
  50198. #if 0
  50199. /*
  50200. ** Page pParent is an internal (non-leaf) tree page. This function
  50201. ** asserts that page number iChild is the left-child if the iIdx'th
  50202. ** cell in page pParent. Or, if iIdx is equal to the total number of
  50203. ** cells in pParent, that page number iChild is the right-child of
  50204. ** the page.
  50205. */
  50206. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  50207. assert( iIdx<=pParent->nCell );
  50208. if( iIdx==pParent->nCell ){
  50209. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  50210. }else{
  50211. assert( get4byte(findCell(pParent, iIdx))==iChild );
  50212. }
  50213. }
  50214. #else
  50215. # define assertParentIndex(x,y,z)
  50216. #endif
  50217. /*
  50218. ** Move the cursor up to the parent page.
  50219. **
  50220. ** pCur->idx is set to the cell index that contains the pointer
  50221. ** to the page we are coming from. If we are coming from the
  50222. ** right-most child page then pCur->idx is set to one more than
  50223. ** the largest cell index.
  50224. */
  50225. static void moveToParent(BtCursor *pCur){
  50226. assert( cursorHoldsMutex(pCur) );
  50227. assert( pCur->eState==CURSOR_VALID );
  50228. assert( pCur->iPage>0 );
  50229. assert( pCur->apPage[pCur->iPage] );
  50230. /* UPDATE: It is actually possible for the condition tested by the assert
  50231. ** below to be untrue if the database file is corrupt. This can occur if
  50232. ** one cursor has modified page pParent while a reference to it is held
  50233. ** by a second cursor. Which can only happen if a single page is linked
  50234. ** into more than one b-tree structure in a corrupt database. */
  50235. #if 0
  50236. assertParentIndex(
  50237. pCur->apPage[pCur->iPage-1],
  50238. pCur->aiIdx[pCur->iPage-1],
  50239. pCur->apPage[pCur->iPage]->pgno
  50240. );
  50241. #endif
  50242. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  50243. releasePage(pCur->apPage[pCur->iPage]);
  50244. pCur->iPage--;
  50245. pCur->info.nSize = 0;
  50246. pCur->validNKey = 0;
  50247. }
  50248. /*
  50249. ** Move the cursor to point to the root page of its b-tree structure.
  50250. **
  50251. ** If the table has a virtual root page, then the cursor is moved to point
  50252. ** to the virtual root page instead of the actual root page. A table has a
  50253. ** virtual root page when the actual root page contains no cells and a
  50254. ** single child page. This can only happen with the table rooted at page 1.
  50255. **
  50256. ** If the b-tree structure is empty, the cursor state is set to
  50257. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  50258. ** cell located on the root (or virtual root) page and the cursor state
  50259. ** is set to CURSOR_VALID.
  50260. **
  50261. ** If this function returns successfully, it may be assumed that the
  50262. ** page-header flags indicate that the [virtual] root-page is the expected
  50263. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  50264. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  50265. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  50266. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  50267. ** b-tree).
  50268. */
  50269. static int moveToRoot(BtCursor *pCur){
  50270. MemPage *pRoot;
  50271. int rc = SQLITE_OK;
  50272. Btree *p = pCur->pBtree;
  50273. BtShared *pBt = p->pBt;
  50274. assert( cursorHoldsMutex(pCur) );
  50275. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  50276. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  50277. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  50278. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  50279. if( pCur->eState==CURSOR_FAULT ){
  50280. assert( pCur->skipNext!=SQLITE_OK );
  50281. return pCur->skipNext;
  50282. }
  50283. sqlite3BtreeClearCursor(pCur);
  50284. }
  50285. if( pCur->iPage>=0 ){
  50286. int i;
  50287. for(i=1; i<=pCur->iPage; i++){
  50288. releasePage(pCur->apPage[i]);
  50289. }
  50290. pCur->iPage = 0;
  50291. }else if( pCur->pgnoRoot==0 ){
  50292. pCur->eState = CURSOR_INVALID;
  50293. return SQLITE_OK;
  50294. }else{
  50295. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], pCur->wrFlag==0);
  50296. if( rc!=SQLITE_OK ){
  50297. pCur->eState = CURSOR_INVALID;
  50298. return rc;
  50299. }
  50300. pCur->iPage = 0;
  50301. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  50302. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  50303. ** NULL, the caller expects a table b-tree. If this is not the case,
  50304. ** return an SQLITE_CORRUPT error. */
  50305. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  50306. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  50307. return SQLITE_CORRUPT_BKPT;
  50308. }
  50309. }
  50310. /* Assert that the root page is of the correct type. This must be the
  50311. ** case as the call to this function that loaded the root-page (either
  50312. ** this call or a previous invocation) would have detected corruption
  50313. ** if the assumption were not true, and it is not possible for the flags
  50314. ** byte to have been modified while this cursor is holding a reference
  50315. ** to the page. */
  50316. pRoot = pCur->apPage[0];
  50317. assert( pRoot->pgno==pCur->pgnoRoot );
  50318. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  50319. pCur->aiIdx[0] = 0;
  50320. pCur->info.nSize = 0;
  50321. pCur->atLast = 0;
  50322. pCur->validNKey = 0;
  50323. if( pRoot->nCell==0 && !pRoot->leaf ){
  50324. Pgno subpage;
  50325. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  50326. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  50327. pCur->eState = CURSOR_VALID;
  50328. rc = moveToChild(pCur, subpage);
  50329. }else{
  50330. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  50331. }
  50332. return rc;
  50333. }
  50334. /*
  50335. ** Move the cursor down to the left-most leaf entry beneath the
  50336. ** entry to which it is currently pointing.
  50337. **
  50338. ** The left-most leaf is the one with the smallest key - the first
  50339. ** in ascending order.
  50340. */
  50341. static int moveToLeftmost(BtCursor *pCur){
  50342. Pgno pgno;
  50343. int rc = SQLITE_OK;
  50344. MemPage *pPage;
  50345. assert( cursorHoldsMutex(pCur) );
  50346. assert( pCur->eState==CURSOR_VALID );
  50347. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  50348. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  50349. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  50350. rc = moveToChild(pCur, pgno);
  50351. }
  50352. return rc;
  50353. }
  50354. /*
  50355. ** Move the cursor down to the right-most leaf entry beneath the
  50356. ** page to which it is currently pointing. Notice the difference
  50357. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  50358. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  50359. ** finds the right-most entry beneath the *page*.
  50360. **
  50361. ** The right-most entry is the one with the largest key - the last
  50362. ** key in ascending order.
  50363. */
  50364. static int moveToRightmost(BtCursor *pCur){
  50365. Pgno pgno;
  50366. int rc = SQLITE_OK;
  50367. MemPage *pPage = 0;
  50368. assert( cursorHoldsMutex(pCur) );
  50369. assert( pCur->eState==CURSOR_VALID );
  50370. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  50371. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  50372. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  50373. rc = moveToChild(pCur, pgno);
  50374. }
  50375. if( rc==SQLITE_OK ){
  50376. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  50377. pCur->info.nSize = 0;
  50378. pCur->validNKey = 0;
  50379. }
  50380. return rc;
  50381. }
  50382. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  50383. ** on success. Set *pRes to 0 if the cursor actually points to something
  50384. ** or set *pRes to 1 if the table is empty.
  50385. */
  50386. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  50387. int rc;
  50388. assert( cursorHoldsMutex(pCur) );
  50389. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50390. rc = moveToRoot(pCur);
  50391. if( rc==SQLITE_OK ){
  50392. if( pCur->eState==CURSOR_INVALID ){
  50393. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50394. *pRes = 1;
  50395. }else{
  50396. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  50397. *pRes = 0;
  50398. rc = moveToLeftmost(pCur);
  50399. }
  50400. }
  50401. return rc;
  50402. }
  50403. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  50404. ** on success. Set *pRes to 0 if the cursor actually points to something
  50405. ** or set *pRes to 1 if the table is empty.
  50406. */
  50407. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  50408. int rc;
  50409. assert( cursorHoldsMutex(pCur) );
  50410. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50411. /* If the cursor already points to the last entry, this is a no-op. */
  50412. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  50413. #ifdef SQLITE_DEBUG
  50414. /* This block serves to assert() that the cursor really does point
  50415. ** to the last entry in the b-tree. */
  50416. int ii;
  50417. for(ii=0; ii<pCur->iPage; ii++){
  50418. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  50419. }
  50420. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  50421. assert( pCur->apPage[pCur->iPage]->leaf );
  50422. #endif
  50423. return SQLITE_OK;
  50424. }
  50425. rc = moveToRoot(pCur);
  50426. if( rc==SQLITE_OK ){
  50427. if( CURSOR_INVALID==pCur->eState ){
  50428. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50429. *pRes = 1;
  50430. }else{
  50431. assert( pCur->eState==CURSOR_VALID );
  50432. *pRes = 0;
  50433. rc = moveToRightmost(pCur);
  50434. pCur->atLast = rc==SQLITE_OK ?1:0;
  50435. }
  50436. }
  50437. return rc;
  50438. }
  50439. /* Move the cursor so that it points to an entry near the key
  50440. ** specified by pIdxKey or intKey. Return a success code.
  50441. **
  50442. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  50443. ** must be NULL. For index tables, pIdxKey is used and intKey
  50444. ** is ignored.
  50445. **
  50446. ** If an exact match is not found, then the cursor is always
  50447. ** left pointing at a leaf page which would hold the entry if it
  50448. ** were present. The cursor might point to an entry that comes
  50449. ** before or after the key.
  50450. **
  50451. ** An integer is written into *pRes which is the result of
  50452. ** comparing the key with the entry to which the cursor is
  50453. ** pointing. The meaning of the integer written into
  50454. ** *pRes is as follows:
  50455. **
  50456. ** *pRes<0 The cursor is left pointing at an entry that
  50457. ** is smaller than intKey/pIdxKey or if the table is empty
  50458. ** and the cursor is therefore left point to nothing.
  50459. **
  50460. ** *pRes==0 The cursor is left pointing at an entry that
  50461. ** exactly matches intKey/pIdxKey.
  50462. **
  50463. ** *pRes>0 The cursor is left pointing at an entry that
  50464. ** is larger than intKey/pIdxKey.
  50465. **
  50466. */
  50467. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  50468. BtCursor *pCur, /* The cursor to be moved */
  50469. UnpackedRecord *pIdxKey, /* Unpacked index key */
  50470. i64 intKey, /* The table key */
  50471. int biasRight, /* If true, bias the search to the high end */
  50472. int *pRes /* Write search results here */
  50473. ){
  50474. int rc;
  50475. assert( cursorHoldsMutex(pCur) );
  50476. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  50477. assert( pRes );
  50478. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  50479. /* If the cursor is already positioned at the point we are trying
  50480. ** to move to, then just return without doing any work */
  50481. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  50482. && pCur->apPage[0]->intKey
  50483. ){
  50484. if( pCur->info.nKey==intKey ){
  50485. *pRes = 0;
  50486. return SQLITE_OK;
  50487. }
  50488. if( pCur->atLast && pCur->info.nKey<intKey ){
  50489. *pRes = -1;
  50490. return SQLITE_OK;
  50491. }
  50492. }
  50493. rc = moveToRoot(pCur);
  50494. if( rc ){
  50495. return rc;
  50496. }
  50497. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  50498. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  50499. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  50500. if( pCur->eState==CURSOR_INVALID ){
  50501. *pRes = -1;
  50502. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  50503. return SQLITE_OK;
  50504. }
  50505. assert( pCur->apPage[0]->intKey || pIdxKey );
  50506. for(;;){
  50507. int lwr, upr, idx;
  50508. Pgno chldPg;
  50509. MemPage *pPage = pCur->apPage[pCur->iPage];
  50510. int c;
  50511. /* pPage->nCell must be greater than zero. If this is the root-page
  50512. ** the cursor would have been INVALID above and this for(;;) loop
  50513. ** not run. If this is not the root-page, then the moveToChild() routine
  50514. ** would have already detected db corruption. Similarly, pPage must
  50515. ** be the right kind (index or table) of b-tree page. Otherwise
  50516. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  50517. assert( pPage->nCell>0 );
  50518. assert( pPage->intKey==(pIdxKey==0) );
  50519. lwr = 0;
  50520. upr = pPage->nCell-1;
  50521. if( biasRight ){
  50522. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  50523. }else{
  50524. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  50525. }
  50526. for(;;){
  50527. u8 *pCell; /* Pointer to current cell in pPage */
  50528. assert( idx==pCur->aiIdx[pCur->iPage] );
  50529. pCur->info.nSize = 0;
  50530. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  50531. if( pPage->intKey ){
  50532. i64 nCellKey;
  50533. if( pPage->hasData ){
  50534. u32 dummy;
  50535. pCell += getVarint32(pCell, dummy);
  50536. }
  50537. getVarint(pCell, (u64*)&nCellKey);
  50538. if( nCellKey==intKey ){
  50539. c = 0;
  50540. }else if( nCellKey<intKey ){
  50541. c = -1;
  50542. }else{
  50543. assert( nCellKey>intKey );
  50544. c = +1;
  50545. }
  50546. pCur->validNKey = 1;
  50547. pCur->info.nKey = nCellKey;
  50548. }else{
  50549. /* The maximum supported page-size is 65536 bytes. This means that
  50550. ** the maximum number of record bytes stored on an index B-Tree
  50551. ** page is less than 16384 bytes and may be stored as a 2-byte
  50552. ** varint. This information is used to attempt to avoid parsing
  50553. ** the entire cell by checking for the cases where the record is
  50554. ** stored entirely within the b-tree page by inspecting the first
  50555. ** 2 bytes of the cell.
  50556. */
  50557. int nCell = pCell[0];
  50558. if( nCell<=pPage->max1bytePayload
  50559. /* && (pCell+nCell)<pPage->aDataEnd */
  50560. ){
  50561. /* This branch runs if the record-size field of the cell is a
  50562. ** single byte varint and the record fits entirely on the main
  50563. ** b-tree page. */
  50564. testcase( pCell+nCell+1==pPage->aDataEnd );
  50565. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  50566. }else if( !(pCell[1] & 0x80)
  50567. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  50568. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  50569. ){
  50570. /* The record-size field is a 2 byte varint and the record
  50571. ** fits entirely on the main b-tree page. */
  50572. testcase( pCell+nCell+2==pPage->aDataEnd );
  50573. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  50574. }else{
  50575. /* The record flows over onto one or more overflow pages. In
  50576. ** this case the whole cell needs to be parsed, a buffer allocated
  50577. ** and accessPayload() used to retrieve the record into the
  50578. ** buffer before VdbeRecordCompare() can be called. */
  50579. void *pCellKey;
  50580. u8 * const pCellBody = pCell - pPage->childPtrSize;
  50581. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  50582. nCell = (int)pCur->info.nKey;
  50583. pCellKey = sqlite3Malloc( nCell );
  50584. if( pCellKey==0 ){
  50585. rc = SQLITE_NOMEM;
  50586. goto moveto_finish;
  50587. }
  50588. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  50589. if( rc ){
  50590. sqlite3_free(pCellKey);
  50591. goto moveto_finish;
  50592. }
  50593. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  50594. sqlite3_free(pCellKey);
  50595. }
  50596. }
  50597. if( c==0 ){
  50598. if( pPage->intKey && !pPage->leaf ){
  50599. lwr = idx;
  50600. break;
  50601. }else{
  50602. *pRes = 0;
  50603. rc = SQLITE_OK;
  50604. goto moveto_finish;
  50605. }
  50606. }
  50607. if( c<0 ){
  50608. lwr = idx+1;
  50609. }else{
  50610. upr = idx-1;
  50611. }
  50612. if( lwr>upr ){
  50613. break;
  50614. }
  50615. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  50616. }
  50617. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  50618. assert( pPage->isInit );
  50619. if( pPage->leaf ){
  50620. chldPg = 0;
  50621. }else if( lwr>=pPage->nCell ){
  50622. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  50623. }else{
  50624. chldPg = get4byte(findCell(pPage, lwr));
  50625. }
  50626. if( chldPg==0 ){
  50627. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  50628. *pRes = c;
  50629. rc = SQLITE_OK;
  50630. goto moveto_finish;
  50631. }
  50632. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  50633. pCur->info.nSize = 0;
  50634. pCur->validNKey = 0;
  50635. rc = moveToChild(pCur, chldPg);
  50636. if( rc ) goto moveto_finish;
  50637. }
  50638. moveto_finish:
  50639. return rc;
  50640. }
  50641. /*
  50642. ** Return TRUE if the cursor is not pointing at an entry of the table.
  50643. **
  50644. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  50645. ** past the last entry in the table or sqlite3BtreePrev() moves past
  50646. ** the first entry. TRUE is also returned if the table is empty.
  50647. */
  50648. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  50649. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  50650. ** have been deleted? This API will need to change to return an error code
  50651. ** as well as the boolean result value.
  50652. */
  50653. return (CURSOR_VALID!=pCur->eState);
  50654. }
  50655. /*
  50656. ** Advance the cursor to the next entry in the database. If
  50657. ** successful then set *pRes=0. If the cursor
  50658. ** was already pointing to the last entry in the database before
  50659. ** this routine was called, then set *pRes=1.
  50660. */
  50661. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  50662. int rc;
  50663. int idx;
  50664. MemPage *pPage;
  50665. assert( cursorHoldsMutex(pCur) );
  50666. rc = restoreCursorPosition(pCur);
  50667. if( rc!=SQLITE_OK ){
  50668. return rc;
  50669. }
  50670. assert( pRes!=0 );
  50671. if( CURSOR_INVALID==pCur->eState ){
  50672. *pRes = 1;
  50673. return SQLITE_OK;
  50674. }
  50675. if( pCur->skipNext>0 ){
  50676. pCur->skipNext = 0;
  50677. *pRes = 0;
  50678. return SQLITE_OK;
  50679. }
  50680. pCur->skipNext = 0;
  50681. pPage = pCur->apPage[pCur->iPage];
  50682. idx = ++pCur->aiIdx[pCur->iPage];
  50683. assert( pPage->isInit );
  50684. /* If the database file is corrupt, it is possible for the value of idx
  50685. ** to be invalid here. This can only occur if a second cursor modifies
  50686. ** the page while cursor pCur is holding a reference to it. Which can
  50687. ** only happen if the database is corrupt in such a way as to link the
  50688. ** page into more than one b-tree structure. */
  50689. testcase( idx>pPage->nCell );
  50690. pCur->info.nSize = 0;
  50691. pCur->validNKey = 0;
  50692. if( idx>=pPage->nCell ){
  50693. if( !pPage->leaf ){
  50694. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  50695. if( rc ) return rc;
  50696. rc = moveToLeftmost(pCur);
  50697. *pRes = 0;
  50698. return rc;
  50699. }
  50700. do{
  50701. if( pCur->iPage==0 ){
  50702. *pRes = 1;
  50703. pCur->eState = CURSOR_INVALID;
  50704. return SQLITE_OK;
  50705. }
  50706. moveToParent(pCur);
  50707. pPage = pCur->apPage[pCur->iPage];
  50708. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  50709. *pRes = 0;
  50710. if( pPage->intKey ){
  50711. rc = sqlite3BtreeNext(pCur, pRes);
  50712. }else{
  50713. rc = SQLITE_OK;
  50714. }
  50715. return rc;
  50716. }
  50717. *pRes = 0;
  50718. if( pPage->leaf ){
  50719. return SQLITE_OK;
  50720. }
  50721. rc = moveToLeftmost(pCur);
  50722. return rc;
  50723. }
  50724. /*
  50725. ** Step the cursor to the back to the previous entry in the database. If
  50726. ** successful then set *pRes=0. If the cursor
  50727. ** was already pointing to the first entry in the database before
  50728. ** this routine was called, then set *pRes=1.
  50729. */
  50730. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  50731. int rc;
  50732. MemPage *pPage;
  50733. assert( cursorHoldsMutex(pCur) );
  50734. rc = restoreCursorPosition(pCur);
  50735. if( rc!=SQLITE_OK ){
  50736. return rc;
  50737. }
  50738. pCur->atLast = 0;
  50739. if( CURSOR_INVALID==pCur->eState ){
  50740. *pRes = 1;
  50741. return SQLITE_OK;
  50742. }
  50743. if( pCur->skipNext<0 ){
  50744. pCur->skipNext = 0;
  50745. *pRes = 0;
  50746. return SQLITE_OK;
  50747. }
  50748. pCur->skipNext = 0;
  50749. pPage = pCur->apPage[pCur->iPage];
  50750. assert( pPage->isInit );
  50751. if( !pPage->leaf ){
  50752. int idx = pCur->aiIdx[pCur->iPage];
  50753. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  50754. if( rc ){
  50755. return rc;
  50756. }
  50757. rc = moveToRightmost(pCur);
  50758. }else{
  50759. while( pCur->aiIdx[pCur->iPage]==0 ){
  50760. if( pCur->iPage==0 ){
  50761. pCur->eState = CURSOR_INVALID;
  50762. *pRes = 1;
  50763. return SQLITE_OK;
  50764. }
  50765. moveToParent(pCur);
  50766. }
  50767. pCur->info.nSize = 0;
  50768. pCur->validNKey = 0;
  50769. pCur->aiIdx[pCur->iPage]--;
  50770. pPage = pCur->apPage[pCur->iPage];
  50771. if( pPage->intKey && !pPage->leaf ){
  50772. rc = sqlite3BtreePrevious(pCur, pRes);
  50773. }else{
  50774. rc = SQLITE_OK;
  50775. }
  50776. }
  50777. *pRes = 0;
  50778. return rc;
  50779. }
  50780. /*
  50781. ** Allocate a new page from the database file.
  50782. **
  50783. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  50784. ** has already been called on the new page.) The new page has also
  50785. ** been referenced and the calling routine is responsible for calling
  50786. ** sqlite3PagerUnref() on the new page when it is done.
  50787. **
  50788. ** SQLITE_OK is returned on success. Any other return value indicates
  50789. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  50790. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  50791. **
  50792. ** If the "nearby" parameter is not 0, then an effort is made to
  50793. ** locate a page close to the page number "nearby". This can be used in an
  50794. ** attempt to keep related pages close to each other in the database file,
  50795. ** which in turn can make database access faster.
  50796. **
  50797. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  50798. ** anywhere on the free-list, then it is guaranteed to be returned. If
  50799. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  50800. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  50801. ** are no restrictions on which page is returned.
  50802. */
  50803. static int allocateBtreePage(
  50804. BtShared *pBt, /* The btree */
  50805. MemPage **ppPage, /* Store pointer to the allocated page here */
  50806. Pgno *pPgno, /* Store the page number here */
  50807. Pgno nearby, /* Search for a page near this one */
  50808. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  50809. ){
  50810. MemPage *pPage1;
  50811. int rc;
  50812. u32 n; /* Number of pages on the freelist */
  50813. u32 k; /* Number of leaves on the trunk of the freelist */
  50814. MemPage *pTrunk = 0;
  50815. MemPage *pPrevTrunk = 0;
  50816. Pgno mxPage; /* Total size of the database file */
  50817. assert( sqlite3_mutex_held(pBt->mutex) );
  50818. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  50819. pPage1 = pBt->pPage1;
  50820. mxPage = btreePagecount(pBt);
  50821. n = get4byte(&pPage1->aData[36]);
  50822. testcase( n==mxPage-1 );
  50823. if( n>=mxPage ){
  50824. return SQLITE_CORRUPT_BKPT;
  50825. }
  50826. if( n>0 ){
  50827. /* There are pages on the freelist. Reuse one of those pages. */
  50828. Pgno iTrunk;
  50829. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  50830. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  50831. ** shows that the page 'nearby' is somewhere on the free-list, then
  50832. ** the entire-list will be searched for that page.
  50833. */
  50834. #ifndef SQLITE_OMIT_AUTOVACUUM
  50835. if( eMode==BTALLOC_EXACT ){
  50836. if( nearby<=mxPage ){
  50837. u8 eType;
  50838. assert( nearby>0 );
  50839. assert( pBt->autoVacuum );
  50840. rc = ptrmapGet(pBt, nearby, &eType, 0);
  50841. if( rc ) return rc;
  50842. if( eType==PTRMAP_FREEPAGE ){
  50843. searchList = 1;
  50844. }
  50845. }
  50846. }else if( eMode==BTALLOC_LE ){
  50847. searchList = 1;
  50848. }
  50849. #endif
  50850. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  50851. ** first free-list trunk page. iPrevTrunk is initially 1.
  50852. */
  50853. rc = sqlite3PagerWrite(pPage1->pDbPage);
  50854. if( rc ) return rc;
  50855. put4byte(&pPage1->aData[36], n-1);
  50856. /* The code within this loop is run only once if the 'searchList' variable
  50857. ** is not true. Otherwise, it runs once for each trunk-page on the
  50858. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  50859. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  50860. */
  50861. do {
  50862. pPrevTrunk = pTrunk;
  50863. if( pPrevTrunk ){
  50864. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  50865. }else{
  50866. iTrunk = get4byte(&pPage1->aData[32]);
  50867. }
  50868. testcase( iTrunk==mxPage );
  50869. if( iTrunk>mxPage ){
  50870. rc = SQLITE_CORRUPT_BKPT;
  50871. }else{
  50872. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
  50873. }
  50874. if( rc ){
  50875. pTrunk = 0;
  50876. goto end_allocate_page;
  50877. }
  50878. assert( pTrunk!=0 );
  50879. assert( pTrunk->aData!=0 );
  50880. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  50881. if( k==0 && !searchList ){
  50882. /* The trunk has no leaves and the list is not being searched.
  50883. ** So extract the trunk page itself and use it as the newly
  50884. ** allocated page */
  50885. assert( pPrevTrunk==0 );
  50886. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  50887. if( rc ){
  50888. goto end_allocate_page;
  50889. }
  50890. *pPgno = iTrunk;
  50891. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  50892. *ppPage = pTrunk;
  50893. pTrunk = 0;
  50894. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  50895. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  50896. /* Value of k is out of range. Database corruption */
  50897. rc = SQLITE_CORRUPT_BKPT;
  50898. goto end_allocate_page;
  50899. #ifndef SQLITE_OMIT_AUTOVACUUM
  50900. }else if( searchList
  50901. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  50902. ){
  50903. /* The list is being searched and this trunk page is the page
  50904. ** to allocate, regardless of whether it has leaves.
  50905. */
  50906. *pPgno = iTrunk;
  50907. *ppPage = pTrunk;
  50908. searchList = 0;
  50909. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  50910. if( rc ){
  50911. goto end_allocate_page;
  50912. }
  50913. if( k==0 ){
  50914. if( !pPrevTrunk ){
  50915. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  50916. }else{
  50917. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  50918. if( rc!=SQLITE_OK ){
  50919. goto end_allocate_page;
  50920. }
  50921. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  50922. }
  50923. }else{
  50924. /* The trunk page is required by the caller but it contains
  50925. ** pointers to free-list leaves. The first leaf becomes a trunk
  50926. ** page in this case.
  50927. */
  50928. MemPage *pNewTrunk;
  50929. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  50930. if( iNewTrunk>mxPage ){
  50931. rc = SQLITE_CORRUPT_BKPT;
  50932. goto end_allocate_page;
  50933. }
  50934. testcase( iNewTrunk==mxPage );
  50935. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0, 0);
  50936. if( rc!=SQLITE_OK ){
  50937. goto end_allocate_page;
  50938. }
  50939. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  50940. if( rc!=SQLITE_OK ){
  50941. releasePage(pNewTrunk);
  50942. goto end_allocate_page;
  50943. }
  50944. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  50945. put4byte(&pNewTrunk->aData[4], k-1);
  50946. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  50947. releasePage(pNewTrunk);
  50948. if( !pPrevTrunk ){
  50949. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  50950. put4byte(&pPage1->aData[32], iNewTrunk);
  50951. }else{
  50952. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  50953. if( rc ){
  50954. goto end_allocate_page;
  50955. }
  50956. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  50957. }
  50958. }
  50959. pTrunk = 0;
  50960. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  50961. #endif
  50962. }else if( k>0 ){
  50963. /* Extract a leaf from the trunk */
  50964. u32 closest;
  50965. Pgno iPage;
  50966. unsigned char *aData = pTrunk->aData;
  50967. if( nearby>0 ){
  50968. u32 i;
  50969. closest = 0;
  50970. if( eMode==BTALLOC_LE ){
  50971. for(i=0; i<k; i++){
  50972. iPage = get4byte(&aData[8+i*4]);
  50973. if( iPage<=nearby ){
  50974. closest = i;
  50975. break;
  50976. }
  50977. }
  50978. }else{
  50979. int dist;
  50980. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  50981. for(i=1; i<k; i++){
  50982. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  50983. if( d2<dist ){
  50984. closest = i;
  50985. dist = d2;
  50986. }
  50987. }
  50988. }
  50989. }else{
  50990. closest = 0;
  50991. }
  50992. iPage = get4byte(&aData[8+closest*4]);
  50993. testcase( iPage==mxPage );
  50994. if( iPage>mxPage ){
  50995. rc = SQLITE_CORRUPT_BKPT;
  50996. goto end_allocate_page;
  50997. }
  50998. testcase( iPage==mxPage );
  50999. if( !searchList
  51000. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  51001. ){
  51002. int noContent;
  51003. *pPgno = iPage;
  51004. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  51005. ": %d more free pages\n",
  51006. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  51007. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51008. if( rc ) goto end_allocate_page;
  51009. if( closest<k-1 ){
  51010. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  51011. }
  51012. put4byte(&aData[4], k-1);
  51013. noContent = !btreeGetHasContent(pBt, *pPgno);
  51014. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent, 0);
  51015. if( rc==SQLITE_OK ){
  51016. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  51017. if( rc!=SQLITE_OK ){
  51018. releasePage(*ppPage);
  51019. }
  51020. }
  51021. searchList = 0;
  51022. }
  51023. }
  51024. releasePage(pPrevTrunk);
  51025. pPrevTrunk = 0;
  51026. }while( searchList );
  51027. }else{
  51028. /* There are no pages on the freelist, so append a new page to the
  51029. ** database image.
  51030. **
  51031. ** Normally, new pages allocated by this block can be requested from the
  51032. ** pager layer with the 'no-content' flag set. This prevents the pager
  51033. ** from trying to read the pages content from disk. However, if the
  51034. ** current transaction has already run one or more incremental-vacuum
  51035. ** steps, then the page we are about to allocate may contain content
  51036. ** that is required in the event of a rollback. In this case, do
  51037. ** not set the no-content flag. This causes the pager to load and journal
  51038. ** the current page content before overwriting it.
  51039. **
  51040. ** Note that the pager will not actually attempt to load or journal
  51041. ** content for any page that really does lie past the end of the database
  51042. ** file on disk. So the effects of disabling the no-content optimization
  51043. ** here are confined to those pages that lie between the end of the
  51044. ** database image and the end of the database file.
  51045. */
  51046. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
  51047. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51048. if( rc ) return rc;
  51049. pBt->nPage++;
  51050. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  51051. #ifndef SQLITE_OMIT_AUTOVACUUM
  51052. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  51053. /* If *pPgno refers to a pointer-map page, allocate two new pages
  51054. ** at the end of the file instead of one. The first allocated page
  51055. ** becomes a new pointer-map page, the second is used by the caller.
  51056. */
  51057. MemPage *pPg = 0;
  51058. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  51059. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  51060. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent, 0);
  51061. if( rc==SQLITE_OK ){
  51062. rc = sqlite3PagerWrite(pPg->pDbPage);
  51063. releasePage(pPg);
  51064. }
  51065. if( rc ) return rc;
  51066. pBt->nPage++;
  51067. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  51068. }
  51069. #endif
  51070. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  51071. *pPgno = pBt->nPage;
  51072. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  51073. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent, 0);
  51074. if( rc ) return rc;
  51075. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  51076. if( rc!=SQLITE_OK ){
  51077. releasePage(*ppPage);
  51078. }
  51079. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  51080. }
  51081. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  51082. end_allocate_page:
  51083. releasePage(pTrunk);
  51084. releasePage(pPrevTrunk);
  51085. if( rc==SQLITE_OK ){
  51086. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  51087. releasePage(*ppPage);
  51088. return SQLITE_CORRUPT_BKPT;
  51089. }
  51090. (*ppPage)->isInit = 0;
  51091. }else{
  51092. *ppPage = 0;
  51093. }
  51094. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  51095. return rc;
  51096. }
  51097. /*
  51098. ** This function is used to add page iPage to the database file free-list.
  51099. ** It is assumed that the page is not already a part of the free-list.
  51100. **
  51101. ** The value passed as the second argument to this function is optional.
  51102. ** If the caller happens to have a pointer to the MemPage object
  51103. ** corresponding to page iPage handy, it may pass it as the second value.
  51104. ** Otherwise, it may pass NULL.
  51105. **
  51106. ** If a pointer to a MemPage object is passed as the second argument,
  51107. ** its reference count is not altered by this function.
  51108. */
  51109. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  51110. MemPage *pTrunk = 0; /* Free-list trunk page */
  51111. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  51112. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  51113. MemPage *pPage; /* Page being freed. May be NULL. */
  51114. int rc; /* Return Code */
  51115. int nFree; /* Initial number of pages on free-list */
  51116. assert( sqlite3_mutex_held(pBt->mutex) );
  51117. assert( iPage>1 );
  51118. assert( !pMemPage || pMemPage->pgno==iPage );
  51119. if( pMemPage ){
  51120. pPage = pMemPage;
  51121. sqlite3PagerRef(pPage->pDbPage);
  51122. }else{
  51123. pPage = btreePageLookup(pBt, iPage);
  51124. }
  51125. /* Increment the free page count on pPage1 */
  51126. rc = sqlite3PagerWrite(pPage1->pDbPage);
  51127. if( rc ) goto freepage_out;
  51128. nFree = get4byte(&pPage1->aData[36]);
  51129. put4byte(&pPage1->aData[36], nFree+1);
  51130. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  51131. /* If the secure_delete option is enabled, then
  51132. ** always fully overwrite deleted information with zeros.
  51133. */
  51134. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0, 0))!=0) )
  51135. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  51136. ){
  51137. goto freepage_out;
  51138. }
  51139. memset(pPage->aData, 0, pPage->pBt->pageSize);
  51140. }
  51141. /* If the database supports auto-vacuum, write an entry in the pointer-map
  51142. ** to indicate that the page is free.
  51143. */
  51144. if( ISAUTOVACUUM ){
  51145. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  51146. if( rc ) goto freepage_out;
  51147. }
  51148. /* Now manipulate the actual database free-list structure. There are two
  51149. ** possibilities. If the free-list is currently empty, or if the first
  51150. ** trunk page in the free-list is full, then this page will become a
  51151. ** new free-list trunk page. Otherwise, it will become a leaf of the
  51152. ** first trunk page in the current free-list. This block tests if it
  51153. ** is possible to add the page as a new free-list leaf.
  51154. */
  51155. if( nFree!=0 ){
  51156. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  51157. iTrunk = get4byte(&pPage1->aData[32]);
  51158. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
  51159. if( rc!=SQLITE_OK ){
  51160. goto freepage_out;
  51161. }
  51162. nLeaf = get4byte(&pTrunk->aData[4]);
  51163. assert( pBt->usableSize>32 );
  51164. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  51165. rc = SQLITE_CORRUPT_BKPT;
  51166. goto freepage_out;
  51167. }
  51168. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  51169. /* In this case there is room on the trunk page to insert the page
  51170. ** being freed as a new leaf.
  51171. **
  51172. ** Note that the trunk page is not really full until it contains
  51173. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  51174. ** coded. But due to a coding error in versions of SQLite prior to
  51175. ** 3.6.0, databases with freelist trunk pages holding more than
  51176. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  51177. ** to maintain backwards compatibility with older versions of SQLite,
  51178. ** we will continue to restrict the number of entries to usableSize/4 - 8
  51179. ** for now. At some point in the future (once everyone has upgraded
  51180. ** to 3.6.0 or later) we should consider fixing the conditional above
  51181. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  51182. */
  51183. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  51184. if( rc==SQLITE_OK ){
  51185. put4byte(&pTrunk->aData[4], nLeaf+1);
  51186. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  51187. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  51188. sqlite3PagerDontWrite(pPage->pDbPage);
  51189. }
  51190. rc = btreeSetHasContent(pBt, iPage);
  51191. }
  51192. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  51193. goto freepage_out;
  51194. }
  51195. }
  51196. /* If control flows to this point, then it was not possible to add the
  51197. ** the page being freed as a leaf page of the first trunk in the free-list.
  51198. ** Possibly because the free-list is empty, or possibly because the
  51199. ** first trunk in the free-list is full. Either way, the page being freed
  51200. ** will become the new first trunk page in the free-list.
  51201. */
  51202. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0, 0)) ){
  51203. goto freepage_out;
  51204. }
  51205. rc = sqlite3PagerWrite(pPage->pDbPage);
  51206. if( rc!=SQLITE_OK ){
  51207. goto freepage_out;
  51208. }
  51209. put4byte(pPage->aData, iTrunk);
  51210. put4byte(&pPage->aData[4], 0);
  51211. put4byte(&pPage1->aData[32], iPage);
  51212. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  51213. freepage_out:
  51214. if( pPage ){
  51215. pPage->isInit = 0;
  51216. }
  51217. releasePage(pPage);
  51218. releasePage(pTrunk);
  51219. return rc;
  51220. }
  51221. static void freePage(MemPage *pPage, int *pRC){
  51222. if( (*pRC)==SQLITE_OK ){
  51223. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  51224. }
  51225. }
  51226. /*
  51227. ** Free any overflow pages associated with the given Cell.
  51228. */
  51229. static int clearCell(MemPage *pPage, unsigned char *pCell){
  51230. BtShared *pBt = pPage->pBt;
  51231. CellInfo info;
  51232. Pgno ovflPgno;
  51233. int rc;
  51234. int nOvfl;
  51235. u32 ovflPageSize;
  51236. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51237. btreeParseCellPtr(pPage, pCell, &info);
  51238. if( info.iOverflow==0 ){
  51239. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  51240. }
  51241. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  51242. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  51243. }
  51244. ovflPgno = get4byte(&pCell[info.iOverflow]);
  51245. assert( pBt->usableSize > 4 );
  51246. ovflPageSize = pBt->usableSize - 4;
  51247. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  51248. assert( ovflPgno==0 || nOvfl>0 );
  51249. while( nOvfl-- ){
  51250. Pgno iNext = 0;
  51251. MemPage *pOvfl = 0;
  51252. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  51253. /* 0 is not a legal page number and page 1 cannot be an
  51254. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  51255. ** file the database must be corrupt. */
  51256. return SQLITE_CORRUPT_BKPT;
  51257. }
  51258. if( nOvfl ){
  51259. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  51260. if( rc ) return rc;
  51261. }
  51262. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  51263. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  51264. ){
  51265. /* There is no reason any cursor should have an outstanding reference
  51266. ** to an overflow page belonging to a cell that is being deleted/updated.
  51267. ** So if there exists more than one reference to this page, then it
  51268. ** must not really be an overflow page and the database must be corrupt.
  51269. ** It is helpful to detect this before calling freePage2(), as
  51270. ** freePage2() may zero the page contents if secure-delete mode is
  51271. ** enabled. If this 'overflow' page happens to be a page that the
  51272. ** caller is iterating through or using in some other way, this
  51273. ** can be problematic.
  51274. */
  51275. rc = SQLITE_CORRUPT_BKPT;
  51276. }else{
  51277. rc = freePage2(pBt, pOvfl, ovflPgno);
  51278. }
  51279. if( pOvfl ){
  51280. sqlite3PagerUnref(pOvfl->pDbPage);
  51281. }
  51282. if( rc ) return rc;
  51283. ovflPgno = iNext;
  51284. }
  51285. return SQLITE_OK;
  51286. }
  51287. /*
  51288. ** Create the byte sequence used to represent a cell on page pPage
  51289. ** and write that byte sequence into pCell[]. Overflow pages are
  51290. ** allocated and filled in as necessary. The calling procedure
  51291. ** is responsible for making sure sufficient space has been allocated
  51292. ** for pCell[].
  51293. **
  51294. ** Note that pCell does not necessary need to point to the pPage->aData
  51295. ** area. pCell might point to some temporary storage. The cell will
  51296. ** be constructed in this temporary area then copied into pPage->aData
  51297. ** later.
  51298. */
  51299. static int fillInCell(
  51300. MemPage *pPage, /* The page that contains the cell */
  51301. unsigned char *pCell, /* Complete text of the cell */
  51302. const void *pKey, i64 nKey, /* The key */
  51303. const void *pData,int nData, /* The data */
  51304. int nZero, /* Extra zero bytes to append to pData */
  51305. int *pnSize /* Write cell size here */
  51306. ){
  51307. int nPayload;
  51308. const u8 *pSrc;
  51309. int nSrc, n, rc;
  51310. int spaceLeft;
  51311. MemPage *pOvfl = 0;
  51312. MemPage *pToRelease = 0;
  51313. unsigned char *pPrior;
  51314. unsigned char *pPayload;
  51315. BtShared *pBt = pPage->pBt;
  51316. Pgno pgnoOvfl = 0;
  51317. int nHeader;
  51318. CellInfo info;
  51319. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51320. /* pPage is not necessarily writeable since pCell might be auxiliary
  51321. ** buffer space that is separate from the pPage buffer area */
  51322. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  51323. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51324. /* Fill in the header. */
  51325. nHeader = 0;
  51326. if( !pPage->leaf ){
  51327. nHeader += 4;
  51328. }
  51329. if( pPage->hasData ){
  51330. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  51331. }else{
  51332. nData = nZero = 0;
  51333. }
  51334. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  51335. btreeParseCellPtr(pPage, pCell, &info);
  51336. assert( info.nHeader==nHeader );
  51337. assert( info.nKey==nKey );
  51338. assert( info.nData==(u32)(nData+nZero) );
  51339. /* Fill in the payload */
  51340. nPayload = nData + nZero;
  51341. if( pPage->intKey ){
  51342. pSrc = pData;
  51343. nSrc = nData;
  51344. nData = 0;
  51345. }else{
  51346. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  51347. return SQLITE_CORRUPT_BKPT;
  51348. }
  51349. nPayload += (int)nKey;
  51350. pSrc = pKey;
  51351. nSrc = (int)nKey;
  51352. }
  51353. *pnSize = info.nSize;
  51354. spaceLeft = info.nLocal;
  51355. pPayload = &pCell[nHeader];
  51356. pPrior = &pCell[info.iOverflow];
  51357. while( nPayload>0 ){
  51358. if( spaceLeft==0 ){
  51359. #ifndef SQLITE_OMIT_AUTOVACUUM
  51360. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  51361. if( pBt->autoVacuum ){
  51362. do{
  51363. pgnoOvfl++;
  51364. } while(
  51365. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  51366. );
  51367. }
  51368. #endif
  51369. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  51370. #ifndef SQLITE_OMIT_AUTOVACUUM
  51371. /* If the database supports auto-vacuum, and the second or subsequent
  51372. ** overflow page is being allocated, add an entry to the pointer-map
  51373. ** for that page now.
  51374. **
  51375. ** If this is the first overflow page, then write a partial entry
  51376. ** to the pointer-map. If we write nothing to this pointer-map slot,
  51377. ** then the optimistic overflow chain processing in clearCell()
  51378. ** may misinterpret the uninitialized values and delete the
  51379. ** wrong pages from the database.
  51380. */
  51381. if( pBt->autoVacuum && rc==SQLITE_OK ){
  51382. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  51383. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  51384. if( rc ){
  51385. releasePage(pOvfl);
  51386. }
  51387. }
  51388. #endif
  51389. if( rc ){
  51390. releasePage(pToRelease);
  51391. return rc;
  51392. }
  51393. /* If pToRelease is not zero than pPrior points into the data area
  51394. ** of pToRelease. Make sure pToRelease is still writeable. */
  51395. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  51396. /* If pPrior is part of the data area of pPage, then make sure pPage
  51397. ** is still writeable */
  51398. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  51399. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51400. put4byte(pPrior, pgnoOvfl);
  51401. releasePage(pToRelease);
  51402. pToRelease = pOvfl;
  51403. pPrior = pOvfl->aData;
  51404. put4byte(pPrior, 0);
  51405. pPayload = &pOvfl->aData[4];
  51406. spaceLeft = pBt->usableSize - 4;
  51407. }
  51408. n = nPayload;
  51409. if( n>spaceLeft ) n = spaceLeft;
  51410. /* If pToRelease is not zero than pPayload points into the data area
  51411. ** of pToRelease. Make sure pToRelease is still writeable. */
  51412. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  51413. /* If pPayload is part of the data area of pPage, then make sure pPage
  51414. ** is still writeable */
  51415. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  51416. || sqlite3PagerIswriteable(pPage->pDbPage) );
  51417. if( nSrc>0 ){
  51418. if( n>nSrc ) n = nSrc;
  51419. assert( pSrc );
  51420. memcpy(pPayload, pSrc, n);
  51421. }else{
  51422. memset(pPayload, 0, n);
  51423. }
  51424. nPayload -= n;
  51425. pPayload += n;
  51426. pSrc += n;
  51427. nSrc -= n;
  51428. spaceLeft -= n;
  51429. if( nSrc==0 ){
  51430. nSrc = nData;
  51431. pSrc = pData;
  51432. }
  51433. }
  51434. releasePage(pToRelease);
  51435. return SQLITE_OK;
  51436. }
  51437. /*
  51438. ** Remove the i-th cell from pPage. This routine effects pPage only.
  51439. ** The cell content is not freed or deallocated. It is assumed that
  51440. ** the cell content has been copied someplace else. This routine just
  51441. ** removes the reference to the cell from pPage.
  51442. **
  51443. ** "sz" must be the number of bytes in the cell.
  51444. */
  51445. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  51446. u32 pc; /* Offset to cell content of cell being deleted */
  51447. u8 *data; /* pPage->aData */
  51448. u8 *ptr; /* Used to move bytes around within data[] */
  51449. u8 *endPtr; /* End of loop */
  51450. int rc; /* The return code */
  51451. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  51452. if( *pRC ) return;
  51453. assert( idx>=0 && idx<pPage->nCell );
  51454. assert( sz==cellSize(pPage, idx) );
  51455. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51456. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51457. data = pPage->aData;
  51458. ptr = &pPage->aCellIdx[2*idx];
  51459. pc = get2byte(ptr);
  51460. hdr = pPage->hdrOffset;
  51461. testcase( pc==get2byte(&data[hdr+5]) );
  51462. testcase( pc+sz==pPage->pBt->usableSize );
  51463. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  51464. *pRC = SQLITE_CORRUPT_BKPT;
  51465. return;
  51466. }
  51467. rc = freeSpace(pPage, pc, sz);
  51468. if( rc ){
  51469. *pRC = rc;
  51470. return;
  51471. }
  51472. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  51473. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  51474. while( ptr<endPtr ){
  51475. *(u16*)ptr = *(u16*)&ptr[2];
  51476. ptr += 2;
  51477. }
  51478. pPage->nCell--;
  51479. put2byte(&data[hdr+3], pPage->nCell);
  51480. pPage->nFree += 2;
  51481. }
  51482. /*
  51483. ** Insert a new cell on pPage at cell index "i". pCell points to the
  51484. ** content of the cell.
  51485. **
  51486. ** If the cell content will fit on the page, then put it there. If it
  51487. ** will not fit, then make a copy of the cell content into pTemp if
  51488. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  51489. ** in pPage->apOvfl[] and make it point to the cell content (either
  51490. ** in pTemp or the original pCell) and also record its index.
  51491. ** Allocating a new entry in pPage->aCell[] implies that
  51492. ** pPage->nOverflow is incremented.
  51493. **
  51494. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  51495. ** cell. The caller will overwrite them after this function returns. If
  51496. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  51497. ** (but pCell+nSkip is always valid).
  51498. */
  51499. static void insertCell(
  51500. MemPage *pPage, /* Page into which we are copying */
  51501. int i, /* New cell becomes the i-th cell of the page */
  51502. u8 *pCell, /* Content of the new cell */
  51503. int sz, /* Bytes of content in pCell */
  51504. u8 *pTemp, /* Temp storage space for pCell, if needed */
  51505. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  51506. int *pRC /* Read and write return code from here */
  51507. ){
  51508. int idx = 0; /* Where to write new cell content in data[] */
  51509. int j; /* Loop counter */
  51510. int end; /* First byte past the last cell pointer in data[] */
  51511. int ins; /* Index in data[] where new cell pointer is inserted */
  51512. int cellOffset; /* Address of first cell pointer in data[] */
  51513. u8 *data; /* The content of the whole page */
  51514. u8 *ptr; /* Used for moving information around in data[] */
  51515. u8 *endPtr; /* End of the loop */
  51516. int nSkip = (iChild ? 4 : 0);
  51517. if( *pRC ) return;
  51518. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  51519. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  51520. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  51521. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  51522. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51523. /* The cell should normally be sized correctly. However, when moving a
  51524. ** malformed cell from a leaf page to an interior page, if the cell size
  51525. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  51526. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  51527. ** the term after the || in the following assert(). */
  51528. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  51529. if( pPage->nOverflow || sz+2>pPage->nFree ){
  51530. if( pTemp ){
  51531. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  51532. pCell = pTemp;
  51533. }
  51534. if( iChild ){
  51535. put4byte(pCell, iChild);
  51536. }
  51537. j = pPage->nOverflow++;
  51538. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  51539. pPage->apOvfl[j] = pCell;
  51540. pPage->aiOvfl[j] = (u16)i;
  51541. }else{
  51542. int rc = sqlite3PagerWrite(pPage->pDbPage);
  51543. if( rc!=SQLITE_OK ){
  51544. *pRC = rc;
  51545. return;
  51546. }
  51547. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51548. data = pPage->aData;
  51549. cellOffset = pPage->cellOffset;
  51550. end = cellOffset + 2*pPage->nCell;
  51551. ins = cellOffset + 2*i;
  51552. rc = allocateSpace(pPage, sz, &idx);
  51553. if( rc ){ *pRC = rc; return; }
  51554. /* The allocateSpace() routine guarantees the following two properties
  51555. ** if it returns success */
  51556. assert( idx >= end+2 );
  51557. assert( idx+sz <= (int)pPage->pBt->usableSize );
  51558. pPage->nCell++;
  51559. pPage->nFree -= (u16)(2 + sz);
  51560. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  51561. if( iChild ){
  51562. put4byte(&data[idx], iChild);
  51563. }
  51564. ptr = &data[end];
  51565. endPtr = &data[ins];
  51566. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  51567. while( ptr>endPtr ){
  51568. *(u16*)ptr = *(u16*)&ptr[-2];
  51569. ptr -= 2;
  51570. }
  51571. put2byte(&data[ins], idx);
  51572. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  51573. #ifndef SQLITE_OMIT_AUTOVACUUM
  51574. if( pPage->pBt->autoVacuum ){
  51575. /* The cell may contain a pointer to an overflow page. If so, write
  51576. ** the entry for the overflow page into the pointer map.
  51577. */
  51578. ptrmapPutOvflPtr(pPage, pCell, pRC);
  51579. }
  51580. #endif
  51581. }
  51582. }
  51583. /*
  51584. ** Add a list of cells to a page. The page should be initially empty.
  51585. ** The cells are guaranteed to fit on the page.
  51586. */
  51587. static void assemblePage(
  51588. MemPage *pPage, /* The page to be assemblied */
  51589. int nCell, /* The number of cells to add to this page */
  51590. u8 **apCell, /* Pointers to cell bodies */
  51591. u16 *aSize /* Sizes of the cells */
  51592. ){
  51593. int i; /* Loop counter */
  51594. u8 *pCellptr; /* Address of next cell pointer */
  51595. int cellbody; /* Address of next cell body */
  51596. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  51597. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  51598. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  51599. assert( pPage->nOverflow==0 );
  51600. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51601. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  51602. && (int)MX_CELL(pPage->pBt)<=10921);
  51603. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51604. /* Check that the page has just been zeroed by zeroPage() */
  51605. assert( pPage->nCell==0 );
  51606. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  51607. pCellptr = &pPage->aCellIdx[nCell*2];
  51608. cellbody = nUsable;
  51609. for(i=nCell-1; i>=0; i--){
  51610. u16 sz = aSize[i];
  51611. pCellptr -= 2;
  51612. cellbody -= sz;
  51613. put2byte(pCellptr, cellbody);
  51614. memcpy(&data[cellbody], apCell[i], sz);
  51615. }
  51616. put2byte(&data[hdr+3], nCell);
  51617. put2byte(&data[hdr+5], cellbody);
  51618. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  51619. pPage->nCell = (u16)nCell;
  51620. }
  51621. /*
  51622. ** The following parameters determine how many adjacent pages get involved
  51623. ** in a balancing operation. NN is the number of neighbors on either side
  51624. ** of the page that participate in the balancing operation. NB is the
  51625. ** total number of pages that participate, including the target page and
  51626. ** NN neighbors on either side.
  51627. **
  51628. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  51629. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  51630. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  51631. ** The value of NN appears to give the best results overall.
  51632. */
  51633. #define NN 1 /* Number of neighbors on either side of pPage */
  51634. #define NB (NN*2+1) /* Total pages involved in the balance */
  51635. #ifndef SQLITE_OMIT_QUICKBALANCE
  51636. /*
  51637. ** This version of balance() handles the common special case where
  51638. ** a new entry is being inserted on the extreme right-end of the
  51639. ** tree, in other words, when the new entry will become the largest
  51640. ** entry in the tree.
  51641. **
  51642. ** Instead of trying to balance the 3 right-most leaf pages, just add
  51643. ** a new page to the right-hand side and put the one new entry in
  51644. ** that page. This leaves the right side of the tree somewhat
  51645. ** unbalanced. But odds are that we will be inserting new entries
  51646. ** at the end soon afterwards so the nearly empty page will quickly
  51647. ** fill up. On average.
  51648. **
  51649. ** pPage is the leaf page which is the right-most page in the tree.
  51650. ** pParent is its parent. pPage must have a single overflow entry
  51651. ** which is also the right-most entry on the page.
  51652. **
  51653. ** The pSpace buffer is used to store a temporary copy of the divider
  51654. ** cell that will be inserted into pParent. Such a cell consists of a 4
  51655. ** byte page number followed by a variable length integer. In other
  51656. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  51657. ** least 13 bytes in size.
  51658. */
  51659. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  51660. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  51661. MemPage *pNew; /* Newly allocated page */
  51662. int rc; /* Return Code */
  51663. Pgno pgnoNew; /* Page number of pNew */
  51664. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51665. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  51666. assert( pPage->nOverflow==1 );
  51667. /* This error condition is now caught prior to reaching this function */
  51668. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  51669. /* Allocate a new page. This page will become the right-sibling of
  51670. ** pPage. Make the parent page writable, so that the new divider cell
  51671. ** may be inserted. If both these operations are successful, proceed.
  51672. */
  51673. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  51674. if( rc==SQLITE_OK ){
  51675. u8 *pOut = &pSpace[4];
  51676. u8 *pCell = pPage->apOvfl[0];
  51677. u16 szCell = cellSizePtr(pPage, pCell);
  51678. u8 *pStop;
  51679. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  51680. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  51681. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  51682. assemblePage(pNew, 1, &pCell, &szCell);
  51683. /* If this is an auto-vacuum database, update the pointer map
  51684. ** with entries for the new page, and any pointer from the
  51685. ** cell on the page to an overflow page. If either of these
  51686. ** operations fails, the return code is set, but the contents
  51687. ** of the parent page are still manipulated by thh code below.
  51688. ** That is Ok, at this point the parent page is guaranteed to
  51689. ** be marked as dirty. Returning an error code will cause a
  51690. ** rollback, undoing any changes made to the parent page.
  51691. */
  51692. if( ISAUTOVACUUM ){
  51693. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  51694. if( szCell>pNew->minLocal ){
  51695. ptrmapPutOvflPtr(pNew, pCell, &rc);
  51696. }
  51697. }
  51698. /* Create a divider cell to insert into pParent. The divider cell
  51699. ** consists of a 4-byte page number (the page number of pPage) and
  51700. ** a variable length key value (which must be the same value as the
  51701. ** largest key on pPage).
  51702. **
  51703. ** To find the largest key value on pPage, first find the right-most
  51704. ** cell on pPage. The first two fields of this cell are the
  51705. ** record-length (a variable length integer at most 32-bits in size)
  51706. ** and the key value (a variable length integer, may have any value).
  51707. ** The first of the while(...) loops below skips over the record-length
  51708. ** field. The second while(...) loop copies the key value from the
  51709. ** cell on pPage into the pSpace buffer.
  51710. */
  51711. pCell = findCell(pPage, pPage->nCell-1);
  51712. pStop = &pCell[9];
  51713. while( (*(pCell++)&0x80) && pCell<pStop );
  51714. pStop = &pCell[9];
  51715. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  51716. /* Insert the new divider cell into pParent. */
  51717. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  51718. 0, pPage->pgno, &rc);
  51719. /* Set the right-child pointer of pParent to point to the new page. */
  51720. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  51721. /* Release the reference to the new page. */
  51722. releasePage(pNew);
  51723. }
  51724. return rc;
  51725. }
  51726. #endif /* SQLITE_OMIT_QUICKBALANCE */
  51727. #if 0
  51728. /*
  51729. ** This function does not contribute anything to the operation of SQLite.
  51730. ** it is sometimes activated temporarily while debugging code responsible
  51731. ** for setting pointer-map entries.
  51732. */
  51733. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  51734. int i, j;
  51735. for(i=0; i<nPage; i++){
  51736. Pgno n;
  51737. u8 e;
  51738. MemPage *pPage = apPage[i];
  51739. BtShared *pBt = pPage->pBt;
  51740. assert( pPage->isInit );
  51741. for(j=0; j<pPage->nCell; j++){
  51742. CellInfo info;
  51743. u8 *z;
  51744. z = findCell(pPage, j);
  51745. btreeParseCellPtr(pPage, z, &info);
  51746. if( info.iOverflow ){
  51747. Pgno ovfl = get4byte(&z[info.iOverflow]);
  51748. ptrmapGet(pBt, ovfl, &e, &n);
  51749. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  51750. }
  51751. if( !pPage->leaf ){
  51752. Pgno child = get4byte(z);
  51753. ptrmapGet(pBt, child, &e, &n);
  51754. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  51755. }
  51756. }
  51757. if( !pPage->leaf ){
  51758. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  51759. ptrmapGet(pBt, child, &e, &n);
  51760. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  51761. }
  51762. }
  51763. return 1;
  51764. }
  51765. #endif
  51766. /*
  51767. ** This function is used to copy the contents of the b-tree node stored
  51768. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  51769. ** the pointer-map entries for each child page are updated so that the
  51770. ** parent page stored in the pointer map is page pTo. If pFrom contained
  51771. ** any cells with overflow page pointers, then the corresponding pointer
  51772. ** map entries are also updated so that the parent page is page pTo.
  51773. **
  51774. ** If pFrom is currently carrying any overflow cells (entries in the
  51775. ** MemPage.apOvfl[] array), they are not copied to pTo.
  51776. **
  51777. ** Before returning, page pTo is reinitialized using btreeInitPage().
  51778. **
  51779. ** The performance of this function is not critical. It is only used by
  51780. ** the balance_shallower() and balance_deeper() procedures, neither of
  51781. ** which are called often under normal circumstances.
  51782. */
  51783. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  51784. if( (*pRC)==SQLITE_OK ){
  51785. BtShared * const pBt = pFrom->pBt;
  51786. u8 * const aFrom = pFrom->aData;
  51787. u8 * const aTo = pTo->aData;
  51788. int const iFromHdr = pFrom->hdrOffset;
  51789. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  51790. int rc;
  51791. int iData;
  51792. assert( pFrom->isInit );
  51793. assert( pFrom->nFree>=iToHdr );
  51794. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  51795. /* Copy the b-tree node content from page pFrom to page pTo. */
  51796. iData = get2byte(&aFrom[iFromHdr+5]);
  51797. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  51798. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  51799. /* Reinitialize page pTo so that the contents of the MemPage structure
  51800. ** match the new data. The initialization of pTo can actually fail under
  51801. ** fairly obscure circumstances, even though it is a copy of initialized
  51802. ** page pFrom.
  51803. */
  51804. pTo->isInit = 0;
  51805. rc = btreeInitPage(pTo);
  51806. if( rc!=SQLITE_OK ){
  51807. *pRC = rc;
  51808. return;
  51809. }
  51810. /* If this is an auto-vacuum database, update the pointer-map entries
  51811. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  51812. */
  51813. if( ISAUTOVACUUM ){
  51814. *pRC = setChildPtrmaps(pTo);
  51815. }
  51816. }
  51817. }
  51818. /*
  51819. ** This routine redistributes cells on the iParentIdx'th child of pParent
  51820. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  51821. ** same amount of free space. Usually a single sibling on either side of the
  51822. ** page are used in the balancing, though both siblings might come from one
  51823. ** side if the page is the first or last child of its parent. If the page
  51824. ** has fewer than 2 siblings (something which can only happen if the page
  51825. ** is a root page or a child of a root page) then all available siblings
  51826. ** participate in the balancing.
  51827. **
  51828. ** The number of siblings of the page might be increased or decreased by
  51829. ** one or two in an effort to keep pages nearly full but not over full.
  51830. **
  51831. ** Note that when this routine is called, some of the cells on the page
  51832. ** might not actually be stored in MemPage.aData[]. This can happen
  51833. ** if the page is overfull. This routine ensures that all cells allocated
  51834. ** to the page and its siblings fit into MemPage.aData[] before returning.
  51835. **
  51836. ** In the course of balancing the page and its siblings, cells may be
  51837. ** inserted into or removed from the parent page (pParent). Doing so
  51838. ** may cause the parent page to become overfull or underfull. If this
  51839. ** happens, it is the responsibility of the caller to invoke the correct
  51840. ** balancing routine to fix this problem (see the balance() routine).
  51841. **
  51842. ** If this routine fails for any reason, it might leave the database
  51843. ** in a corrupted state. So if this routine fails, the database should
  51844. ** be rolled back.
  51845. **
  51846. ** The third argument to this function, aOvflSpace, is a pointer to a
  51847. ** buffer big enough to hold one page. If while inserting cells into the parent
  51848. ** page (pParent) the parent page becomes overfull, this buffer is
  51849. ** used to store the parent's overflow cells. Because this function inserts
  51850. ** a maximum of four divider cells into the parent page, and the maximum
  51851. ** size of a cell stored within an internal node is always less than 1/4
  51852. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  51853. ** enough for all overflow cells.
  51854. **
  51855. ** If aOvflSpace is set to a null pointer, this function returns
  51856. ** SQLITE_NOMEM.
  51857. */
  51858. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  51859. #pragma optimize("", off)
  51860. #endif
  51861. static int balance_nonroot(
  51862. MemPage *pParent, /* Parent page of siblings being balanced */
  51863. int iParentIdx, /* Index of "the page" in pParent */
  51864. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  51865. int isRoot, /* True if pParent is a root-page */
  51866. int bBulk /* True if this call is part of a bulk load */
  51867. ){
  51868. BtShared *pBt; /* The whole database */
  51869. int nCell = 0; /* Number of cells in apCell[] */
  51870. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  51871. int nNew = 0; /* Number of pages in apNew[] */
  51872. int nOld; /* Number of pages in apOld[] */
  51873. int i, j, k; /* Loop counters */
  51874. int nxDiv; /* Next divider slot in pParent->aCell[] */
  51875. int rc = SQLITE_OK; /* The return code */
  51876. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  51877. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  51878. int usableSpace; /* Bytes in pPage beyond the header */
  51879. int pageFlags; /* Value of pPage->aData[0] */
  51880. int subtotal; /* Subtotal of bytes in cells on one page */
  51881. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  51882. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  51883. int szScratch; /* Size of scratch memory requested */
  51884. MemPage *apOld[NB]; /* pPage and up to two siblings */
  51885. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  51886. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  51887. u8 *pRight; /* Location in parent of right-sibling pointer */
  51888. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  51889. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  51890. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  51891. u8 **apCell = 0; /* All cells begin balanced */
  51892. u16 *szCell; /* Local size of all cells in apCell[] */
  51893. u8 *aSpace1; /* Space for copies of dividers cells */
  51894. Pgno pgno; /* Temp var to store a page number in */
  51895. pBt = pParent->pBt;
  51896. assert( sqlite3_mutex_held(pBt->mutex) );
  51897. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  51898. #if 0
  51899. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  51900. #endif
  51901. /* At this point pParent may have at most one overflow cell. And if
  51902. ** this overflow cell is present, it must be the cell with
  51903. ** index iParentIdx. This scenario comes about when this function
  51904. ** is called (indirectly) from sqlite3BtreeDelete().
  51905. */
  51906. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  51907. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  51908. if( !aOvflSpace ){
  51909. return SQLITE_NOMEM;
  51910. }
  51911. /* Find the sibling pages to balance. Also locate the cells in pParent
  51912. ** that divide the siblings. An attempt is made to find NN siblings on
  51913. ** either side of pPage. More siblings are taken from one side, however,
  51914. ** if there are fewer than NN siblings on the other side. If pParent
  51915. ** has NB or fewer children then all children of pParent are taken.
  51916. **
  51917. ** This loop also drops the divider cells from the parent page. This
  51918. ** way, the remainder of the function does not have to deal with any
  51919. ** overflow cells in the parent page, since if any existed they will
  51920. ** have already been removed.
  51921. */
  51922. i = pParent->nOverflow + pParent->nCell;
  51923. if( i<2 ){
  51924. nxDiv = 0;
  51925. }else{
  51926. assert( bBulk==0 || bBulk==1 );
  51927. if( iParentIdx==0 ){
  51928. nxDiv = 0;
  51929. }else if( iParentIdx==i ){
  51930. nxDiv = i-2+bBulk;
  51931. }else{
  51932. assert( bBulk==0 );
  51933. nxDiv = iParentIdx-1;
  51934. }
  51935. i = 2-bBulk;
  51936. }
  51937. nOld = i+1;
  51938. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  51939. pRight = &pParent->aData[pParent->hdrOffset+8];
  51940. }else{
  51941. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  51942. }
  51943. pgno = get4byte(pRight);
  51944. while( 1 ){
  51945. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  51946. if( rc ){
  51947. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  51948. goto balance_cleanup;
  51949. }
  51950. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  51951. if( (i--)==0 ) break;
  51952. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  51953. apDiv[i] = pParent->apOvfl[0];
  51954. pgno = get4byte(apDiv[i]);
  51955. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  51956. pParent->nOverflow = 0;
  51957. }else{
  51958. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  51959. pgno = get4byte(apDiv[i]);
  51960. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  51961. /* Drop the cell from the parent page. apDiv[i] still points to
  51962. ** the cell within the parent, even though it has been dropped.
  51963. ** This is safe because dropping a cell only overwrites the first
  51964. ** four bytes of it, and this function does not need the first
  51965. ** four bytes of the divider cell. So the pointer is safe to use
  51966. ** later on.
  51967. **
  51968. ** But not if we are in secure-delete mode. In secure-delete mode,
  51969. ** the dropCell() routine will overwrite the entire cell with zeroes.
  51970. ** In this case, temporarily copy the cell into the aOvflSpace[]
  51971. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  51972. ** is allocated. */
  51973. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  51974. int iOff;
  51975. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  51976. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  51977. rc = SQLITE_CORRUPT_BKPT;
  51978. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  51979. goto balance_cleanup;
  51980. }else{
  51981. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  51982. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  51983. }
  51984. }
  51985. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  51986. }
  51987. }
  51988. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  51989. ** alignment */
  51990. nMaxCells = (nMaxCells + 3)&~3;
  51991. /*
  51992. ** Allocate space for memory structures
  51993. */
  51994. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  51995. szScratch =
  51996. nMaxCells*sizeof(u8*) /* apCell */
  51997. + nMaxCells*sizeof(u16) /* szCell */
  51998. + pBt->pageSize /* aSpace1 */
  51999. + k*nOld; /* Page copies (apCopy) */
  52000. apCell = sqlite3ScratchMalloc( szScratch );
  52001. if( apCell==0 ){
  52002. rc = SQLITE_NOMEM;
  52003. goto balance_cleanup;
  52004. }
  52005. szCell = (u16*)&apCell[nMaxCells];
  52006. aSpace1 = (u8*)&szCell[nMaxCells];
  52007. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  52008. /*
  52009. ** Load pointers to all cells on sibling pages and the divider cells
  52010. ** into the local apCell[] array. Make copies of the divider cells
  52011. ** into space obtained from aSpace1[] and remove the divider cells
  52012. ** from pParent.
  52013. **
  52014. ** If the siblings are on leaf pages, then the child pointers of the
  52015. ** divider cells are stripped from the cells before they are copied
  52016. ** into aSpace1[]. In this way, all cells in apCell[] are without
  52017. ** child pointers. If siblings are not leaves, then all cell in
  52018. ** apCell[] include child pointers. Either way, all cells in apCell[]
  52019. ** are alike.
  52020. **
  52021. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  52022. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  52023. */
  52024. leafCorrection = apOld[0]->leaf*4;
  52025. leafData = apOld[0]->hasData;
  52026. for(i=0; i<nOld; i++){
  52027. int limit;
  52028. /* Before doing anything else, take a copy of the i'th original sibling
  52029. ** The rest of this function will use data from the copies rather
  52030. ** that the original pages since the original pages will be in the
  52031. ** process of being overwritten. */
  52032. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  52033. memcpy(pOld, apOld[i], sizeof(MemPage));
  52034. pOld->aData = (void*)&pOld[1];
  52035. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  52036. limit = pOld->nCell+pOld->nOverflow;
  52037. if( pOld->nOverflow>0 ){
  52038. for(j=0; j<limit; j++){
  52039. assert( nCell<nMaxCells );
  52040. apCell[nCell] = findOverflowCell(pOld, j);
  52041. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  52042. nCell++;
  52043. }
  52044. }else{
  52045. u8 *aData = pOld->aData;
  52046. u16 maskPage = pOld->maskPage;
  52047. u16 cellOffset = pOld->cellOffset;
  52048. for(j=0; j<limit; j++){
  52049. assert( nCell<nMaxCells );
  52050. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  52051. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  52052. nCell++;
  52053. }
  52054. }
  52055. if( i<nOld-1 && !leafData){
  52056. u16 sz = (u16)szNew[i];
  52057. u8 *pTemp;
  52058. assert( nCell<nMaxCells );
  52059. szCell[nCell] = sz;
  52060. pTemp = &aSpace1[iSpace1];
  52061. iSpace1 += sz;
  52062. assert( sz<=pBt->maxLocal+23 );
  52063. assert( iSpace1 <= (int)pBt->pageSize );
  52064. memcpy(pTemp, apDiv[i], sz);
  52065. apCell[nCell] = pTemp+leafCorrection;
  52066. assert( leafCorrection==0 || leafCorrection==4 );
  52067. szCell[nCell] = szCell[nCell] - leafCorrection;
  52068. if( !pOld->leaf ){
  52069. assert( leafCorrection==0 );
  52070. assert( pOld->hdrOffset==0 );
  52071. /* The right pointer of the child page pOld becomes the left
  52072. ** pointer of the divider cell */
  52073. memcpy(apCell[nCell], &pOld->aData[8], 4);
  52074. }else{
  52075. assert( leafCorrection==4 );
  52076. if( szCell[nCell]<4 ){
  52077. /* Do not allow any cells smaller than 4 bytes. */
  52078. szCell[nCell] = 4;
  52079. }
  52080. }
  52081. nCell++;
  52082. }
  52083. }
  52084. /*
  52085. ** Figure out the number of pages needed to hold all nCell cells.
  52086. ** Store this number in "k". Also compute szNew[] which is the total
  52087. ** size of all cells on the i-th page and cntNew[] which is the index
  52088. ** in apCell[] of the cell that divides page i from page i+1.
  52089. ** cntNew[k] should equal nCell.
  52090. **
  52091. ** Values computed by this block:
  52092. **
  52093. ** k: The total number of sibling pages
  52094. ** szNew[i]: Spaced used on the i-th sibling page.
  52095. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  52096. ** the right of the i-th sibling page.
  52097. ** usableSpace: Number of bytes of space available on each sibling.
  52098. **
  52099. */
  52100. usableSpace = pBt->usableSize - 12 + leafCorrection;
  52101. for(subtotal=k=i=0; i<nCell; i++){
  52102. assert( i<nMaxCells );
  52103. subtotal += szCell[i] + 2;
  52104. if( subtotal > usableSpace ){
  52105. szNew[k] = subtotal - szCell[i];
  52106. cntNew[k] = i;
  52107. if( leafData ){ i--; }
  52108. subtotal = 0;
  52109. k++;
  52110. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  52111. }
  52112. }
  52113. szNew[k] = subtotal;
  52114. cntNew[k] = nCell;
  52115. k++;
  52116. /*
  52117. ** The packing computed by the previous block is biased toward the siblings
  52118. ** on the left side. The left siblings are always nearly full, while the
  52119. ** right-most sibling might be nearly empty. This block of code attempts
  52120. ** to adjust the packing of siblings to get a better balance.
  52121. **
  52122. ** This adjustment is more than an optimization. The packing above might
  52123. ** be so out of balance as to be illegal. For example, the right-most
  52124. ** sibling might be completely empty. This adjustment is not optional.
  52125. */
  52126. for(i=k-1; i>0; i--){
  52127. int szRight = szNew[i]; /* Size of sibling on the right */
  52128. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  52129. int r; /* Index of right-most cell in left sibling */
  52130. int d; /* Index of first cell to the left of right sibling */
  52131. r = cntNew[i-1] - 1;
  52132. d = r + 1 - leafData;
  52133. assert( d<nMaxCells );
  52134. assert( r<nMaxCells );
  52135. while( szRight==0
  52136. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  52137. ){
  52138. szRight += szCell[d] + 2;
  52139. szLeft -= szCell[r] + 2;
  52140. cntNew[i-1]--;
  52141. r = cntNew[i-1] - 1;
  52142. d = r + 1 - leafData;
  52143. }
  52144. szNew[i] = szRight;
  52145. szNew[i-1] = szLeft;
  52146. }
  52147. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  52148. ** a virtual root page. A virtual root page is when the real root
  52149. ** page is page 1 and we are the only child of that page.
  52150. **
  52151. ** UPDATE: The assert() below is not necessarily true if the database
  52152. ** file is corrupt. The corruption will be detected and reported later
  52153. ** in this procedure so there is no need to act upon it now.
  52154. */
  52155. #if 0
  52156. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  52157. #endif
  52158. TRACE(("BALANCE: old: %d %d %d ",
  52159. apOld[0]->pgno,
  52160. nOld>=2 ? apOld[1]->pgno : 0,
  52161. nOld>=3 ? apOld[2]->pgno : 0
  52162. ));
  52163. /*
  52164. ** Allocate k new pages. Reuse old pages where possible.
  52165. */
  52166. if( apOld[0]->pgno<=1 ){
  52167. rc = SQLITE_CORRUPT_BKPT;
  52168. goto balance_cleanup;
  52169. }
  52170. pageFlags = apOld[0]->aData[0];
  52171. for(i=0; i<k; i++){
  52172. MemPage *pNew;
  52173. if( i<nOld ){
  52174. pNew = apNew[i] = apOld[i];
  52175. apOld[i] = 0;
  52176. rc = sqlite3PagerWrite(pNew->pDbPage);
  52177. nNew++;
  52178. if( rc ) goto balance_cleanup;
  52179. }else{
  52180. assert( i>0 );
  52181. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  52182. if( rc ) goto balance_cleanup;
  52183. apNew[i] = pNew;
  52184. nNew++;
  52185. /* Set the pointer-map entry for the new sibling page. */
  52186. if( ISAUTOVACUUM ){
  52187. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  52188. if( rc!=SQLITE_OK ){
  52189. goto balance_cleanup;
  52190. }
  52191. }
  52192. }
  52193. }
  52194. /* Free any old pages that were not reused as new pages.
  52195. */
  52196. while( i<nOld ){
  52197. freePage(apOld[i], &rc);
  52198. if( rc ) goto balance_cleanup;
  52199. releasePage(apOld[i]);
  52200. apOld[i] = 0;
  52201. i++;
  52202. }
  52203. /*
  52204. ** Put the new pages in accending order. This helps to
  52205. ** keep entries in the disk file in order so that a scan
  52206. ** of the table is a linear scan through the file. That
  52207. ** in turn helps the operating system to deliver pages
  52208. ** from the disk more rapidly.
  52209. **
  52210. ** An O(n^2) insertion sort algorithm is used, but since
  52211. ** n is never more than NB (a small constant), that should
  52212. ** not be a problem.
  52213. **
  52214. ** When NB==3, this one optimization makes the database
  52215. ** about 25% faster for large insertions and deletions.
  52216. */
  52217. for(i=0; i<k-1; i++){
  52218. int minV = apNew[i]->pgno;
  52219. int minI = i;
  52220. for(j=i+1; j<k; j++){
  52221. if( apNew[j]->pgno<(unsigned)minV ){
  52222. minI = j;
  52223. minV = apNew[j]->pgno;
  52224. }
  52225. }
  52226. if( minI>i ){
  52227. MemPage *pT;
  52228. pT = apNew[i];
  52229. apNew[i] = apNew[minI];
  52230. apNew[minI] = pT;
  52231. }
  52232. }
  52233. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  52234. apNew[0]->pgno, szNew[0],
  52235. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  52236. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  52237. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  52238. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  52239. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52240. put4byte(pRight, apNew[nNew-1]->pgno);
  52241. /*
  52242. ** Evenly distribute the data in apCell[] across the new pages.
  52243. ** Insert divider cells into pParent as necessary.
  52244. */
  52245. j = 0;
  52246. for(i=0; i<nNew; i++){
  52247. /* Assemble the new sibling page. */
  52248. MemPage *pNew = apNew[i];
  52249. assert( j<nMaxCells );
  52250. zeroPage(pNew, pageFlags);
  52251. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  52252. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  52253. assert( pNew->nOverflow==0 );
  52254. j = cntNew[i];
  52255. /* If the sibling page assembled above was not the right-most sibling,
  52256. ** insert a divider cell into the parent page.
  52257. */
  52258. assert( i<nNew-1 || j==nCell );
  52259. if( j<nCell ){
  52260. u8 *pCell;
  52261. u8 *pTemp;
  52262. int sz;
  52263. assert( j<nMaxCells );
  52264. pCell = apCell[j];
  52265. sz = szCell[j] + leafCorrection;
  52266. pTemp = &aOvflSpace[iOvflSpace];
  52267. if( !pNew->leaf ){
  52268. memcpy(&pNew->aData[8], pCell, 4);
  52269. }else if( leafData ){
  52270. /* If the tree is a leaf-data tree, and the siblings are leaves,
  52271. ** then there is no divider cell in apCell[]. Instead, the divider
  52272. ** cell consists of the integer key for the right-most cell of
  52273. ** the sibling-page assembled above only.
  52274. */
  52275. CellInfo info;
  52276. j--;
  52277. btreeParseCellPtr(pNew, apCell[j], &info);
  52278. pCell = pTemp;
  52279. sz = 4 + putVarint(&pCell[4], info.nKey);
  52280. pTemp = 0;
  52281. }else{
  52282. pCell -= 4;
  52283. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  52284. ** previously stored on a leaf node, and its reported size was 4
  52285. ** bytes, then it may actually be smaller than this
  52286. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  52287. ** any cell). But it is important to pass the correct size to
  52288. ** insertCell(), so reparse the cell now.
  52289. **
  52290. ** Note that this can never happen in an SQLite data file, as all
  52291. ** cells are at least 4 bytes. It only happens in b-trees used
  52292. ** to evaluate "IN (SELECT ...)" and similar clauses.
  52293. */
  52294. if( szCell[j]==4 ){
  52295. assert(leafCorrection==4);
  52296. sz = cellSizePtr(pParent, pCell);
  52297. }
  52298. }
  52299. iOvflSpace += sz;
  52300. assert( sz<=pBt->maxLocal+23 );
  52301. assert( iOvflSpace <= (int)pBt->pageSize );
  52302. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  52303. if( rc!=SQLITE_OK ) goto balance_cleanup;
  52304. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  52305. j++;
  52306. nxDiv++;
  52307. }
  52308. }
  52309. assert( j==nCell );
  52310. assert( nOld>0 );
  52311. assert( nNew>0 );
  52312. if( (pageFlags & PTF_LEAF)==0 ){
  52313. u8 *zChild = &apCopy[nOld-1]->aData[8];
  52314. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  52315. }
  52316. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  52317. /* The root page of the b-tree now contains no cells. The only sibling
  52318. ** page is the right-child of the parent. Copy the contents of the
  52319. ** child page into the parent, decreasing the overall height of the
  52320. ** b-tree structure by one. This is described as the "balance-shallower"
  52321. ** sub-algorithm in some documentation.
  52322. **
  52323. ** If this is an auto-vacuum database, the call to copyNodeContent()
  52324. ** sets all pointer-map entries corresponding to database image pages
  52325. ** for which the pointer is stored within the content being copied.
  52326. **
  52327. ** The second assert below verifies that the child page is defragmented
  52328. ** (it must be, as it was just reconstructed using assemblePage()). This
  52329. ** is important if the parent page happens to be page 1 of the database
  52330. ** image. */
  52331. assert( nNew==1 );
  52332. assert( apNew[0]->nFree ==
  52333. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  52334. );
  52335. copyNodeContent(apNew[0], pParent, &rc);
  52336. freePage(apNew[0], &rc);
  52337. }else if( ISAUTOVACUUM ){
  52338. /* Fix the pointer-map entries for all the cells that were shifted around.
  52339. ** There are several different types of pointer-map entries that need to
  52340. ** be dealt with by this routine. Some of these have been set already, but
  52341. ** many have not. The following is a summary:
  52342. **
  52343. ** 1) The entries associated with new sibling pages that were not
  52344. ** siblings when this function was called. These have already
  52345. ** been set. We don't need to worry about old siblings that were
  52346. ** moved to the free-list - the freePage() code has taken care
  52347. ** of those.
  52348. **
  52349. ** 2) The pointer-map entries associated with the first overflow
  52350. ** page in any overflow chains used by new divider cells. These
  52351. ** have also already been taken care of by the insertCell() code.
  52352. **
  52353. ** 3) If the sibling pages are not leaves, then the child pages of
  52354. ** cells stored on the sibling pages may need to be updated.
  52355. **
  52356. ** 4) If the sibling pages are not internal intkey nodes, then any
  52357. ** overflow pages used by these cells may need to be updated
  52358. ** (internal intkey nodes never contain pointers to overflow pages).
  52359. **
  52360. ** 5) If the sibling pages are not leaves, then the pointer-map
  52361. ** entries for the right-child pages of each sibling may need
  52362. ** to be updated.
  52363. **
  52364. ** Cases 1 and 2 are dealt with above by other code. The next
  52365. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  52366. ** setting a pointer map entry is a relatively expensive operation, this
  52367. ** code only sets pointer map entries for child or overflow pages that have
  52368. ** actually moved between pages. */
  52369. MemPage *pNew = apNew[0];
  52370. MemPage *pOld = apCopy[0];
  52371. int nOverflow = pOld->nOverflow;
  52372. int iNextOld = pOld->nCell + nOverflow;
  52373. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  52374. j = 0; /* Current 'old' sibling page */
  52375. k = 0; /* Current 'new' sibling page */
  52376. for(i=0; i<nCell; i++){
  52377. int isDivider = 0;
  52378. while( i==iNextOld ){
  52379. /* Cell i is the cell immediately following the last cell on old
  52380. ** sibling page j. If the siblings are not leaf pages of an
  52381. ** intkey b-tree, then cell i was a divider cell. */
  52382. assert( j+1 < ArraySize(apCopy) );
  52383. assert( j+1 < nOld );
  52384. pOld = apCopy[++j];
  52385. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  52386. if( pOld->nOverflow ){
  52387. nOverflow = pOld->nOverflow;
  52388. iOverflow = i + !leafData + pOld->aiOvfl[0];
  52389. }
  52390. isDivider = !leafData;
  52391. }
  52392. assert(nOverflow>0 || iOverflow<i );
  52393. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  52394. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  52395. if( i==iOverflow ){
  52396. isDivider = 1;
  52397. if( (--nOverflow)>0 ){
  52398. iOverflow++;
  52399. }
  52400. }
  52401. if( i==cntNew[k] ){
  52402. /* Cell i is the cell immediately following the last cell on new
  52403. ** sibling page k. If the siblings are not leaf pages of an
  52404. ** intkey b-tree, then cell i is a divider cell. */
  52405. pNew = apNew[++k];
  52406. if( !leafData ) continue;
  52407. }
  52408. assert( j<nOld );
  52409. assert( k<nNew );
  52410. /* If the cell was originally divider cell (and is not now) or
  52411. ** an overflow cell, or if the cell was located on a different sibling
  52412. ** page before the balancing, then the pointer map entries associated
  52413. ** with any child or overflow pages need to be updated. */
  52414. if( isDivider || pOld->pgno!=pNew->pgno ){
  52415. if( !leafCorrection ){
  52416. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  52417. }
  52418. if( szCell[i]>pNew->minLocal ){
  52419. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  52420. }
  52421. }
  52422. }
  52423. if( !leafCorrection ){
  52424. for(i=0; i<nNew; i++){
  52425. u32 key = get4byte(&apNew[i]->aData[8]);
  52426. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  52427. }
  52428. }
  52429. #if 0
  52430. /* The ptrmapCheckPages() contains assert() statements that verify that
  52431. ** all pointer map pages are set correctly. This is helpful while
  52432. ** debugging. This is usually disabled because a corrupt database may
  52433. ** cause an assert() statement to fail. */
  52434. ptrmapCheckPages(apNew, nNew);
  52435. ptrmapCheckPages(&pParent, 1);
  52436. #endif
  52437. }
  52438. assert( pParent->isInit );
  52439. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  52440. nOld, nNew, nCell));
  52441. /*
  52442. ** Cleanup before returning.
  52443. */
  52444. balance_cleanup:
  52445. sqlite3ScratchFree(apCell);
  52446. for(i=0; i<nOld; i++){
  52447. releasePage(apOld[i]);
  52448. }
  52449. for(i=0; i<nNew; i++){
  52450. releasePage(apNew[i]);
  52451. }
  52452. return rc;
  52453. }
  52454. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  52455. #pragma optimize("", on)
  52456. #endif
  52457. /*
  52458. ** This function is called when the root page of a b-tree structure is
  52459. ** overfull (has one or more overflow pages).
  52460. **
  52461. ** A new child page is allocated and the contents of the current root
  52462. ** page, including overflow cells, are copied into the child. The root
  52463. ** page is then overwritten to make it an empty page with the right-child
  52464. ** pointer pointing to the new page.
  52465. **
  52466. ** Before returning, all pointer-map entries corresponding to pages
  52467. ** that the new child-page now contains pointers to are updated. The
  52468. ** entry corresponding to the new right-child pointer of the root
  52469. ** page is also updated.
  52470. **
  52471. ** If successful, *ppChild is set to contain a reference to the child
  52472. ** page and SQLITE_OK is returned. In this case the caller is required
  52473. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  52474. ** an error code is returned and *ppChild is set to 0.
  52475. */
  52476. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  52477. int rc; /* Return value from subprocedures */
  52478. MemPage *pChild = 0; /* Pointer to a new child page */
  52479. Pgno pgnoChild = 0; /* Page number of the new child page */
  52480. BtShared *pBt = pRoot->pBt; /* The BTree */
  52481. assert( pRoot->nOverflow>0 );
  52482. assert( sqlite3_mutex_held(pBt->mutex) );
  52483. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  52484. ** page that will become the new right-child of pPage. Copy the contents
  52485. ** of the node stored on pRoot into the new child page.
  52486. */
  52487. rc = sqlite3PagerWrite(pRoot->pDbPage);
  52488. if( rc==SQLITE_OK ){
  52489. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  52490. copyNodeContent(pRoot, pChild, &rc);
  52491. if( ISAUTOVACUUM ){
  52492. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  52493. }
  52494. }
  52495. if( rc ){
  52496. *ppChild = 0;
  52497. releasePage(pChild);
  52498. return rc;
  52499. }
  52500. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  52501. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  52502. assert( pChild->nCell==pRoot->nCell );
  52503. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  52504. /* Copy the overflow cells from pRoot to pChild */
  52505. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  52506. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  52507. memcpy(pChild->apOvfl, pRoot->apOvfl,
  52508. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  52509. pChild->nOverflow = pRoot->nOverflow;
  52510. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  52511. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  52512. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  52513. *ppChild = pChild;
  52514. return SQLITE_OK;
  52515. }
  52516. /*
  52517. ** The page that pCur currently points to has just been modified in
  52518. ** some way. This function figures out if this modification means the
  52519. ** tree needs to be balanced, and if so calls the appropriate balancing
  52520. ** routine. Balancing routines are:
  52521. **
  52522. ** balance_quick()
  52523. ** balance_deeper()
  52524. ** balance_nonroot()
  52525. */
  52526. static int balance(BtCursor *pCur){
  52527. int rc = SQLITE_OK;
  52528. const int nMin = pCur->pBt->usableSize * 2 / 3;
  52529. u8 aBalanceQuickSpace[13];
  52530. u8 *pFree = 0;
  52531. TESTONLY( int balance_quick_called = 0 );
  52532. TESTONLY( int balance_deeper_called = 0 );
  52533. do {
  52534. int iPage = pCur->iPage;
  52535. MemPage *pPage = pCur->apPage[iPage];
  52536. if( iPage==0 ){
  52537. if( pPage->nOverflow ){
  52538. /* The root page of the b-tree is overfull. In this case call the
  52539. ** balance_deeper() function to create a new child for the root-page
  52540. ** and copy the current contents of the root-page to it. The
  52541. ** next iteration of the do-loop will balance the child page.
  52542. */
  52543. assert( (balance_deeper_called++)==0 );
  52544. rc = balance_deeper(pPage, &pCur->apPage[1]);
  52545. if( rc==SQLITE_OK ){
  52546. pCur->iPage = 1;
  52547. pCur->aiIdx[0] = 0;
  52548. pCur->aiIdx[1] = 0;
  52549. assert( pCur->apPage[1]->nOverflow );
  52550. }
  52551. }else{
  52552. break;
  52553. }
  52554. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  52555. break;
  52556. }else{
  52557. MemPage * const pParent = pCur->apPage[iPage-1];
  52558. int const iIdx = pCur->aiIdx[iPage-1];
  52559. rc = sqlite3PagerWrite(pParent->pDbPage);
  52560. if( rc==SQLITE_OK ){
  52561. #ifndef SQLITE_OMIT_QUICKBALANCE
  52562. if( pPage->hasData
  52563. && pPage->nOverflow==1
  52564. && pPage->aiOvfl[0]==pPage->nCell
  52565. && pParent->pgno!=1
  52566. && pParent->nCell==iIdx
  52567. ){
  52568. /* Call balance_quick() to create a new sibling of pPage on which
  52569. ** to store the overflow cell. balance_quick() inserts a new cell
  52570. ** into pParent, which may cause pParent overflow. If this
  52571. ** happens, the next interation of the do-loop will balance pParent
  52572. ** use either balance_nonroot() or balance_deeper(). Until this
  52573. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  52574. ** buffer.
  52575. **
  52576. ** The purpose of the following assert() is to check that only a
  52577. ** single call to balance_quick() is made for each call to this
  52578. ** function. If this were not verified, a subtle bug involving reuse
  52579. ** of the aBalanceQuickSpace[] might sneak in.
  52580. */
  52581. assert( (balance_quick_called++)==0 );
  52582. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  52583. }else
  52584. #endif
  52585. {
  52586. /* In this case, call balance_nonroot() to redistribute cells
  52587. ** between pPage and up to 2 of its sibling pages. This involves
  52588. ** modifying the contents of pParent, which may cause pParent to
  52589. ** become overfull or underfull. The next iteration of the do-loop
  52590. ** will balance the parent page to correct this.
  52591. **
  52592. ** If the parent page becomes overfull, the overflow cell or cells
  52593. ** are stored in the pSpace buffer allocated immediately below.
  52594. ** A subsequent iteration of the do-loop will deal with this by
  52595. ** calling balance_nonroot() (balance_deeper() may be called first,
  52596. ** but it doesn't deal with overflow cells - just moves them to a
  52597. ** different page). Once this subsequent call to balance_nonroot()
  52598. ** has completed, it is safe to release the pSpace buffer used by
  52599. ** the previous call, as the overflow cell data will have been
  52600. ** copied either into the body of a database page or into the new
  52601. ** pSpace buffer passed to the latter call to balance_nonroot().
  52602. */
  52603. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  52604. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  52605. if( pFree ){
  52606. /* If pFree is not NULL, it points to the pSpace buffer used
  52607. ** by a previous call to balance_nonroot(). Its contents are
  52608. ** now stored either on real database pages or within the
  52609. ** new pSpace buffer, so it may be safely freed here. */
  52610. sqlite3PageFree(pFree);
  52611. }
  52612. /* The pSpace buffer will be freed after the next call to
  52613. ** balance_nonroot(), or just before this function returns, whichever
  52614. ** comes first. */
  52615. pFree = pSpace;
  52616. }
  52617. }
  52618. pPage->nOverflow = 0;
  52619. /* The next iteration of the do-loop balances the parent page. */
  52620. releasePage(pPage);
  52621. pCur->iPage--;
  52622. }
  52623. }while( rc==SQLITE_OK );
  52624. if( pFree ){
  52625. sqlite3PageFree(pFree);
  52626. }
  52627. return rc;
  52628. }
  52629. /*
  52630. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  52631. ** and the data is given by (pData,nData). The cursor is used only to
  52632. ** define what table the record should be inserted into. The cursor
  52633. ** is left pointing at a random location.
  52634. **
  52635. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  52636. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  52637. **
  52638. ** If the seekResult parameter is non-zero, then a successful call to
  52639. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  52640. ** been performed. seekResult is the search result returned (a negative
  52641. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  52642. ** a positive value if pCur points at an etry that is larger than
  52643. ** (pKey, nKey)).
  52644. **
  52645. ** If the seekResult parameter is non-zero, then the caller guarantees that
  52646. ** cursor pCur is pointing at the existing copy of a row that is to be
  52647. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  52648. ** point to any entry or to no entry at all and so this function has to seek
  52649. ** the cursor before the new key can be inserted.
  52650. */
  52651. SQLITE_PRIVATE int sqlite3BtreeInsert(
  52652. BtCursor *pCur, /* Insert data into the table of this cursor */
  52653. const void *pKey, i64 nKey, /* The key of the new record */
  52654. const void *pData, int nData, /* The data of the new record */
  52655. int nZero, /* Number of extra 0 bytes to append to data */
  52656. int appendBias, /* True if this is likely an append */
  52657. int seekResult /* Result of prior MovetoUnpacked() call */
  52658. ){
  52659. int rc;
  52660. int loc = seekResult; /* -1: before desired location +1: after */
  52661. int szNew = 0;
  52662. int idx;
  52663. MemPage *pPage;
  52664. Btree *p = pCur->pBtree;
  52665. BtShared *pBt = p->pBt;
  52666. unsigned char *oldCell;
  52667. unsigned char *newCell = 0;
  52668. if( pCur->eState==CURSOR_FAULT ){
  52669. assert( pCur->skipNext!=SQLITE_OK );
  52670. return pCur->skipNext;
  52671. }
  52672. assert( cursorHoldsMutex(pCur) );
  52673. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  52674. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52675. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  52676. /* Assert that the caller has been consistent. If this cursor was opened
  52677. ** expecting an index b-tree, then the caller should be inserting blob
  52678. ** keys with no associated data. If the cursor was opened expecting an
  52679. ** intkey table, the caller should be inserting integer keys with a
  52680. ** blob of associated data. */
  52681. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  52682. /* Save the positions of any other cursors open on this table.
  52683. **
  52684. ** In some cases, the call to btreeMoveto() below is a no-op. For
  52685. ** example, when inserting data into a table with auto-generated integer
  52686. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  52687. ** integer key to use. It then calls this function to actually insert the
  52688. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  52689. ** that the cursor is already where it needs to be and returns without
  52690. ** doing any work. To avoid thwarting these optimizations, it is important
  52691. ** not to clear the cursor here.
  52692. */
  52693. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  52694. if( rc ) return rc;
  52695. /* If this is an insert into a table b-tree, invalidate any incrblob
  52696. ** cursors open on the row being replaced (assuming this is a replace
  52697. ** operation - if it is not, the following is a no-op). */
  52698. if( pCur->pKeyInfo==0 ){
  52699. invalidateIncrblobCursors(p, nKey, 0);
  52700. }
  52701. if( !loc ){
  52702. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  52703. if( rc ) return rc;
  52704. }
  52705. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  52706. pPage = pCur->apPage[pCur->iPage];
  52707. assert( pPage->intKey || nKey>=0 );
  52708. assert( pPage->leaf || !pPage->intKey );
  52709. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  52710. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  52711. loc==0 ? "overwrite" : "new entry"));
  52712. assert( pPage->isInit );
  52713. allocateTempSpace(pBt);
  52714. newCell = pBt->pTmpSpace;
  52715. if( newCell==0 ) return SQLITE_NOMEM;
  52716. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  52717. if( rc ) goto end_insert;
  52718. assert( szNew==cellSizePtr(pPage, newCell) );
  52719. assert( szNew <= MX_CELL_SIZE(pBt) );
  52720. idx = pCur->aiIdx[pCur->iPage];
  52721. if( loc==0 ){
  52722. u16 szOld;
  52723. assert( idx<pPage->nCell );
  52724. rc = sqlite3PagerWrite(pPage->pDbPage);
  52725. if( rc ){
  52726. goto end_insert;
  52727. }
  52728. oldCell = findCell(pPage, idx);
  52729. if( !pPage->leaf ){
  52730. memcpy(newCell, oldCell, 4);
  52731. }
  52732. szOld = cellSizePtr(pPage, oldCell);
  52733. rc = clearCell(pPage, oldCell);
  52734. dropCell(pPage, idx, szOld, &rc);
  52735. if( rc ) goto end_insert;
  52736. }else if( loc<0 && pPage->nCell>0 ){
  52737. assert( pPage->leaf );
  52738. idx = ++pCur->aiIdx[pCur->iPage];
  52739. }else{
  52740. assert( pPage->leaf );
  52741. }
  52742. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  52743. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  52744. /* If no error has occurred and pPage has an overflow cell, call balance()
  52745. ** to redistribute the cells within the tree. Since balance() may move
  52746. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  52747. ** variables.
  52748. **
  52749. ** Previous versions of SQLite called moveToRoot() to move the cursor
  52750. ** back to the root page as balance() used to invalidate the contents
  52751. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  52752. ** set the cursor state to "invalid". This makes common insert operations
  52753. ** slightly faster.
  52754. **
  52755. ** There is a subtle but important optimization here too. When inserting
  52756. ** multiple records into an intkey b-tree using a single cursor (as can
  52757. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  52758. ** is advantageous to leave the cursor pointing to the last entry in
  52759. ** the b-tree if possible. If the cursor is left pointing to the last
  52760. ** entry in the table, and the next row inserted has an integer key
  52761. ** larger than the largest existing key, it is possible to insert the
  52762. ** row without seeking the cursor. This can be a big performance boost.
  52763. */
  52764. pCur->info.nSize = 0;
  52765. pCur->validNKey = 0;
  52766. if( rc==SQLITE_OK && pPage->nOverflow ){
  52767. rc = balance(pCur);
  52768. /* Must make sure nOverflow is reset to zero even if the balance()
  52769. ** fails. Internal data structure corruption will result otherwise.
  52770. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  52771. ** from trying to save the current position of the cursor. */
  52772. pCur->apPage[pCur->iPage]->nOverflow = 0;
  52773. pCur->eState = CURSOR_INVALID;
  52774. }
  52775. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  52776. end_insert:
  52777. return rc;
  52778. }
  52779. /*
  52780. ** Delete the entry that the cursor is pointing to. The cursor
  52781. ** is left pointing at a arbitrary location.
  52782. */
  52783. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  52784. Btree *p = pCur->pBtree;
  52785. BtShared *pBt = p->pBt;
  52786. int rc; /* Return code */
  52787. MemPage *pPage; /* Page to delete cell from */
  52788. unsigned char *pCell; /* Pointer to cell to delete */
  52789. int iCellIdx; /* Index of cell to delete */
  52790. int iCellDepth; /* Depth of node containing pCell */
  52791. assert( cursorHoldsMutex(pCur) );
  52792. assert( pBt->inTransaction==TRANS_WRITE );
  52793. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52794. assert( pCur->wrFlag );
  52795. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  52796. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  52797. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  52798. || NEVER(pCur->eState!=CURSOR_VALID)
  52799. ){
  52800. return SQLITE_ERROR; /* Something has gone awry. */
  52801. }
  52802. iCellDepth = pCur->iPage;
  52803. iCellIdx = pCur->aiIdx[iCellDepth];
  52804. pPage = pCur->apPage[iCellDepth];
  52805. pCell = findCell(pPage, iCellIdx);
  52806. /* If the page containing the entry to delete is not a leaf page, move
  52807. ** the cursor to the largest entry in the tree that is smaller than
  52808. ** the entry being deleted. This cell will replace the cell being deleted
  52809. ** from the internal node. The 'previous' entry is used for this instead
  52810. ** of the 'next' entry, as the previous entry is always a part of the
  52811. ** sub-tree headed by the child page of the cell being deleted. This makes
  52812. ** balancing the tree following the delete operation easier. */
  52813. if( !pPage->leaf ){
  52814. int notUsed;
  52815. rc = sqlite3BtreePrevious(pCur, &notUsed);
  52816. if( rc ) return rc;
  52817. }
  52818. /* Save the positions of any other cursors open on this table before
  52819. ** making any modifications. Make the page containing the entry to be
  52820. ** deleted writable. Then free any overflow pages associated with the
  52821. ** entry and finally remove the cell itself from within the page.
  52822. */
  52823. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  52824. if( rc ) return rc;
  52825. /* If this is a delete operation to remove a row from a table b-tree,
  52826. ** invalidate any incrblob cursors open on the row being deleted. */
  52827. if( pCur->pKeyInfo==0 ){
  52828. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  52829. }
  52830. rc = sqlite3PagerWrite(pPage->pDbPage);
  52831. if( rc ) return rc;
  52832. rc = clearCell(pPage, pCell);
  52833. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  52834. if( rc ) return rc;
  52835. /* If the cell deleted was not located on a leaf page, then the cursor
  52836. ** is currently pointing to the largest entry in the sub-tree headed
  52837. ** by the child-page of the cell that was just deleted from an internal
  52838. ** node. The cell from the leaf node needs to be moved to the internal
  52839. ** node to replace the deleted cell. */
  52840. if( !pPage->leaf ){
  52841. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  52842. int nCell;
  52843. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  52844. unsigned char *pTmp;
  52845. pCell = findCell(pLeaf, pLeaf->nCell-1);
  52846. nCell = cellSizePtr(pLeaf, pCell);
  52847. assert( MX_CELL_SIZE(pBt) >= nCell );
  52848. allocateTempSpace(pBt);
  52849. pTmp = pBt->pTmpSpace;
  52850. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  52851. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  52852. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  52853. if( rc ) return rc;
  52854. }
  52855. /* Balance the tree. If the entry deleted was located on a leaf page,
  52856. ** then the cursor still points to that page. In this case the first
  52857. ** call to balance() repairs the tree, and the if(...) condition is
  52858. ** never true.
  52859. **
  52860. ** Otherwise, if the entry deleted was on an internal node page, then
  52861. ** pCur is pointing to the leaf page from which a cell was removed to
  52862. ** replace the cell deleted from the internal node. This is slightly
  52863. ** tricky as the leaf node may be underfull, and the internal node may
  52864. ** be either under or overfull. In this case run the balancing algorithm
  52865. ** on the leaf node first. If the balance proceeds far enough up the
  52866. ** tree that we can be sure that any problem in the internal node has
  52867. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  52868. ** walk the cursor up the tree to the internal node and balance it as
  52869. ** well. */
  52870. rc = balance(pCur);
  52871. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  52872. while( pCur->iPage>iCellDepth ){
  52873. releasePage(pCur->apPage[pCur->iPage--]);
  52874. }
  52875. rc = balance(pCur);
  52876. }
  52877. if( rc==SQLITE_OK ){
  52878. moveToRoot(pCur);
  52879. }
  52880. return rc;
  52881. }
  52882. /*
  52883. ** Create a new BTree table. Write into *piTable the page
  52884. ** number for the root page of the new table.
  52885. **
  52886. ** The type of type is determined by the flags parameter. Only the
  52887. ** following values of flags are currently in use. Other values for
  52888. ** flags might not work:
  52889. **
  52890. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  52891. ** BTREE_ZERODATA Used for SQL indices
  52892. */
  52893. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  52894. BtShared *pBt = p->pBt;
  52895. MemPage *pRoot;
  52896. Pgno pgnoRoot;
  52897. int rc;
  52898. int ptfFlags; /* Page-type flage for the root page of new table */
  52899. assert( sqlite3BtreeHoldsMutex(p) );
  52900. assert( pBt->inTransaction==TRANS_WRITE );
  52901. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52902. #ifdef SQLITE_OMIT_AUTOVACUUM
  52903. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  52904. if( rc ){
  52905. return rc;
  52906. }
  52907. #else
  52908. if( pBt->autoVacuum ){
  52909. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  52910. MemPage *pPageMove; /* The page to move to. */
  52911. /* Creating a new table may probably require moving an existing database
  52912. ** to make room for the new tables root page. In case this page turns
  52913. ** out to be an overflow page, delete all overflow page-map caches
  52914. ** held by open cursors.
  52915. */
  52916. invalidateAllOverflowCache(pBt);
  52917. /* Read the value of meta[3] from the database to determine where the
  52918. ** root page of the new table should go. meta[3] is the largest root-page
  52919. ** created so far, so the new root-page is (meta[3]+1).
  52920. */
  52921. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  52922. pgnoRoot++;
  52923. /* The new root-page may not be allocated on a pointer-map page, or the
  52924. ** PENDING_BYTE page.
  52925. */
  52926. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  52927. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  52928. pgnoRoot++;
  52929. }
  52930. assert( pgnoRoot>=3 );
  52931. /* Allocate a page. The page that currently resides at pgnoRoot will
  52932. ** be moved to the allocated page (unless the allocated page happens
  52933. ** to reside at pgnoRoot).
  52934. */
  52935. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  52936. if( rc!=SQLITE_OK ){
  52937. return rc;
  52938. }
  52939. if( pgnoMove!=pgnoRoot ){
  52940. /* pgnoRoot is the page that will be used for the root-page of
  52941. ** the new table (assuming an error did not occur). But we were
  52942. ** allocated pgnoMove. If required (i.e. if it was not allocated
  52943. ** by extending the file), the current page at position pgnoMove
  52944. ** is already journaled.
  52945. */
  52946. u8 eType = 0;
  52947. Pgno iPtrPage = 0;
  52948. /* Save the positions of any open cursors. This is required in
  52949. ** case they are holding a reference to an xFetch reference
  52950. ** corresponding to page pgnoRoot. */
  52951. rc = saveAllCursors(pBt, 0, 0);
  52952. releasePage(pPageMove);
  52953. if( rc!=SQLITE_OK ){
  52954. return rc;
  52955. }
  52956. /* Move the page currently at pgnoRoot to pgnoMove. */
  52957. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
  52958. if( rc!=SQLITE_OK ){
  52959. return rc;
  52960. }
  52961. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  52962. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  52963. rc = SQLITE_CORRUPT_BKPT;
  52964. }
  52965. if( rc!=SQLITE_OK ){
  52966. releasePage(pRoot);
  52967. return rc;
  52968. }
  52969. assert( eType!=PTRMAP_ROOTPAGE );
  52970. assert( eType!=PTRMAP_FREEPAGE );
  52971. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  52972. releasePage(pRoot);
  52973. /* Obtain the page at pgnoRoot */
  52974. if( rc!=SQLITE_OK ){
  52975. return rc;
  52976. }
  52977. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
  52978. if( rc!=SQLITE_OK ){
  52979. return rc;
  52980. }
  52981. rc = sqlite3PagerWrite(pRoot->pDbPage);
  52982. if( rc!=SQLITE_OK ){
  52983. releasePage(pRoot);
  52984. return rc;
  52985. }
  52986. }else{
  52987. pRoot = pPageMove;
  52988. }
  52989. /* Update the pointer-map and meta-data with the new root-page number. */
  52990. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  52991. if( rc ){
  52992. releasePage(pRoot);
  52993. return rc;
  52994. }
  52995. /* When the new root page was allocated, page 1 was made writable in
  52996. ** order either to increase the database filesize, or to decrement the
  52997. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  52998. */
  52999. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  53000. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  53001. if( NEVER(rc) ){
  53002. releasePage(pRoot);
  53003. return rc;
  53004. }
  53005. }else{
  53006. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  53007. if( rc ) return rc;
  53008. }
  53009. #endif
  53010. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  53011. if( createTabFlags & BTREE_INTKEY ){
  53012. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  53013. }else{
  53014. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  53015. }
  53016. zeroPage(pRoot, ptfFlags);
  53017. sqlite3PagerUnref(pRoot->pDbPage);
  53018. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  53019. *piTable = (int)pgnoRoot;
  53020. return SQLITE_OK;
  53021. }
  53022. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  53023. int rc;
  53024. sqlite3BtreeEnter(p);
  53025. rc = btreeCreateTable(p, piTable, flags);
  53026. sqlite3BtreeLeave(p);
  53027. return rc;
  53028. }
  53029. /*
  53030. ** Erase the given database page and all its children. Return
  53031. ** the page to the freelist.
  53032. */
  53033. static int clearDatabasePage(
  53034. BtShared *pBt, /* The BTree that contains the table */
  53035. Pgno pgno, /* Page number to clear */
  53036. int freePageFlag, /* Deallocate page if true */
  53037. int *pnChange /* Add number of Cells freed to this counter */
  53038. ){
  53039. MemPage *pPage;
  53040. int rc;
  53041. unsigned char *pCell;
  53042. int i;
  53043. assert( sqlite3_mutex_held(pBt->mutex) );
  53044. if( pgno>btreePagecount(pBt) ){
  53045. return SQLITE_CORRUPT_BKPT;
  53046. }
  53047. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  53048. if( rc ) return rc;
  53049. for(i=0; i<pPage->nCell; i++){
  53050. pCell = findCell(pPage, i);
  53051. if( !pPage->leaf ){
  53052. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  53053. if( rc ) goto cleardatabasepage_out;
  53054. }
  53055. rc = clearCell(pPage, pCell);
  53056. if( rc ) goto cleardatabasepage_out;
  53057. }
  53058. if( !pPage->leaf ){
  53059. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  53060. if( rc ) goto cleardatabasepage_out;
  53061. }else if( pnChange ){
  53062. assert( pPage->intKey );
  53063. *pnChange += pPage->nCell;
  53064. }
  53065. if( freePageFlag ){
  53066. freePage(pPage, &rc);
  53067. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  53068. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  53069. }
  53070. cleardatabasepage_out:
  53071. releasePage(pPage);
  53072. return rc;
  53073. }
  53074. /*
  53075. ** Delete all information from a single table in the database. iTable is
  53076. ** the page number of the root of the table. After this routine returns,
  53077. ** the root page is empty, but still exists.
  53078. **
  53079. ** This routine will fail with SQLITE_LOCKED if there are any open
  53080. ** read cursors on the table. Open write cursors are moved to the
  53081. ** root of the table.
  53082. **
  53083. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  53084. ** integer value pointed to by pnChange is incremented by the number of
  53085. ** entries in the table.
  53086. */
  53087. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  53088. int rc;
  53089. BtShared *pBt = p->pBt;
  53090. sqlite3BtreeEnter(p);
  53091. assert( p->inTrans==TRANS_WRITE );
  53092. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  53093. if( SQLITE_OK==rc ){
  53094. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  53095. ** is the root of a table b-tree - if it is not, the following call is
  53096. ** a no-op). */
  53097. invalidateIncrblobCursors(p, 0, 1);
  53098. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  53099. }
  53100. sqlite3BtreeLeave(p);
  53101. return rc;
  53102. }
  53103. /*
  53104. ** Erase all information in a table and add the root of the table to
  53105. ** the freelist. Except, the root of the principle table (the one on
  53106. ** page 1) is never added to the freelist.
  53107. **
  53108. ** This routine will fail with SQLITE_LOCKED if there are any open
  53109. ** cursors on the table.
  53110. **
  53111. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  53112. ** root page in the database file, then the last root page
  53113. ** in the database file is moved into the slot formerly occupied by
  53114. ** iTable and that last slot formerly occupied by the last root page
  53115. ** is added to the freelist instead of iTable. In this say, all
  53116. ** root pages are kept at the beginning of the database file, which
  53117. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  53118. ** page number that used to be the last root page in the file before
  53119. ** the move. If no page gets moved, *piMoved is set to 0.
  53120. ** The last root page is recorded in meta[3] and the value of
  53121. ** meta[3] is updated by this procedure.
  53122. */
  53123. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  53124. int rc;
  53125. MemPage *pPage = 0;
  53126. BtShared *pBt = p->pBt;
  53127. assert( sqlite3BtreeHoldsMutex(p) );
  53128. assert( p->inTrans==TRANS_WRITE );
  53129. /* It is illegal to drop a table if any cursors are open on the
  53130. ** database. This is because in auto-vacuum mode the backend may
  53131. ** need to move another root-page to fill a gap left by the deleted
  53132. ** root page. If an open cursor was using this page a problem would
  53133. ** occur.
  53134. **
  53135. ** This error is caught long before control reaches this point.
  53136. */
  53137. if( NEVER(pBt->pCursor) ){
  53138. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  53139. return SQLITE_LOCKED_SHAREDCACHE;
  53140. }
  53141. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0, 0);
  53142. if( rc ) return rc;
  53143. rc = sqlite3BtreeClearTable(p, iTable, 0);
  53144. if( rc ){
  53145. releasePage(pPage);
  53146. return rc;
  53147. }
  53148. *piMoved = 0;
  53149. if( iTable>1 ){
  53150. #ifdef SQLITE_OMIT_AUTOVACUUM
  53151. freePage(pPage, &rc);
  53152. releasePage(pPage);
  53153. #else
  53154. if( pBt->autoVacuum ){
  53155. Pgno maxRootPgno;
  53156. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  53157. if( iTable==maxRootPgno ){
  53158. /* If the table being dropped is the table with the largest root-page
  53159. ** number in the database, put the root page on the free list.
  53160. */
  53161. freePage(pPage, &rc);
  53162. releasePage(pPage);
  53163. if( rc!=SQLITE_OK ){
  53164. return rc;
  53165. }
  53166. }else{
  53167. /* The table being dropped does not have the largest root-page
  53168. ** number in the database. So move the page that does into the
  53169. ** gap left by the deleted root-page.
  53170. */
  53171. MemPage *pMove;
  53172. releasePage(pPage);
  53173. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
  53174. if( rc!=SQLITE_OK ){
  53175. return rc;
  53176. }
  53177. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  53178. releasePage(pMove);
  53179. if( rc!=SQLITE_OK ){
  53180. return rc;
  53181. }
  53182. pMove = 0;
  53183. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
  53184. freePage(pMove, &rc);
  53185. releasePage(pMove);
  53186. if( rc!=SQLITE_OK ){
  53187. return rc;
  53188. }
  53189. *piMoved = maxRootPgno;
  53190. }
  53191. /* Set the new 'max-root-page' value in the database header. This
  53192. ** is the old value less one, less one more if that happens to
  53193. ** be a root-page number, less one again if that is the
  53194. ** PENDING_BYTE_PAGE.
  53195. */
  53196. maxRootPgno--;
  53197. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  53198. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  53199. maxRootPgno--;
  53200. }
  53201. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  53202. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  53203. }else{
  53204. freePage(pPage, &rc);
  53205. releasePage(pPage);
  53206. }
  53207. #endif
  53208. }else{
  53209. /* If sqlite3BtreeDropTable was called on page 1.
  53210. ** This really never should happen except in a corrupt
  53211. ** database.
  53212. */
  53213. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  53214. releasePage(pPage);
  53215. }
  53216. return rc;
  53217. }
  53218. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  53219. int rc;
  53220. sqlite3BtreeEnter(p);
  53221. rc = btreeDropTable(p, iTable, piMoved);
  53222. sqlite3BtreeLeave(p);
  53223. return rc;
  53224. }
  53225. /*
  53226. ** This function may only be called if the b-tree connection already
  53227. ** has a read or write transaction open on the database.
  53228. **
  53229. ** Read the meta-information out of a database file. Meta[0]
  53230. ** is the number of free pages currently in the database. Meta[1]
  53231. ** through meta[15] are available for use by higher layers. Meta[0]
  53232. ** is read-only, the others are read/write.
  53233. **
  53234. ** The schema layer numbers meta values differently. At the schema
  53235. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  53236. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  53237. */
  53238. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  53239. BtShared *pBt = p->pBt;
  53240. sqlite3BtreeEnter(p);
  53241. assert( p->inTrans>TRANS_NONE );
  53242. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  53243. assert( pBt->pPage1 );
  53244. assert( idx>=0 && idx<=15 );
  53245. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  53246. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  53247. ** database, mark the database as read-only. */
  53248. #ifdef SQLITE_OMIT_AUTOVACUUM
  53249. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  53250. pBt->btsFlags |= BTS_READ_ONLY;
  53251. }
  53252. #endif
  53253. sqlite3BtreeLeave(p);
  53254. }
  53255. /*
  53256. ** Write meta-information back into the database. Meta[0] is
  53257. ** read-only and may not be written.
  53258. */
  53259. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  53260. BtShared *pBt = p->pBt;
  53261. unsigned char *pP1;
  53262. int rc;
  53263. assert( idx>=1 && idx<=15 );
  53264. sqlite3BtreeEnter(p);
  53265. assert( p->inTrans==TRANS_WRITE );
  53266. assert( pBt->pPage1!=0 );
  53267. pP1 = pBt->pPage1->aData;
  53268. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53269. if( rc==SQLITE_OK ){
  53270. put4byte(&pP1[36 + idx*4], iMeta);
  53271. #ifndef SQLITE_OMIT_AUTOVACUUM
  53272. if( idx==BTREE_INCR_VACUUM ){
  53273. assert( pBt->autoVacuum || iMeta==0 );
  53274. assert( iMeta==0 || iMeta==1 );
  53275. pBt->incrVacuum = (u8)iMeta;
  53276. }
  53277. #endif
  53278. }
  53279. sqlite3BtreeLeave(p);
  53280. return rc;
  53281. }
  53282. #ifndef SQLITE_OMIT_BTREECOUNT
  53283. /*
  53284. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  53285. ** number of entries in the b-tree and write the result to *pnEntry.
  53286. **
  53287. ** SQLITE_OK is returned if the operation is successfully executed.
  53288. ** Otherwise, if an error is encountered (i.e. an IO error or database
  53289. ** corruption) an SQLite error code is returned.
  53290. */
  53291. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  53292. i64 nEntry = 0; /* Value to return in *pnEntry */
  53293. int rc; /* Return code */
  53294. if( pCur->pgnoRoot==0 ){
  53295. *pnEntry = 0;
  53296. return SQLITE_OK;
  53297. }
  53298. rc = moveToRoot(pCur);
  53299. /* Unless an error occurs, the following loop runs one iteration for each
  53300. ** page in the B-Tree structure (not including overflow pages).
  53301. */
  53302. while( rc==SQLITE_OK ){
  53303. int iIdx; /* Index of child node in parent */
  53304. MemPage *pPage; /* Current page of the b-tree */
  53305. /* If this is a leaf page or the tree is not an int-key tree, then
  53306. ** this page contains countable entries. Increment the entry counter
  53307. ** accordingly.
  53308. */
  53309. pPage = pCur->apPage[pCur->iPage];
  53310. if( pPage->leaf || !pPage->intKey ){
  53311. nEntry += pPage->nCell;
  53312. }
  53313. /* pPage is a leaf node. This loop navigates the cursor so that it
  53314. ** points to the first interior cell that it points to the parent of
  53315. ** the next page in the tree that has not yet been visited. The
  53316. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  53317. ** of the page, or to the number of cells in the page if the next page
  53318. ** to visit is the right-child of its parent.
  53319. **
  53320. ** If all pages in the tree have been visited, return SQLITE_OK to the
  53321. ** caller.
  53322. */
  53323. if( pPage->leaf ){
  53324. do {
  53325. if( pCur->iPage==0 ){
  53326. /* All pages of the b-tree have been visited. Return successfully. */
  53327. *pnEntry = nEntry;
  53328. return SQLITE_OK;
  53329. }
  53330. moveToParent(pCur);
  53331. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  53332. pCur->aiIdx[pCur->iPage]++;
  53333. pPage = pCur->apPage[pCur->iPage];
  53334. }
  53335. /* Descend to the child node of the cell that the cursor currently
  53336. ** points at. This is the right-child if (iIdx==pPage->nCell).
  53337. */
  53338. iIdx = pCur->aiIdx[pCur->iPage];
  53339. if( iIdx==pPage->nCell ){
  53340. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  53341. }else{
  53342. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  53343. }
  53344. }
  53345. /* An error has occurred. Return an error code. */
  53346. return rc;
  53347. }
  53348. #endif
  53349. /*
  53350. ** Return the pager associated with a BTree. This routine is used for
  53351. ** testing and debugging only.
  53352. */
  53353. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  53354. return p->pBt->pPager;
  53355. }
  53356. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53357. /*
  53358. ** Append a message to the error message string.
  53359. */
  53360. static void checkAppendMsg(
  53361. IntegrityCk *pCheck,
  53362. char *zMsg1,
  53363. const char *zFormat,
  53364. ...
  53365. ){
  53366. va_list ap;
  53367. if( !pCheck->mxErr ) return;
  53368. pCheck->mxErr--;
  53369. pCheck->nErr++;
  53370. va_start(ap, zFormat);
  53371. if( pCheck->errMsg.nChar ){
  53372. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  53373. }
  53374. if( zMsg1 ){
  53375. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  53376. }
  53377. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  53378. va_end(ap);
  53379. if( pCheck->errMsg.mallocFailed ){
  53380. pCheck->mallocFailed = 1;
  53381. }
  53382. }
  53383. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53384. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53385. /*
  53386. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  53387. ** corresponds to page iPg is already set.
  53388. */
  53389. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  53390. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  53391. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  53392. }
  53393. /*
  53394. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  53395. */
  53396. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  53397. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  53398. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  53399. }
  53400. /*
  53401. ** Add 1 to the reference count for page iPage. If this is the second
  53402. ** reference to the page, add an error message to pCheck->zErrMsg.
  53403. ** Return 1 if there are 2 ore more references to the page and 0 if
  53404. ** if this is the first reference to the page.
  53405. **
  53406. ** Also check that the page number is in bounds.
  53407. */
  53408. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  53409. if( iPage==0 ) return 1;
  53410. if( iPage>pCheck->nPage ){
  53411. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  53412. return 1;
  53413. }
  53414. if( getPageReferenced(pCheck, iPage) ){
  53415. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  53416. return 1;
  53417. }
  53418. setPageReferenced(pCheck, iPage);
  53419. return 0;
  53420. }
  53421. #ifndef SQLITE_OMIT_AUTOVACUUM
  53422. /*
  53423. ** Check that the entry in the pointer-map for page iChild maps to
  53424. ** page iParent, pointer type ptrType. If not, append an error message
  53425. ** to pCheck.
  53426. */
  53427. static void checkPtrmap(
  53428. IntegrityCk *pCheck, /* Integrity check context */
  53429. Pgno iChild, /* Child page number */
  53430. u8 eType, /* Expected pointer map type */
  53431. Pgno iParent, /* Expected pointer map parent page number */
  53432. char *zContext /* Context description (used for error msg) */
  53433. ){
  53434. int rc;
  53435. u8 ePtrmapType;
  53436. Pgno iPtrmapParent;
  53437. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  53438. if( rc!=SQLITE_OK ){
  53439. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  53440. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  53441. return;
  53442. }
  53443. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  53444. checkAppendMsg(pCheck, zContext,
  53445. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  53446. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  53447. }
  53448. }
  53449. #endif
  53450. /*
  53451. ** Check the integrity of the freelist or of an overflow page list.
  53452. ** Verify that the number of pages on the list is N.
  53453. */
  53454. static void checkList(
  53455. IntegrityCk *pCheck, /* Integrity checking context */
  53456. int isFreeList, /* True for a freelist. False for overflow page list */
  53457. int iPage, /* Page number for first page in the list */
  53458. int N, /* Expected number of pages in the list */
  53459. char *zContext /* Context for error messages */
  53460. ){
  53461. int i;
  53462. int expected = N;
  53463. int iFirst = iPage;
  53464. while( N-- > 0 && pCheck->mxErr ){
  53465. DbPage *pOvflPage;
  53466. unsigned char *pOvflData;
  53467. if( iPage<1 ){
  53468. checkAppendMsg(pCheck, zContext,
  53469. "%d of %d pages missing from overflow list starting at %d",
  53470. N+1, expected, iFirst);
  53471. break;
  53472. }
  53473. if( checkRef(pCheck, iPage, zContext) ) break;
  53474. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  53475. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  53476. break;
  53477. }
  53478. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  53479. if( isFreeList ){
  53480. int n = get4byte(&pOvflData[4]);
  53481. #ifndef SQLITE_OMIT_AUTOVACUUM
  53482. if( pCheck->pBt->autoVacuum ){
  53483. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  53484. }
  53485. #endif
  53486. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  53487. checkAppendMsg(pCheck, zContext,
  53488. "freelist leaf count too big on page %d", iPage);
  53489. N--;
  53490. }else{
  53491. for(i=0; i<n; i++){
  53492. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  53493. #ifndef SQLITE_OMIT_AUTOVACUUM
  53494. if( pCheck->pBt->autoVacuum ){
  53495. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  53496. }
  53497. #endif
  53498. checkRef(pCheck, iFreePage, zContext);
  53499. }
  53500. N -= n;
  53501. }
  53502. }
  53503. #ifndef SQLITE_OMIT_AUTOVACUUM
  53504. else{
  53505. /* If this database supports auto-vacuum and iPage is not the last
  53506. ** page in this overflow list, check that the pointer-map entry for
  53507. ** the following page matches iPage.
  53508. */
  53509. if( pCheck->pBt->autoVacuum && N>0 ){
  53510. i = get4byte(pOvflData);
  53511. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  53512. }
  53513. }
  53514. #endif
  53515. iPage = get4byte(pOvflData);
  53516. sqlite3PagerUnref(pOvflPage);
  53517. }
  53518. }
  53519. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53520. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53521. /*
  53522. ** Do various sanity checks on a single page of a tree. Return
  53523. ** the tree depth. Root pages return 0. Parents of root pages
  53524. ** return 1, and so forth.
  53525. **
  53526. ** These checks are done:
  53527. **
  53528. ** 1. Make sure that cells and freeblocks do not overlap
  53529. ** but combine to completely cover the page.
  53530. ** NO 2. Make sure cell keys are in order.
  53531. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  53532. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  53533. ** 5. Check the integrity of overflow pages.
  53534. ** 6. Recursively call checkTreePage on all children.
  53535. ** 7. Verify that the depth of all children is the same.
  53536. ** 8. Make sure this page is at least 33% full or else it is
  53537. ** the root of the tree.
  53538. */
  53539. static int checkTreePage(
  53540. IntegrityCk *pCheck, /* Context for the sanity check */
  53541. int iPage, /* Page number of the page to check */
  53542. char *zParentContext, /* Parent context */
  53543. i64 *pnParentMinKey,
  53544. i64 *pnParentMaxKey
  53545. ){
  53546. MemPage *pPage;
  53547. int i, rc, depth, d2, pgno, cnt;
  53548. int hdr, cellStart;
  53549. int nCell;
  53550. u8 *data;
  53551. BtShared *pBt;
  53552. int usableSize;
  53553. char zContext[100];
  53554. char *hit = 0;
  53555. i64 nMinKey = 0;
  53556. i64 nMaxKey = 0;
  53557. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  53558. /* Check that the page exists
  53559. */
  53560. pBt = pCheck->pBt;
  53561. usableSize = pBt->usableSize;
  53562. if( iPage==0 ) return 0;
  53563. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  53564. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0, 0))!=0 ){
  53565. checkAppendMsg(pCheck, zContext,
  53566. "unable to get the page. error code=%d", rc);
  53567. return 0;
  53568. }
  53569. /* Clear MemPage.isInit to make sure the corruption detection code in
  53570. ** btreeInitPage() is executed. */
  53571. pPage->isInit = 0;
  53572. if( (rc = btreeInitPage(pPage))!=0 ){
  53573. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  53574. checkAppendMsg(pCheck, zContext,
  53575. "btreeInitPage() returns error code %d", rc);
  53576. releasePage(pPage);
  53577. return 0;
  53578. }
  53579. /* Check out all the cells.
  53580. */
  53581. depth = 0;
  53582. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  53583. u8 *pCell;
  53584. u32 sz;
  53585. CellInfo info;
  53586. /* Check payload overflow pages
  53587. */
  53588. sqlite3_snprintf(sizeof(zContext), zContext,
  53589. "On tree page %d cell %d: ", iPage, i);
  53590. pCell = findCell(pPage,i);
  53591. btreeParseCellPtr(pPage, pCell, &info);
  53592. sz = info.nData;
  53593. if( !pPage->intKey ) sz += (int)info.nKey;
  53594. /* For intKey pages, check that the keys are in order.
  53595. */
  53596. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  53597. else{
  53598. if( info.nKey <= nMaxKey ){
  53599. checkAppendMsg(pCheck, zContext,
  53600. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  53601. }
  53602. nMaxKey = info.nKey;
  53603. }
  53604. assert( sz==info.nPayload );
  53605. if( (sz>info.nLocal)
  53606. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  53607. ){
  53608. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  53609. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  53610. #ifndef SQLITE_OMIT_AUTOVACUUM
  53611. if( pBt->autoVacuum ){
  53612. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  53613. }
  53614. #endif
  53615. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  53616. }
  53617. /* Check sanity of left child page.
  53618. */
  53619. if( !pPage->leaf ){
  53620. pgno = get4byte(pCell);
  53621. #ifndef SQLITE_OMIT_AUTOVACUUM
  53622. if( pBt->autoVacuum ){
  53623. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  53624. }
  53625. #endif
  53626. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  53627. if( i>0 && d2!=depth ){
  53628. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  53629. }
  53630. depth = d2;
  53631. }
  53632. }
  53633. if( !pPage->leaf ){
  53634. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53635. sqlite3_snprintf(sizeof(zContext), zContext,
  53636. "On page %d at right child: ", iPage);
  53637. #ifndef SQLITE_OMIT_AUTOVACUUM
  53638. if( pBt->autoVacuum ){
  53639. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  53640. }
  53641. #endif
  53642. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  53643. }
  53644. /* For intKey leaf pages, check that the min/max keys are in order
  53645. ** with any left/parent/right pages.
  53646. */
  53647. if( pPage->leaf && pPage->intKey ){
  53648. /* if we are a left child page */
  53649. if( pnParentMinKey ){
  53650. /* if we are the left most child page */
  53651. if( !pnParentMaxKey ){
  53652. if( nMaxKey > *pnParentMinKey ){
  53653. checkAppendMsg(pCheck, zContext,
  53654. "Rowid %lld out of order (max larger than parent min of %lld)",
  53655. nMaxKey, *pnParentMinKey);
  53656. }
  53657. }else{
  53658. if( nMinKey <= *pnParentMinKey ){
  53659. checkAppendMsg(pCheck, zContext,
  53660. "Rowid %lld out of order (min less than parent min of %lld)",
  53661. nMinKey, *pnParentMinKey);
  53662. }
  53663. if( nMaxKey > *pnParentMaxKey ){
  53664. checkAppendMsg(pCheck, zContext,
  53665. "Rowid %lld out of order (max larger than parent max of %lld)",
  53666. nMaxKey, *pnParentMaxKey);
  53667. }
  53668. *pnParentMinKey = nMaxKey;
  53669. }
  53670. /* else if we're a right child page */
  53671. } else if( pnParentMaxKey ){
  53672. if( nMinKey <= *pnParentMaxKey ){
  53673. checkAppendMsg(pCheck, zContext,
  53674. "Rowid %lld out of order (min less than parent max of %lld)",
  53675. nMinKey, *pnParentMaxKey);
  53676. }
  53677. }
  53678. }
  53679. /* Check for complete coverage of the page
  53680. */
  53681. data = pPage->aData;
  53682. hdr = pPage->hdrOffset;
  53683. hit = sqlite3PageMalloc( pBt->pageSize );
  53684. if( hit==0 ){
  53685. pCheck->mallocFailed = 1;
  53686. }else{
  53687. int contentOffset = get2byteNotZero(&data[hdr+5]);
  53688. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  53689. memset(hit+contentOffset, 0, usableSize-contentOffset);
  53690. memset(hit, 1, contentOffset);
  53691. nCell = get2byte(&data[hdr+3]);
  53692. cellStart = hdr + 12 - 4*pPage->leaf;
  53693. for(i=0; i<nCell; i++){
  53694. int pc = get2byte(&data[cellStart+i*2]);
  53695. u32 size = 65536;
  53696. int j;
  53697. if( pc<=usableSize-4 ){
  53698. size = cellSizePtr(pPage, &data[pc]);
  53699. }
  53700. if( (int)(pc+size-1)>=usableSize ){
  53701. checkAppendMsg(pCheck, 0,
  53702. "Corruption detected in cell %d on page %d",i,iPage);
  53703. }else{
  53704. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  53705. }
  53706. }
  53707. i = get2byte(&data[hdr+1]);
  53708. while( i>0 ){
  53709. int size, j;
  53710. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  53711. size = get2byte(&data[i+2]);
  53712. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  53713. for(j=i+size-1; j>=i; j--) hit[j]++;
  53714. j = get2byte(&data[i]);
  53715. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  53716. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  53717. i = j;
  53718. }
  53719. for(i=cnt=0; i<usableSize; i++){
  53720. if( hit[i]==0 ){
  53721. cnt++;
  53722. }else if( hit[i]>1 ){
  53723. checkAppendMsg(pCheck, 0,
  53724. "Multiple uses for byte %d of page %d", i, iPage);
  53725. break;
  53726. }
  53727. }
  53728. if( cnt!=data[hdr+7] ){
  53729. checkAppendMsg(pCheck, 0,
  53730. "Fragmentation of %d bytes reported as %d on page %d",
  53731. cnt, data[hdr+7], iPage);
  53732. }
  53733. }
  53734. sqlite3PageFree(hit);
  53735. releasePage(pPage);
  53736. return depth+1;
  53737. }
  53738. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53739. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  53740. /*
  53741. ** This routine does a complete check of the given BTree file. aRoot[] is
  53742. ** an array of pages numbers were each page number is the root page of
  53743. ** a table. nRoot is the number of entries in aRoot.
  53744. **
  53745. ** A read-only or read-write transaction must be opened before calling
  53746. ** this function.
  53747. **
  53748. ** Write the number of error seen in *pnErr. Except for some memory
  53749. ** allocation errors, an error message held in memory obtained from
  53750. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  53751. ** returned. If a memory allocation error occurs, NULL is returned.
  53752. */
  53753. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  53754. Btree *p, /* The btree to be checked */
  53755. int *aRoot, /* An array of root pages numbers for individual trees */
  53756. int nRoot, /* Number of entries in aRoot[] */
  53757. int mxErr, /* Stop reporting errors after this many */
  53758. int *pnErr /* Write number of errors seen to this variable */
  53759. ){
  53760. Pgno i;
  53761. int nRef;
  53762. IntegrityCk sCheck;
  53763. BtShared *pBt = p->pBt;
  53764. char zErr[100];
  53765. sqlite3BtreeEnter(p);
  53766. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  53767. nRef = sqlite3PagerRefcount(pBt->pPager);
  53768. sCheck.pBt = pBt;
  53769. sCheck.pPager = pBt->pPager;
  53770. sCheck.nPage = btreePagecount(sCheck.pBt);
  53771. sCheck.mxErr = mxErr;
  53772. sCheck.nErr = 0;
  53773. sCheck.mallocFailed = 0;
  53774. *pnErr = 0;
  53775. if( sCheck.nPage==0 ){
  53776. sqlite3BtreeLeave(p);
  53777. return 0;
  53778. }
  53779. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  53780. if( !sCheck.aPgRef ){
  53781. *pnErr = 1;
  53782. sqlite3BtreeLeave(p);
  53783. return 0;
  53784. }
  53785. i = PENDING_BYTE_PAGE(pBt);
  53786. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  53787. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  53788. sCheck.errMsg.useMalloc = 2;
  53789. /* Check the integrity of the freelist
  53790. */
  53791. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  53792. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  53793. /* Check all the tables.
  53794. */
  53795. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  53796. if( aRoot[i]==0 ) continue;
  53797. #ifndef SQLITE_OMIT_AUTOVACUUM
  53798. if( pBt->autoVacuum && aRoot[i]>1 ){
  53799. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  53800. }
  53801. #endif
  53802. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  53803. }
  53804. /* Make sure every page in the file is referenced
  53805. */
  53806. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  53807. #ifdef SQLITE_OMIT_AUTOVACUUM
  53808. if( getPageReferenced(&sCheck, i)==0 ){
  53809. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  53810. }
  53811. #else
  53812. /* If the database supports auto-vacuum, make sure no tables contain
  53813. ** references to pointer-map pages.
  53814. */
  53815. if( getPageReferenced(&sCheck, i)==0 &&
  53816. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  53817. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  53818. }
  53819. if( getPageReferenced(&sCheck, i)!=0 &&
  53820. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  53821. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  53822. }
  53823. #endif
  53824. }
  53825. /* Make sure this analysis did not leave any unref() pages.
  53826. ** This is an internal consistency check; an integrity check
  53827. ** of the integrity check.
  53828. */
  53829. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  53830. checkAppendMsg(&sCheck, 0,
  53831. "Outstanding page count goes from %d to %d during this analysis",
  53832. nRef, sqlite3PagerRefcount(pBt->pPager)
  53833. );
  53834. }
  53835. /* Clean up and report errors.
  53836. */
  53837. sqlite3BtreeLeave(p);
  53838. sqlite3_free(sCheck.aPgRef);
  53839. if( sCheck.mallocFailed ){
  53840. sqlite3StrAccumReset(&sCheck.errMsg);
  53841. *pnErr = sCheck.nErr+1;
  53842. return 0;
  53843. }
  53844. *pnErr = sCheck.nErr;
  53845. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  53846. return sqlite3StrAccumFinish(&sCheck.errMsg);
  53847. }
  53848. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  53849. /*
  53850. ** Return the full pathname of the underlying database file. Return
  53851. ** an empty string if the database is in-memory or a TEMP database.
  53852. **
  53853. ** The pager filename is invariant as long as the pager is
  53854. ** open so it is safe to access without the BtShared mutex.
  53855. */
  53856. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  53857. assert( p->pBt->pPager!=0 );
  53858. return sqlite3PagerFilename(p->pBt->pPager, 1);
  53859. }
  53860. /*
  53861. ** Return the pathname of the journal file for this database. The return
  53862. ** value of this routine is the same regardless of whether the journal file
  53863. ** has been created or not.
  53864. **
  53865. ** The pager journal filename is invariant as long as the pager is
  53866. ** open so it is safe to access without the BtShared mutex.
  53867. */
  53868. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  53869. assert( p->pBt->pPager!=0 );
  53870. return sqlite3PagerJournalname(p->pBt->pPager);
  53871. }
  53872. /*
  53873. ** Return non-zero if a transaction is active.
  53874. */
  53875. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  53876. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  53877. return (p && (p->inTrans==TRANS_WRITE));
  53878. }
  53879. #ifndef SQLITE_OMIT_WAL
  53880. /*
  53881. ** Run a checkpoint on the Btree passed as the first argument.
  53882. **
  53883. ** Return SQLITE_LOCKED if this or any other connection has an open
  53884. ** transaction on the shared-cache the argument Btree is connected to.
  53885. **
  53886. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  53887. */
  53888. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  53889. int rc = SQLITE_OK;
  53890. if( p ){
  53891. BtShared *pBt = p->pBt;
  53892. sqlite3BtreeEnter(p);
  53893. if( pBt->inTransaction!=TRANS_NONE ){
  53894. rc = SQLITE_LOCKED;
  53895. }else{
  53896. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  53897. }
  53898. sqlite3BtreeLeave(p);
  53899. }
  53900. return rc;
  53901. }
  53902. #endif
  53903. /*
  53904. ** Return non-zero if a read (or write) transaction is active.
  53905. */
  53906. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  53907. assert( p );
  53908. assert( sqlite3_mutex_held(p->db->mutex) );
  53909. return p->inTrans!=TRANS_NONE;
  53910. }
  53911. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  53912. assert( p );
  53913. assert( sqlite3_mutex_held(p->db->mutex) );
  53914. return p->nBackup!=0;
  53915. }
  53916. /*
  53917. ** This function returns a pointer to a blob of memory associated with
  53918. ** a single shared-btree. The memory is used by client code for its own
  53919. ** purposes (for example, to store a high-level schema associated with
  53920. ** the shared-btree). The btree layer manages reference counting issues.
  53921. **
  53922. ** The first time this is called on a shared-btree, nBytes bytes of memory
  53923. ** are allocated, zeroed, and returned to the caller. For each subsequent
  53924. ** call the nBytes parameter is ignored and a pointer to the same blob
  53925. ** of memory returned.
  53926. **
  53927. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  53928. ** allocated, a null pointer is returned. If the blob has already been
  53929. ** allocated, it is returned as normal.
  53930. **
  53931. ** Just before the shared-btree is closed, the function passed as the
  53932. ** xFree argument when the memory allocation was made is invoked on the
  53933. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  53934. ** on the memory, the btree layer does that.
  53935. */
  53936. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  53937. BtShared *pBt = p->pBt;
  53938. sqlite3BtreeEnter(p);
  53939. if( !pBt->pSchema && nBytes ){
  53940. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  53941. pBt->xFreeSchema = xFree;
  53942. }
  53943. sqlite3BtreeLeave(p);
  53944. return pBt->pSchema;
  53945. }
  53946. /*
  53947. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  53948. ** btree as the argument handle holds an exclusive lock on the
  53949. ** sqlite_master table. Otherwise SQLITE_OK.
  53950. */
  53951. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  53952. int rc;
  53953. assert( sqlite3_mutex_held(p->db->mutex) );
  53954. sqlite3BtreeEnter(p);
  53955. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  53956. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  53957. sqlite3BtreeLeave(p);
  53958. return rc;
  53959. }
  53960. #ifndef SQLITE_OMIT_SHARED_CACHE
  53961. /*
  53962. ** Obtain a lock on the table whose root page is iTab. The
  53963. ** lock is a write lock if isWritelock is true or a read lock
  53964. ** if it is false.
  53965. */
  53966. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  53967. int rc = SQLITE_OK;
  53968. assert( p->inTrans!=TRANS_NONE );
  53969. if( p->sharable ){
  53970. u8 lockType = READ_LOCK + isWriteLock;
  53971. assert( READ_LOCK+1==WRITE_LOCK );
  53972. assert( isWriteLock==0 || isWriteLock==1 );
  53973. sqlite3BtreeEnter(p);
  53974. rc = querySharedCacheTableLock(p, iTab, lockType);
  53975. if( rc==SQLITE_OK ){
  53976. rc = setSharedCacheTableLock(p, iTab, lockType);
  53977. }
  53978. sqlite3BtreeLeave(p);
  53979. }
  53980. return rc;
  53981. }
  53982. #endif
  53983. #ifndef SQLITE_OMIT_INCRBLOB
  53984. /*
  53985. ** Argument pCsr must be a cursor opened for writing on an
  53986. ** INTKEY table currently pointing at a valid table entry.
  53987. ** This function modifies the data stored as part of that entry.
  53988. **
  53989. ** Only the data content may only be modified, it is not possible to
  53990. ** change the length of the data stored. If this function is called with
  53991. ** parameters that attempt to write past the end of the existing data,
  53992. ** no modifications are made and SQLITE_CORRUPT is returned.
  53993. */
  53994. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  53995. int rc;
  53996. assert( cursorHoldsMutex(pCsr) );
  53997. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  53998. assert( pCsr->isIncrblobHandle );
  53999. rc = restoreCursorPosition(pCsr);
  54000. if( rc!=SQLITE_OK ){
  54001. return rc;
  54002. }
  54003. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  54004. if( pCsr->eState!=CURSOR_VALID ){
  54005. return SQLITE_ABORT;
  54006. }
  54007. /* Save the positions of all other cursors open on this table. This is
  54008. ** required in case any of them are holding references to an xFetch
  54009. ** version of the b-tree page modified by the accessPayload call below.
  54010. **
  54011. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  54012. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  54013. ** saveAllCursors can only return SQLITE_OK.
  54014. */
  54015. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  54016. assert( rc==SQLITE_OK );
  54017. /* Check some assumptions:
  54018. ** (a) the cursor is open for writing,
  54019. ** (b) there is a read/write transaction open,
  54020. ** (c) the connection holds a write-lock on the table (if required),
  54021. ** (d) there are no conflicting read-locks, and
  54022. ** (e) the cursor points at a valid row of an intKey table.
  54023. */
  54024. if( !pCsr->wrFlag ){
  54025. return SQLITE_READONLY;
  54026. }
  54027. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  54028. && pCsr->pBt->inTransaction==TRANS_WRITE );
  54029. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  54030. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  54031. assert( pCsr->apPage[pCsr->iPage]->intKey );
  54032. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  54033. }
  54034. /*
  54035. ** Set a flag on this cursor to cache the locations of pages from the
  54036. ** overflow list for the current row. This is used by cursors opened
  54037. ** for incremental blob IO only.
  54038. **
  54039. ** This function sets a flag only. The actual page location cache
  54040. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  54041. ** accessPayload() (the worker function for sqlite3BtreeData() and
  54042. ** sqlite3BtreePutData()).
  54043. */
  54044. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  54045. assert( cursorHoldsMutex(pCur) );
  54046. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54047. invalidateOverflowCache(pCur);
  54048. pCur->isIncrblobHandle = 1;
  54049. }
  54050. #endif
  54051. /*
  54052. ** Set both the "read version" (single byte at byte offset 18) and
  54053. ** "write version" (single byte at byte offset 19) fields in the database
  54054. ** header to iVersion.
  54055. */
  54056. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  54057. BtShared *pBt = pBtree->pBt;
  54058. int rc; /* Return code */
  54059. assert( iVersion==1 || iVersion==2 );
  54060. /* If setting the version fields to 1, do not automatically open the
  54061. ** WAL connection, even if the version fields are currently set to 2.
  54062. */
  54063. pBt->btsFlags &= ~BTS_NO_WAL;
  54064. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  54065. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  54066. if( rc==SQLITE_OK ){
  54067. u8 *aData = pBt->pPage1->aData;
  54068. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  54069. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  54070. if( rc==SQLITE_OK ){
  54071. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54072. if( rc==SQLITE_OK ){
  54073. aData[18] = (u8)iVersion;
  54074. aData[19] = (u8)iVersion;
  54075. }
  54076. }
  54077. }
  54078. }
  54079. pBt->btsFlags &= ~BTS_NO_WAL;
  54080. return rc;
  54081. }
  54082. /*
  54083. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  54084. ** values are 0 and BTREE_BULKLOAD.
  54085. */
  54086. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  54087. assert( mask==BTREE_BULKLOAD || mask==0 );
  54088. pCsr->hints = mask;
  54089. }
  54090. /************** End of btree.c ***********************************************/
  54091. /************** Begin file backup.c ******************************************/
  54092. /*
  54093. ** 2009 January 28
  54094. **
  54095. ** The author disclaims copyright to this source code. In place of
  54096. ** a legal notice, here is a blessing:
  54097. **
  54098. ** May you do good and not evil.
  54099. ** May you find forgiveness for yourself and forgive others.
  54100. ** May you share freely, never taking more than you give.
  54101. **
  54102. *************************************************************************
  54103. ** This file contains the implementation of the sqlite3_backup_XXX()
  54104. ** API functions and the related features.
  54105. */
  54106. /* Macro to find the minimum of two numeric values.
  54107. */
  54108. #ifndef MIN
  54109. # define MIN(x,y) ((x)<(y)?(x):(y))
  54110. #endif
  54111. /*
  54112. ** Structure allocated for each backup operation.
  54113. */
  54114. struct sqlite3_backup {
  54115. sqlite3* pDestDb; /* Destination database handle */
  54116. Btree *pDest; /* Destination b-tree file */
  54117. u32 iDestSchema; /* Original schema cookie in destination */
  54118. int bDestLocked; /* True once a write-transaction is open on pDest */
  54119. Pgno iNext; /* Page number of the next source page to copy */
  54120. sqlite3* pSrcDb; /* Source database handle */
  54121. Btree *pSrc; /* Source b-tree file */
  54122. int rc; /* Backup process error code */
  54123. /* These two variables are set by every call to backup_step(). They are
  54124. ** read by calls to backup_remaining() and backup_pagecount().
  54125. */
  54126. Pgno nRemaining; /* Number of pages left to copy */
  54127. Pgno nPagecount; /* Total number of pages to copy */
  54128. int isAttached; /* True once backup has been registered with pager */
  54129. sqlite3_backup *pNext; /* Next backup associated with source pager */
  54130. };
  54131. /*
  54132. ** THREAD SAFETY NOTES:
  54133. **
  54134. ** Once it has been created using backup_init(), a single sqlite3_backup
  54135. ** structure may be accessed via two groups of thread-safe entry points:
  54136. **
  54137. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  54138. ** backup_finish(). Both these functions obtain the source database
  54139. ** handle mutex and the mutex associated with the source BtShared
  54140. ** structure, in that order.
  54141. **
  54142. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  54143. ** invoked by the pager layer to report various state changes in
  54144. ** the page cache associated with the source database. The mutex
  54145. ** associated with the source database BtShared structure will always
  54146. ** be held when either of these functions are invoked.
  54147. **
  54148. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  54149. ** backup_pagecount() are not thread-safe functions. If they are called
  54150. ** while some other thread is calling backup_step() or backup_finish(),
  54151. ** the values returned may be invalid. There is no way for a call to
  54152. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  54153. ** or backup_pagecount().
  54154. **
  54155. ** Depending on the SQLite configuration, the database handles and/or
  54156. ** the Btree objects may have their own mutexes that require locking.
  54157. ** Non-sharable Btrees (in-memory databases for example), do not have
  54158. ** associated mutexes.
  54159. */
  54160. /*
  54161. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  54162. ** in connection handle pDb. If such a database cannot be found, return
  54163. ** a NULL pointer and write an error message to pErrorDb.
  54164. **
  54165. ** If the "temp" database is requested, it may need to be opened by this
  54166. ** function. If an error occurs while doing so, return 0 and write an
  54167. ** error message to pErrorDb.
  54168. */
  54169. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  54170. int i = sqlite3FindDbName(pDb, zDb);
  54171. if( i==1 ){
  54172. Parse *pParse;
  54173. int rc = 0;
  54174. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  54175. if( pParse==0 ){
  54176. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  54177. rc = SQLITE_NOMEM;
  54178. }else{
  54179. pParse->db = pDb;
  54180. if( sqlite3OpenTempDatabase(pParse) ){
  54181. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  54182. rc = SQLITE_ERROR;
  54183. }
  54184. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  54185. sqlite3StackFree(pErrorDb, pParse);
  54186. }
  54187. if( rc ){
  54188. return 0;
  54189. }
  54190. }
  54191. if( i<0 ){
  54192. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  54193. return 0;
  54194. }
  54195. return pDb->aDb[i].pBt;
  54196. }
  54197. /*
  54198. ** Attempt to set the page size of the destination to match the page size
  54199. ** of the source.
  54200. */
  54201. static int setDestPgsz(sqlite3_backup *p){
  54202. int rc;
  54203. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  54204. return rc;
  54205. }
  54206. /*
  54207. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  54208. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  54209. ** a pointer to the new sqlite3_backup object.
  54210. **
  54211. ** If an error occurs, NULL is returned and an error code and error message
  54212. ** stored in database handle pDestDb.
  54213. */
  54214. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  54215. sqlite3* pDestDb, /* Database to write to */
  54216. const char *zDestDb, /* Name of database within pDestDb */
  54217. sqlite3* pSrcDb, /* Database connection to read from */
  54218. const char *zSrcDb /* Name of database within pSrcDb */
  54219. ){
  54220. sqlite3_backup *p; /* Value to return */
  54221. /* Lock the source database handle. The destination database
  54222. ** handle is not locked in this routine, but it is locked in
  54223. ** sqlite3_backup_step(). The user is required to ensure that no
  54224. ** other thread accesses the destination handle for the duration
  54225. ** of the backup operation. Any attempt to use the destination
  54226. ** database connection while a backup is in progress may cause
  54227. ** a malfunction or a deadlock.
  54228. */
  54229. sqlite3_mutex_enter(pSrcDb->mutex);
  54230. sqlite3_mutex_enter(pDestDb->mutex);
  54231. if( pSrcDb==pDestDb ){
  54232. sqlite3Error(
  54233. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  54234. );
  54235. p = 0;
  54236. }else {
  54237. /* Allocate space for a new sqlite3_backup object...
  54238. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  54239. ** call to sqlite3_backup_init() and is destroyed by a call to
  54240. ** sqlite3_backup_finish(). */
  54241. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  54242. if( !p ){
  54243. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  54244. }
  54245. }
  54246. /* If the allocation succeeded, populate the new object. */
  54247. if( p ){
  54248. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  54249. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  54250. p->pDestDb = pDestDb;
  54251. p->pSrcDb = pSrcDb;
  54252. p->iNext = 1;
  54253. p->isAttached = 0;
  54254. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  54255. /* One (or both) of the named databases did not exist or an OOM
  54256. ** error was hit. The error has already been written into the
  54257. ** pDestDb handle. All that is left to do here is free the
  54258. ** sqlite3_backup structure.
  54259. */
  54260. sqlite3_free(p);
  54261. p = 0;
  54262. }
  54263. }
  54264. if( p ){
  54265. p->pSrc->nBackup++;
  54266. }
  54267. sqlite3_mutex_leave(pDestDb->mutex);
  54268. sqlite3_mutex_leave(pSrcDb->mutex);
  54269. return p;
  54270. }
  54271. /*
  54272. ** Argument rc is an SQLite error code. Return true if this error is
  54273. ** considered fatal if encountered during a backup operation. All errors
  54274. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  54275. */
  54276. static int isFatalError(int rc){
  54277. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  54278. }
  54279. /*
  54280. ** Parameter zSrcData points to a buffer containing the data for
  54281. ** page iSrcPg from the source database. Copy this data into the
  54282. ** destination database.
  54283. */
  54284. static int backupOnePage(
  54285. sqlite3_backup *p, /* Backup handle */
  54286. Pgno iSrcPg, /* Source database page to backup */
  54287. const u8 *zSrcData, /* Source database page data */
  54288. int bUpdate /* True for an update, false otherwise */
  54289. ){
  54290. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  54291. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  54292. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  54293. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  54294. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  54295. #ifdef SQLITE_HAS_CODEC
  54296. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  54297. ** guaranteed that the shared-mutex is held by this thread, handle
  54298. ** p->pSrc may not actually be the owner. */
  54299. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  54300. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  54301. #endif
  54302. int rc = SQLITE_OK;
  54303. i64 iOff;
  54304. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  54305. assert( p->bDestLocked );
  54306. assert( !isFatalError(p->rc) );
  54307. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  54308. assert( zSrcData );
  54309. /* Catch the case where the destination is an in-memory database and the
  54310. ** page sizes of the source and destination differ.
  54311. */
  54312. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  54313. rc = SQLITE_READONLY;
  54314. }
  54315. #ifdef SQLITE_HAS_CODEC
  54316. /* Backup is not possible if the page size of the destination is changing
  54317. ** and a codec is in use.
  54318. */
  54319. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  54320. rc = SQLITE_READONLY;
  54321. }
  54322. /* Backup is not possible if the number of bytes of reserve space differ
  54323. ** between source and destination. If there is a difference, try to
  54324. ** fix the destination to agree with the source. If that is not possible,
  54325. ** then the backup cannot proceed.
  54326. */
  54327. if( nSrcReserve!=nDestReserve ){
  54328. u32 newPgsz = nSrcPgsz;
  54329. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  54330. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  54331. }
  54332. #endif
  54333. /* This loop runs once for each destination page spanned by the source
  54334. ** page. For each iteration, variable iOff is set to the byte offset
  54335. ** of the destination page.
  54336. */
  54337. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  54338. DbPage *pDestPg = 0;
  54339. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  54340. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  54341. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  54342. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  54343. ){
  54344. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  54345. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  54346. u8 *zOut = &zDestData[iOff%nDestPgsz];
  54347. /* Copy the data from the source page into the destination page.
  54348. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  54349. ** and the pager code use this trick (clearing the first byte
  54350. ** of the page 'extra' space to invalidate the Btree layers
  54351. ** cached parse of the page). MemPage.isInit is marked
  54352. ** "MUST BE FIRST" for this purpose.
  54353. */
  54354. memcpy(zOut, zIn, nCopy);
  54355. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  54356. if( iOff==0 && bUpdate==0 ){
  54357. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  54358. }
  54359. }
  54360. sqlite3PagerUnref(pDestPg);
  54361. }
  54362. return rc;
  54363. }
  54364. /*
  54365. ** If pFile is currently larger than iSize bytes, then truncate it to
  54366. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  54367. ** this function is a no-op.
  54368. **
  54369. ** Return SQLITE_OK if everything is successful, or an SQLite error
  54370. ** code if an error occurs.
  54371. */
  54372. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  54373. i64 iCurrent;
  54374. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  54375. if( rc==SQLITE_OK && iCurrent>iSize ){
  54376. rc = sqlite3OsTruncate(pFile, iSize);
  54377. }
  54378. return rc;
  54379. }
  54380. /*
  54381. ** Register this backup object with the associated source pager for
  54382. ** callbacks when pages are changed or the cache invalidated.
  54383. */
  54384. static void attachBackupObject(sqlite3_backup *p){
  54385. sqlite3_backup **pp;
  54386. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  54387. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  54388. p->pNext = *pp;
  54389. *pp = p;
  54390. p->isAttached = 1;
  54391. }
  54392. /*
  54393. ** Copy nPage pages from the source b-tree to the destination.
  54394. */
  54395. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  54396. int rc;
  54397. int destMode; /* Destination journal mode */
  54398. int pgszSrc = 0; /* Source page size */
  54399. int pgszDest = 0; /* Destination page size */
  54400. sqlite3_mutex_enter(p->pSrcDb->mutex);
  54401. sqlite3BtreeEnter(p->pSrc);
  54402. if( p->pDestDb ){
  54403. sqlite3_mutex_enter(p->pDestDb->mutex);
  54404. }
  54405. rc = p->rc;
  54406. if( !isFatalError(rc) ){
  54407. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  54408. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  54409. int ii; /* Iterator variable */
  54410. int nSrcPage = -1; /* Size of source db in pages */
  54411. int bCloseTrans = 0; /* True if src db requires unlocking */
  54412. /* If the source pager is currently in a write-transaction, return
  54413. ** SQLITE_BUSY immediately.
  54414. */
  54415. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  54416. rc = SQLITE_BUSY;
  54417. }else{
  54418. rc = SQLITE_OK;
  54419. }
  54420. /* Lock the destination database, if it is not locked already. */
  54421. if( SQLITE_OK==rc && p->bDestLocked==0
  54422. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  54423. ){
  54424. p->bDestLocked = 1;
  54425. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  54426. }
  54427. /* If there is no open read-transaction on the source database, open
  54428. ** one now. If a transaction is opened here, then it will be closed
  54429. ** before this function exits.
  54430. */
  54431. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  54432. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  54433. bCloseTrans = 1;
  54434. }
  54435. /* Do not allow backup if the destination database is in WAL mode
  54436. ** and the page sizes are different between source and destination */
  54437. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  54438. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  54439. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  54440. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  54441. rc = SQLITE_READONLY;
  54442. }
  54443. /* Now that there is a read-lock on the source database, query the
  54444. ** source pager for the number of pages in the database.
  54445. */
  54446. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  54447. assert( nSrcPage>=0 );
  54448. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  54449. const Pgno iSrcPg = p->iNext; /* Source page number */
  54450. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  54451. DbPage *pSrcPg; /* Source page object */
  54452. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  54453. PAGER_ACQUIRE_READONLY);
  54454. if( rc==SQLITE_OK ){
  54455. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  54456. sqlite3PagerUnref(pSrcPg);
  54457. }
  54458. }
  54459. p->iNext++;
  54460. }
  54461. if( rc==SQLITE_OK ){
  54462. p->nPagecount = nSrcPage;
  54463. p->nRemaining = nSrcPage+1-p->iNext;
  54464. if( p->iNext>(Pgno)nSrcPage ){
  54465. rc = SQLITE_DONE;
  54466. }else if( !p->isAttached ){
  54467. attachBackupObject(p);
  54468. }
  54469. }
  54470. /* Update the schema version field in the destination database. This
  54471. ** is to make sure that the schema-version really does change in
  54472. ** the case where the source and destination databases have the
  54473. ** same schema version.
  54474. */
  54475. if( rc==SQLITE_DONE ){
  54476. if( nSrcPage==0 ){
  54477. rc = sqlite3BtreeNewDb(p->pDest);
  54478. nSrcPage = 1;
  54479. }
  54480. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  54481. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  54482. }
  54483. if( rc==SQLITE_OK ){
  54484. if( p->pDestDb ){
  54485. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  54486. }
  54487. if( destMode==PAGER_JOURNALMODE_WAL ){
  54488. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  54489. }
  54490. }
  54491. if( rc==SQLITE_OK ){
  54492. int nDestTruncate;
  54493. /* Set nDestTruncate to the final number of pages in the destination
  54494. ** database. The complication here is that the destination page
  54495. ** size may be different to the source page size.
  54496. **
  54497. ** If the source page size is smaller than the destination page size,
  54498. ** round up. In this case the call to sqlite3OsTruncate() below will
  54499. ** fix the size of the file. However it is important to call
  54500. ** sqlite3PagerTruncateImage() here so that any pages in the
  54501. ** destination file that lie beyond the nDestTruncate page mark are
  54502. ** journalled by PagerCommitPhaseOne() before they are destroyed
  54503. ** by the file truncation.
  54504. */
  54505. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  54506. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  54507. if( pgszSrc<pgszDest ){
  54508. int ratio = pgszDest/pgszSrc;
  54509. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  54510. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  54511. nDestTruncate--;
  54512. }
  54513. }else{
  54514. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  54515. }
  54516. assert( nDestTruncate>0 );
  54517. if( pgszSrc<pgszDest ){
  54518. /* If the source page-size is smaller than the destination page-size,
  54519. ** two extra things may need to happen:
  54520. **
  54521. ** * The destination may need to be truncated, and
  54522. **
  54523. ** * Data stored on the pages immediately following the
  54524. ** pending-byte page in the source database may need to be
  54525. ** copied into the destination database.
  54526. */
  54527. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  54528. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  54529. Pgno iPg;
  54530. int nDstPage;
  54531. i64 iOff;
  54532. i64 iEnd;
  54533. assert( pFile );
  54534. assert( nDestTruncate==0
  54535. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  54536. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  54537. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  54538. ));
  54539. /* This block ensures that all data required to recreate the original
  54540. ** database has been stored in the journal for pDestPager and the
  54541. ** journal synced to disk. So at this point we may safely modify
  54542. ** the database file in any way, knowing that if a power failure
  54543. ** occurs, the original database will be reconstructed from the
  54544. ** journal file. */
  54545. sqlite3PagerPagecount(pDestPager, &nDstPage);
  54546. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  54547. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  54548. DbPage *pPg;
  54549. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  54550. if( rc==SQLITE_OK ){
  54551. rc = sqlite3PagerWrite(pPg);
  54552. sqlite3PagerUnref(pPg);
  54553. }
  54554. }
  54555. }
  54556. if( rc==SQLITE_OK ){
  54557. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  54558. }
  54559. /* Write the extra pages and truncate the database file as required */
  54560. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  54561. for(
  54562. iOff=PENDING_BYTE+pgszSrc;
  54563. rc==SQLITE_OK && iOff<iEnd;
  54564. iOff+=pgszSrc
  54565. ){
  54566. PgHdr *pSrcPg = 0;
  54567. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  54568. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  54569. if( rc==SQLITE_OK ){
  54570. u8 *zData = sqlite3PagerGetData(pSrcPg);
  54571. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  54572. }
  54573. sqlite3PagerUnref(pSrcPg);
  54574. }
  54575. if( rc==SQLITE_OK ){
  54576. rc = backupTruncateFile(pFile, iSize);
  54577. }
  54578. /* Sync the database file to disk. */
  54579. if( rc==SQLITE_OK ){
  54580. rc = sqlite3PagerSync(pDestPager);
  54581. }
  54582. }else{
  54583. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  54584. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  54585. }
  54586. /* Finish committing the transaction to the destination database. */
  54587. if( SQLITE_OK==rc
  54588. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  54589. ){
  54590. rc = SQLITE_DONE;
  54591. }
  54592. }
  54593. }
  54594. /* If bCloseTrans is true, then this function opened a read transaction
  54595. ** on the source database. Close the read transaction here. There is
  54596. ** no need to check the return values of the btree methods here, as
  54597. ** "committing" a read-only transaction cannot fail.
  54598. */
  54599. if( bCloseTrans ){
  54600. TESTONLY( int rc2 );
  54601. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  54602. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  54603. assert( rc2==SQLITE_OK );
  54604. }
  54605. if( rc==SQLITE_IOERR_NOMEM ){
  54606. rc = SQLITE_NOMEM;
  54607. }
  54608. p->rc = rc;
  54609. }
  54610. if( p->pDestDb ){
  54611. sqlite3_mutex_leave(p->pDestDb->mutex);
  54612. }
  54613. sqlite3BtreeLeave(p->pSrc);
  54614. sqlite3_mutex_leave(p->pSrcDb->mutex);
  54615. return rc;
  54616. }
  54617. /*
  54618. ** Release all resources associated with an sqlite3_backup* handle.
  54619. */
  54620. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  54621. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  54622. sqlite3 *pSrcDb; /* Source database connection */
  54623. int rc; /* Value to return */
  54624. /* Enter the mutexes */
  54625. if( p==0 ) return SQLITE_OK;
  54626. pSrcDb = p->pSrcDb;
  54627. sqlite3_mutex_enter(pSrcDb->mutex);
  54628. sqlite3BtreeEnter(p->pSrc);
  54629. if( p->pDestDb ){
  54630. sqlite3_mutex_enter(p->pDestDb->mutex);
  54631. }
  54632. /* Detach this backup from the source pager. */
  54633. if( p->pDestDb ){
  54634. p->pSrc->nBackup--;
  54635. }
  54636. if( p->isAttached ){
  54637. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  54638. while( *pp!=p ){
  54639. pp = &(*pp)->pNext;
  54640. }
  54641. *pp = p->pNext;
  54642. }
  54643. /* If a transaction is still open on the Btree, roll it back. */
  54644. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  54645. /* Set the error code of the destination database handle. */
  54646. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  54647. sqlite3Error(p->pDestDb, rc, 0);
  54648. /* Exit the mutexes and free the backup context structure. */
  54649. if( p->pDestDb ){
  54650. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  54651. }
  54652. sqlite3BtreeLeave(p->pSrc);
  54653. if( p->pDestDb ){
  54654. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  54655. ** call to sqlite3_backup_init() and is destroyed by a call to
  54656. ** sqlite3_backup_finish(). */
  54657. sqlite3_free(p);
  54658. }
  54659. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  54660. return rc;
  54661. }
  54662. /*
  54663. ** Return the number of pages still to be backed up as of the most recent
  54664. ** call to sqlite3_backup_step().
  54665. */
  54666. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  54667. return p->nRemaining;
  54668. }
  54669. /*
  54670. ** Return the total number of pages in the source database as of the most
  54671. ** recent call to sqlite3_backup_step().
  54672. */
  54673. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  54674. return p->nPagecount;
  54675. }
  54676. /*
  54677. ** This function is called after the contents of page iPage of the
  54678. ** source database have been modified. If page iPage has already been
  54679. ** copied into the destination database, then the data written to the
  54680. ** destination is now invalidated. The destination copy of iPage needs
  54681. ** to be updated with the new data before the backup operation is
  54682. ** complete.
  54683. **
  54684. ** It is assumed that the mutex associated with the BtShared object
  54685. ** corresponding to the source database is held when this function is
  54686. ** called.
  54687. */
  54688. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  54689. sqlite3_backup *p; /* Iterator variable */
  54690. for(p=pBackup; p; p=p->pNext){
  54691. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  54692. if( !isFatalError(p->rc) && iPage<p->iNext ){
  54693. /* The backup process p has already copied page iPage. But now it
  54694. ** has been modified by a transaction on the source pager. Copy
  54695. ** the new data into the backup.
  54696. */
  54697. int rc;
  54698. assert( p->pDestDb );
  54699. sqlite3_mutex_enter(p->pDestDb->mutex);
  54700. rc = backupOnePage(p, iPage, aData, 1);
  54701. sqlite3_mutex_leave(p->pDestDb->mutex);
  54702. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  54703. if( rc!=SQLITE_OK ){
  54704. p->rc = rc;
  54705. }
  54706. }
  54707. }
  54708. }
  54709. /*
  54710. ** Restart the backup process. This is called when the pager layer
  54711. ** detects that the database has been modified by an external database
  54712. ** connection. In this case there is no way of knowing which of the
  54713. ** pages that have been copied into the destination database are still
  54714. ** valid and which are not, so the entire process needs to be restarted.
  54715. **
  54716. ** It is assumed that the mutex associated with the BtShared object
  54717. ** corresponding to the source database is held when this function is
  54718. ** called.
  54719. */
  54720. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  54721. sqlite3_backup *p; /* Iterator variable */
  54722. for(p=pBackup; p; p=p->pNext){
  54723. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  54724. p->iNext = 1;
  54725. }
  54726. }
  54727. #ifndef SQLITE_OMIT_VACUUM
  54728. /*
  54729. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  54730. ** must be active for both files.
  54731. **
  54732. ** The size of file pTo may be reduced by this operation. If anything
  54733. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  54734. ** transaction is committed before returning.
  54735. */
  54736. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  54737. int rc;
  54738. sqlite3_file *pFd; /* File descriptor for database pTo */
  54739. sqlite3_backup b;
  54740. sqlite3BtreeEnter(pTo);
  54741. sqlite3BtreeEnter(pFrom);
  54742. assert( sqlite3BtreeIsInTrans(pTo) );
  54743. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  54744. if( pFd->pMethods ){
  54745. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  54746. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  54747. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  54748. if( rc ) goto copy_finished;
  54749. }
  54750. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  54751. ** to 0. This is used by the implementations of sqlite3_backup_step()
  54752. ** and sqlite3_backup_finish() to detect that they are being called
  54753. ** from this function, not directly by the user.
  54754. */
  54755. memset(&b, 0, sizeof(b));
  54756. b.pSrcDb = pFrom->db;
  54757. b.pSrc = pFrom;
  54758. b.pDest = pTo;
  54759. b.iNext = 1;
  54760. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  54761. ** file. By passing this as the number of pages to copy to
  54762. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  54763. ** within a single call (unless an error occurs). The assert() statement
  54764. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  54765. ** or an error code.
  54766. */
  54767. sqlite3_backup_step(&b, 0x7FFFFFFF);
  54768. assert( b.rc!=SQLITE_OK );
  54769. rc = sqlite3_backup_finish(&b);
  54770. if( rc==SQLITE_OK ){
  54771. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  54772. }else{
  54773. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  54774. }
  54775. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  54776. copy_finished:
  54777. sqlite3BtreeLeave(pFrom);
  54778. sqlite3BtreeLeave(pTo);
  54779. return rc;
  54780. }
  54781. #endif /* SQLITE_OMIT_VACUUM */
  54782. /************** End of backup.c **********************************************/
  54783. /************** Begin file vdbemem.c *****************************************/
  54784. /*
  54785. ** 2004 May 26
  54786. **
  54787. ** The author disclaims copyright to this source code. In place of
  54788. ** a legal notice, here is a blessing:
  54789. **
  54790. ** May you do good and not evil.
  54791. ** May you find forgiveness for yourself and forgive others.
  54792. ** May you share freely, never taking more than you give.
  54793. **
  54794. *************************************************************************
  54795. **
  54796. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  54797. ** stores a single value in the VDBE. Mem is an opaque structure visible
  54798. ** only within the VDBE. Interface routines refer to a Mem using the
  54799. ** name sqlite_value
  54800. */
  54801. /*
  54802. ** If pMem is an object with a valid string representation, this routine
  54803. ** ensures the internal encoding for the string representation is
  54804. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  54805. **
  54806. ** If pMem is not a string object, or the encoding of the string
  54807. ** representation is already stored using the requested encoding, then this
  54808. ** routine is a no-op.
  54809. **
  54810. ** SQLITE_OK is returned if the conversion is successful (or not required).
  54811. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  54812. ** between formats.
  54813. */
  54814. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  54815. #ifndef SQLITE_OMIT_UTF16
  54816. int rc;
  54817. #endif
  54818. assert( (pMem->flags&MEM_RowSet)==0 );
  54819. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  54820. || desiredEnc==SQLITE_UTF16BE );
  54821. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  54822. return SQLITE_OK;
  54823. }
  54824. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54825. #ifdef SQLITE_OMIT_UTF16
  54826. return SQLITE_ERROR;
  54827. #else
  54828. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  54829. ** then the encoding of the value may not have changed.
  54830. */
  54831. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  54832. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  54833. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  54834. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  54835. return rc;
  54836. #endif
  54837. }
  54838. /*
  54839. ** Make sure pMem->z points to a writable allocation of at least
  54840. ** n bytes.
  54841. **
  54842. ** If the third argument passed to this function is true, then memory
  54843. ** cell pMem must contain a string or blob. In this case the content is
  54844. ** preserved. Otherwise, if the third parameter to this function is false,
  54845. ** any current string or blob value may be discarded.
  54846. **
  54847. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  54848. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  54849. ** not set, Mem.n is zeroed.
  54850. */
  54851. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  54852. assert( 1 >=
  54853. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  54854. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  54855. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  54856. ((pMem->flags&MEM_Static) ? 1 : 0)
  54857. );
  54858. assert( (pMem->flags&MEM_RowSet)==0 );
  54859. /* If the preserve flag is set to true, then the memory cell must already
  54860. ** contain a valid string or blob value. */
  54861. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  54862. if( n<32 ) n = 32;
  54863. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  54864. if( preserve && pMem->z==pMem->zMalloc ){
  54865. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  54866. preserve = 0;
  54867. }else{
  54868. sqlite3DbFree(pMem->db, pMem->zMalloc);
  54869. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  54870. }
  54871. }
  54872. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  54873. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  54874. }
  54875. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  54876. assert( pMem->xDel!=SQLITE_DYNAMIC );
  54877. pMem->xDel((void *)(pMem->z));
  54878. }
  54879. pMem->z = pMem->zMalloc;
  54880. if( pMem->z==0 ){
  54881. pMem->flags = MEM_Null;
  54882. }else{
  54883. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  54884. }
  54885. pMem->xDel = 0;
  54886. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  54887. }
  54888. /*
  54889. ** Make the given Mem object MEM_Dyn. In other words, make it so
  54890. ** that any TEXT or BLOB content is stored in memory obtained from
  54891. ** malloc(). In this way, we know that the memory is safe to be
  54892. ** overwritten or altered.
  54893. **
  54894. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  54895. */
  54896. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  54897. int f;
  54898. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54899. assert( (pMem->flags&MEM_RowSet)==0 );
  54900. ExpandBlob(pMem);
  54901. f = pMem->flags;
  54902. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  54903. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  54904. return SQLITE_NOMEM;
  54905. }
  54906. pMem->z[pMem->n] = 0;
  54907. pMem->z[pMem->n+1] = 0;
  54908. pMem->flags |= MEM_Term;
  54909. #ifdef SQLITE_DEBUG
  54910. pMem->pScopyFrom = 0;
  54911. #endif
  54912. }
  54913. return SQLITE_OK;
  54914. }
  54915. /*
  54916. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  54917. ** blob stored in dynamically allocated space.
  54918. */
  54919. #ifndef SQLITE_OMIT_INCRBLOB
  54920. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  54921. if( pMem->flags & MEM_Zero ){
  54922. int nByte;
  54923. assert( pMem->flags&MEM_Blob );
  54924. assert( (pMem->flags&MEM_RowSet)==0 );
  54925. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54926. /* Set nByte to the number of bytes required to store the expanded blob. */
  54927. nByte = pMem->n + pMem->u.nZero;
  54928. if( nByte<=0 ){
  54929. nByte = 1;
  54930. }
  54931. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  54932. return SQLITE_NOMEM;
  54933. }
  54934. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  54935. pMem->n += pMem->u.nZero;
  54936. pMem->flags &= ~(MEM_Zero|MEM_Term);
  54937. }
  54938. return SQLITE_OK;
  54939. }
  54940. #endif
  54941. /*
  54942. ** Make sure the given Mem is \u0000 terminated.
  54943. */
  54944. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  54945. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54946. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  54947. return SQLITE_OK; /* Nothing to do */
  54948. }
  54949. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  54950. return SQLITE_NOMEM;
  54951. }
  54952. pMem->z[pMem->n] = 0;
  54953. pMem->z[pMem->n+1] = 0;
  54954. pMem->flags |= MEM_Term;
  54955. return SQLITE_OK;
  54956. }
  54957. /*
  54958. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  54959. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  54960. ** is a no-op.
  54961. **
  54962. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  54963. **
  54964. ** A MEM_Null value will never be passed to this function. This function is
  54965. ** used for converting values to text for returning to the user (i.e. via
  54966. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  54967. ** keys are strings. In the former case a NULL pointer is returned the
  54968. ** user and the later is an internal programming error.
  54969. */
  54970. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  54971. int rc = SQLITE_OK;
  54972. int fg = pMem->flags;
  54973. const int nByte = 32;
  54974. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54975. assert( !(fg&MEM_Zero) );
  54976. assert( !(fg&(MEM_Str|MEM_Blob)) );
  54977. assert( fg&(MEM_Int|MEM_Real) );
  54978. assert( (pMem->flags&MEM_RowSet)==0 );
  54979. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  54980. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  54981. return SQLITE_NOMEM;
  54982. }
  54983. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  54984. ** string representation of the value. Then, if the required encoding
  54985. ** is UTF-16le or UTF-16be do a translation.
  54986. **
  54987. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  54988. */
  54989. if( fg & MEM_Int ){
  54990. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  54991. }else{
  54992. assert( fg & MEM_Real );
  54993. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  54994. }
  54995. pMem->n = sqlite3Strlen30(pMem->z);
  54996. pMem->enc = SQLITE_UTF8;
  54997. pMem->flags |= MEM_Str|MEM_Term;
  54998. sqlite3VdbeChangeEncoding(pMem, enc);
  54999. return rc;
  55000. }
  55001. /*
  55002. ** Memory cell pMem contains the context of an aggregate function.
  55003. ** This routine calls the finalize method for that function. The
  55004. ** result of the aggregate is stored back into pMem.
  55005. **
  55006. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  55007. ** otherwise.
  55008. */
  55009. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  55010. int rc = SQLITE_OK;
  55011. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  55012. sqlite3_context ctx;
  55013. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  55014. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55015. memset(&ctx, 0, sizeof(ctx));
  55016. ctx.s.flags = MEM_Null;
  55017. ctx.s.db = pMem->db;
  55018. ctx.pMem = pMem;
  55019. ctx.pFunc = pFunc;
  55020. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  55021. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  55022. sqlite3DbFree(pMem->db, pMem->zMalloc);
  55023. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  55024. rc = ctx.isError;
  55025. }
  55026. return rc;
  55027. }
  55028. /*
  55029. ** If the memory cell contains a string value that must be freed by
  55030. ** invoking an external callback, free it now. Calling this function
  55031. ** does not free any Mem.zMalloc buffer.
  55032. */
  55033. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  55034. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  55035. if( p->flags&MEM_Agg ){
  55036. sqlite3VdbeMemFinalize(p, p->u.pDef);
  55037. assert( (p->flags & MEM_Agg)==0 );
  55038. sqlite3VdbeMemRelease(p);
  55039. }else if( p->flags&MEM_Dyn && p->xDel ){
  55040. assert( (p->flags&MEM_RowSet)==0 );
  55041. assert( p->xDel!=SQLITE_DYNAMIC );
  55042. p->xDel((void *)p->z);
  55043. p->xDel = 0;
  55044. }else if( p->flags&MEM_RowSet ){
  55045. sqlite3RowSetClear(p->u.pRowSet);
  55046. }else if( p->flags&MEM_Frame ){
  55047. sqlite3VdbeMemSetNull(p);
  55048. }
  55049. }
  55050. /*
  55051. ** Release any memory held by the Mem. This may leave the Mem in an
  55052. ** inconsistent state, for example with (Mem.z==0) and
  55053. ** (Mem.type==SQLITE_TEXT).
  55054. */
  55055. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  55056. VdbeMemRelease(p);
  55057. sqlite3DbFree(p->db, p->zMalloc);
  55058. p->z = 0;
  55059. p->zMalloc = 0;
  55060. p->xDel = 0;
  55061. }
  55062. /*
  55063. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  55064. ** If the double is too large, return 0x8000000000000000.
  55065. **
  55066. ** Most systems appear to do this simply by assigning
  55067. ** variables and without the extra range tests. But
  55068. ** there are reports that windows throws an expection
  55069. ** if the floating point value is out of range. (See ticket #2880.)
  55070. ** Because we do not completely understand the problem, we will
  55071. ** take the conservative approach and always do range tests
  55072. ** before attempting the conversion.
  55073. */
  55074. static i64 doubleToInt64(double r){
  55075. #ifdef SQLITE_OMIT_FLOATING_POINT
  55076. /* When floating-point is omitted, double and int64 are the same thing */
  55077. return r;
  55078. #else
  55079. /*
  55080. ** Many compilers we encounter do not define constants for the
  55081. ** minimum and maximum 64-bit integers, or they define them
  55082. ** inconsistently. And many do not understand the "LL" notation.
  55083. ** So we define our own static constants here using nothing
  55084. ** larger than a 32-bit integer constant.
  55085. */
  55086. static const i64 maxInt = LARGEST_INT64;
  55087. static const i64 minInt = SMALLEST_INT64;
  55088. if( r<(double)minInt ){
  55089. return minInt;
  55090. }else if( r>(double)maxInt ){
  55091. /* minInt is correct here - not maxInt. It turns out that assigning
  55092. ** a very large positive number to an integer results in a very large
  55093. ** negative integer. This makes no sense, but it is what x86 hardware
  55094. ** does so for compatibility we will do the same in software. */
  55095. return minInt;
  55096. }else{
  55097. return (i64)r;
  55098. }
  55099. #endif
  55100. }
  55101. /*
  55102. ** Return some kind of integer value which is the best we can do
  55103. ** at representing the value that *pMem describes as an integer.
  55104. ** If pMem is an integer, then the value is exact. If pMem is
  55105. ** a floating-point then the value returned is the integer part.
  55106. ** If pMem is a string or blob, then we make an attempt to convert
  55107. ** it into a integer and return that. If pMem represents an
  55108. ** an SQL-NULL value, return 0.
  55109. **
  55110. ** If pMem represents a string value, its encoding might be changed.
  55111. */
  55112. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  55113. int flags;
  55114. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55115. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55116. flags = pMem->flags;
  55117. if( flags & MEM_Int ){
  55118. return pMem->u.i;
  55119. }else if( flags & MEM_Real ){
  55120. return doubleToInt64(pMem->r);
  55121. }else if( flags & (MEM_Str|MEM_Blob) ){
  55122. i64 value = 0;
  55123. assert( pMem->z || pMem->n==0 );
  55124. testcase( pMem->z==0 );
  55125. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  55126. return value;
  55127. }else{
  55128. return 0;
  55129. }
  55130. }
  55131. /*
  55132. ** Return the best representation of pMem that we can get into a
  55133. ** double. If pMem is already a double or an integer, return its
  55134. ** value. If it is a string or blob, try to convert it to a double.
  55135. ** If it is a NULL, return 0.0.
  55136. */
  55137. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  55138. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55139. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55140. if( pMem->flags & MEM_Real ){
  55141. return pMem->r;
  55142. }else if( pMem->flags & MEM_Int ){
  55143. return (double)pMem->u.i;
  55144. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  55145. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  55146. double val = (double)0;
  55147. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  55148. return val;
  55149. }else{
  55150. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  55151. return (double)0;
  55152. }
  55153. }
  55154. /*
  55155. ** The MEM structure is already a MEM_Real. Try to also make it a
  55156. ** MEM_Int if we can.
  55157. */
  55158. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  55159. assert( pMem->flags & MEM_Real );
  55160. assert( (pMem->flags & MEM_RowSet)==0 );
  55161. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55162. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55163. pMem->u.i = doubleToInt64(pMem->r);
  55164. /* Only mark the value as an integer if
  55165. **
  55166. ** (1) the round-trip conversion real->int->real is a no-op, and
  55167. ** (2) The integer is neither the largest nor the smallest
  55168. ** possible integer (ticket #3922)
  55169. **
  55170. ** The second and third terms in the following conditional enforces
  55171. ** the second condition under the assumption that addition overflow causes
  55172. ** values to wrap around. On x86 hardware, the third term is always
  55173. ** true and could be omitted. But we leave it in because other
  55174. ** architectures might behave differently.
  55175. */
  55176. if( pMem->r==(double)pMem->u.i
  55177. && pMem->u.i>SMALLEST_INT64
  55178. #if defined(__i486__) || defined(__x86_64__)
  55179. && ALWAYS(pMem->u.i<LARGEST_INT64)
  55180. #else
  55181. && pMem->u.i<LARGEST_INT64
  55182. #endif
  55183. ){
  55184. pMem->flags |= MEM_Int;
  55185. }
  55186. }
  55187. /*
  55188. ** Convert pMem to type integer. Invalidate any prior representations.
  55189. */
  55190. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  55191. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55192. assert( (pMem->flags & MEM_RowSet)==0 );
  55193. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55194. pMem->u.i = sqlite3VdbeIntValue(pMem);
  55195. MemSetTypeFlag(pMem, MEM_Int);
  55196. return SQLITE_OK;
  55197. }
  55198. /*
  55199. ** Convert pMem so that it is of type MEM_Real.
  55200. ** Invalidate any prior representations.
  55201. */
  55202. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  55203. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55204. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55205. pMem->r = sqlite3VdbeRealValue(pMem);
  55206. MemSetTypeFlag(pMem, MEM_Real);
  55207. return SQLITE_OK;
  55208. }
  55209. /*
  55210. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  55211. ** Invalidate any prior representations.
  55212. **
  55213. ** Every effort is made to force the conversion, even if the input
  55214. ** is a string that does not look completely like a number. Convert
  55215. ** as much of the string as we can and ignore the rest.
  55216. */
  55217. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  55218. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  55219. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  55220. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55221. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  55222. MemSetTypeFlag(pMem, MEM_Int);
  55223. }else{
  55224. pMem->r = sqlite3VdbeRealValue(pMem);
  55225. MemSetTypeFlag(pMem, MEM_Real);
  55226. sqlite3VdbeIntegerAffinity(pMem);
  55227. }
  55228. }
  55229. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  55230. pMem->flags &= ~(MEM_Str|MEM_Blob);
  55231. return SQLITE_OK;
  55232. }
  55233. /*
  55234. ** Delete any previous value and set the value stored in *pMem to NULL.
  55235. */
  55236. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  55237. if( pMem->flags & MEM_Frame ){
  55238. VdbeFrame *pFrame = pMem->u.pFrame;
  55239. pFrame->pParent = pFrame->v->pDelFrame;
  55240. pFrame->v->pDelFrame = pFrame;
  55241. }
  55242. if( pMem->flags & MEM_RowSet ){
  55243. sqlite3RowSetClear(pMem->u.pRowSet);
  55244. }
  55245. MemSetTypeFlag(pMem, MEM_Null);
  55246. pMem->type = SQLITE_NULL;
  55247. }
  55248. /*
  55249. ** Delete any previous value and set the value to be a BLOB of length
  55250. ** n containing all zeros.
  55251. */
  55252. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  55253. sqlite3VdbeMemRelease(pMem);
  55254. pMem->flags = MEM_Blob|MEM_Zero;
  55255. pMem->type = SQLITE_BLOB;
  55256. pMem->n = 0;
  55257. if( n<0 ) n = 0;
  55258. pMem->u.nZero = n;
  55259. pMem->enc = SQLITE_UTF8;
  55260. #ifdef SQLITE_OMIT_INCRBLOB
  55261. sqlite3VdbeMemGrow(pMem, n, 0);
  55262. if( pMem->z ){
  55263. pMem->n = n;
  55264. memset(pMem->z, 0, n);
  55265. }
  55266. #endif
  55267. }
  55268. /*
  55269. ** Delete any previous value and set the value stored in *pMem to val,
  55270. ** manifest type INTEGER.
  55271. */
  55272. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  55273. sqlite3VdbeMemRelease(pMem);
  55274. pMem->u.i = val;
  55275. pMem->flags = MEM_Int;
  55276. pMem->type = SQLITE_INTEGER;
  55277. }
  55278. #ifndef SQLITE_OMIT_FLOATING_POINT
  55279. /*
  55280. ** Delete any previous value and set the value stored in *pMem to val,
  55281. ** manifest type REAL.
  55282. */
  55283. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  55284. if( sqlite3IsNaN(val) ){
  55285. sqlite3VdbeMemSetNull(pMem);
  55286. }else{
  55287. sqlite3VdbeMemRelease(pMem);
  55288. pMem->r = val;
  55289. pMem->flags = MEM_Real;
  55290. pMem->type = SQLITE_FLOAT;
  55291. }
  55292. }
  55293. #endif
  55294. /*
  55295. ** Delete any previous value and set the value of pMem to be an
  55296. ** empty boolean index.
  55297. */
  55298. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  55299. sqlite3 *db = pMem->db;
  55300. assert( db!=0 );
  55301. assert( (pMem->flags & MEM_RowSet)==0 );
  55302. sqlite3VdbeMemRelease(pMem);
  55303. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  55304. if( db->mallocFailed ){
  55305. pMem->flags = MEM_Null;
  55306. }else{
  55307. assert( pMem->zMalloc );
  55308. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  55309. sqlite3DbMallocSize(db, pMem->zMalloc));
  55310. assert( pMem->u.pRowSet!=0 );
  55311. pMem->flags = MEM_RowSet;
  55312. }
  55313. }
  55314. /*
  55315. ** Return true if the Mem object contains a TEXT or BLOB that is
  55316. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  55317. */
  55318. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  55319. assert( p->db!=0 );
  55320. if( p->flags & (MEM_Str|MEM_Blob) ){
  55321. int n = p->n;
  55322. if( p->flags & MEM_Zero ){
  55323. n += p->u.nZero;
  55324. }
  55325. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  55326. }
  55327. return 0;
  55328. }
  55329. #ifdef SQLITE_DEBUG
  55330. /*
  55331. ** This routine prepares a memory cell for modication by breaking
  55332. ** its link to a shallow copy and by marking any current shallow
  55333. ** copies of this cell as invalid.
  55334. **
  55335. ** This is used for testing and debugging only - to make sure shallow
  55336. ** copies are not misused.
  55337. */
  55338. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  55339. int i;
  55340. Mem *pX;
  55341. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  55342. if( pX->pScopyFrom==pMem ){
  55343. pX->flags |= MEM_Invalid;
  55344. pX->pScopyFrom = 0;
  55345. }
  55346. }
  55347. pMem->pScopyFrom = 0;
  55348. }
  55349. #endif /* SQLITE_DEBUG */
  55350. /*
  55351. ** Size of struct Mem not including the Mem.zMalloc member.
  55352. */
  55353. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  55354. /*
  55355. ** Make an shallow copy of pFrom into pTo. Prior contents of
  55356. ** pTo are freed. The pFrom->z field is not duplicated. If
  55357. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  55358. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  55359. */
  55360. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  55361. assert( (pFrom->flags & MEM_RowSet)==0 );
  55362. VdbeMemRelease(pTo);
  55363. memcpy(pTo, pFrom, MEMCELLSIZE);
  55364. pTo->xDel = 0;
  55365. if( (pFrom->flags&MEM_Static)==0 ){
  55366. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  55367. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  55368. pTo->flags |= srcType;
  55369. }
  55370. }
  55371. /*
  55372. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  55373. ** freed before the copy is made.
  55374. */
  55375. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  55376. int rc = SQLITE_OK;
  55377. assert( (pFrom->flags & MEM_RowSet)==0 );
  55378. VdbeMemRelease(pTo);
  55379. memcpy(pTo, pFrom, MEMCELLSIZE);
  55380. pTo->flags &= ~MEM_Dyn;
  55381. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  55382. if( 0==(pFrom->flags&MEM_Static) ){
  55383. pTo->flags |= MEM_Ephem;
  55384. rc = sqlite3VdbeMemMakeWriteable(pTo);
  55385. }
  55386. }
  55387. return rc;
  55388. }
  55389. /*
  55390. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  55391. ** freed. If pFrom contains ephemeral data, a copy is made.
  55392. **
  55393. ** pFrom contains an SQL NULL when this routine returns.
  55394. */
  55395. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  55396. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  55397. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  55398. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  55399. sqlite3VdbeMemRelease(pTo);
  55400. memcpy(pTo, pFrom, sizeof(Mem));
  55401. pFrom->flags = MEM_Null;
  55402. pFrom->xDel = 0;
  55403. pFrom->zMalloc = 0;
  55404. }
  55405. /*
  55406. ** Change the value of a Mem to be a string or a BLOB.
  55407. **
  55408. ** The memory management strategy depends on the value of the xDel
  55409. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  55410. ** string is copied into a (possibly existing) buffer managed by the
  55411. ** Mem structure. Otherwise, any existing buffer is freed and the
  55412. ** pointer copied.
  55413. **
  55414. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  55415. ** size limit) then no memory allocation occurs. If the string can be
  55416. ** stored without allocating memory, then it is. If a memory allocation
  55417. ** is required to store the string, then value of pMem is unchanged. In
  55418. ** either case, SQLITE_TOOBIG is returned.
  55419. */
  55420. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  55421. Mem *pMem, /* Memory cell to set to string value */
  55422. const char *z, /* String pointer */
  55423. int n, /* Bytes in string, or negative */
  55424. u8 enc, /* Encoding of z. 0 for BLOBs */
  55425. void (*xDel)(void*) /* Destructor function */
  55426. ){
  55427. int nByte = n; /* New value for pMem->n */
  55428. int iLimit; /* Maximum allowed string or blob size */
  55429. u16 flags = 0; /* New value for pMem->flags */
  55430. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  55431. assert( (pMem->flags & MEM_RowSet)==0 );
  55432. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  55433. if( !z ){
  55434. sqlite3VdbeMemSetNull(pMem);
  55435. return SQLITE_OK;
  55436. }
  55437. if( pMem->db ){
  55438. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  55439. }else{
  55440. iLimit = SQLITE_MAX_LENGTH;
  55441. }
  55442. flags = (enc==0?MEM_Blob:MEM_Str);
  55443. if( nByte<0 ){
  55444. assert( enc!=0 );
  55445. if( enc==SQLITE_UTF8 ){
  55446. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  55447. }else{
  55448. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  55449. }
  55450. flags |= MEM_Term;
  55451. }
  55452. /* The following block sets the new values of Mem.z and Mem.xDel. It
  55453. ** also sets a flag in local variable "flags" to indicate the memory
  55454. ** management (one of MEM_Dyn or MEM_Static).
  55455. */
  55456. if( xDel==SQLITE_TRANSIENT ){
  55457. int nAlloc = nByte;
  55458. if( flags&MEM_Term ){
  55459. nAlloc += (enc==SQLITE_UTF8?1:2);
  55460. }
  55461. if( nByte>iLimit ){
  55462. return SQLITE_TOOBIG;
  55463. }
  55464. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  55465. return SQLITE_NOMEM;
  55466. }
  55467. memcpy(pMem->z, z, nAlloc);
  55468. }else if( xDel==SQLITE_DYNAMIC ){
  55469. sqlite3VdbeMemRelease(pMem);
  55470. pMem->zMalloc = pMem->z = (char *)z;
  55471. pMem->xDel = 0;
  55472. }else{
  55473. sqlite3VdbeMemRelease(pMem);
  55474. pMem->z = (char *)z;
  55475. pMem->xDel = xDel;
  55476. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  55477. }
  55478. pMem->n = nByte;
  55479. pMem->flags = flags;
  55480. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  55481. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  55482. #ifndef SQLITE_OMIT_UTF16
  55483. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  55484. return SQLITE_NOMEM;
  55485. }
  55486. #endif
  55487. if( nByte>iLimit ){
  55488. return SQLITE_TOOBIG;
  55489. }
  55490. return SQLITE_OK;
  55491. }
  55492. /*
  55493. ** Compare the values contained by the two memory cells, returning
  55494. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  55495. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  55496. ** and reals) sorted numerically, followed by text ordered by the collating
  55497. ** sequence pColl and finally blob's ordered by memcmp().
  55498. **
  55499. ** Two NULL values are considered equal by this function.
  55500. */
  55501. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  55502. int rc;
  55503. int f1, f2;
  55504. int combined_flags;
  55505. f1 = pMem1->flags;
  55506. f2 = pMem2->flags;
  55507. combined_flags = f1|f2;
  55508. assert( (combined_flags & MEM_RowSet)==0 );
  55509. /* If one value is NULL, it is less than the other. If both values
  55510. ** are NULL, return 0.
  55511. */
  55512. if( combined_flags&MEM_Null ){
  55513. return (f2&MEM_Null) - (f1&MEM_Null);
  55514. }
  55515. /* If one value is a number and the other is not, the number is less.
  55516. ** If both are numbers, compare as reals if one is a real, or as integers
  55517. ** if both values are integers.
  55518. */
  55519. if( combined_flags&(MEM_Int|MEM_Real) ){
  55520. if( !(f1&(MEM_Int|MEM_Real)) ){
  55521. return 1;
  55522. }
  55523. if( !(f2&(MEM_Int|MEM_Real)) ){
  55524. return -1;
  55525. }
  55526. if( (f1 & f2 & MEM_Int)==0 ){
  55527. double r1, r2;
  55528. if( (f1&MEM_Real)==0 ){
  55529. r1 = (double)pMem1->u.i;
  55530. }else{
  55531. r1 = pMem1->r;
  55532. }
  55533. if( (f2&MEM_Real)==0 ){
  55534. r2 = (double)pMem2->u.i;
  55535. }else{
  55536. r2 = pMem2->r;
  55537. }
  55538. if( r1<r2 ) return -1;
  55539. if( r1>r2 ) return 1;
  55540. return 0;
  55541. }else{
  55542. assert( f1&MEM_Int );
  55543. assert( f2&MEM_Int );
  55544. if( pMem1->u.i < pMem2->u.i ) return -1;
  55545. if( pMem1->u.i > pMem2->u.i ) return 1;
  55546. return 0;
  55547. }
  55548. }
  55549. /* If one value is a string and the other is a blob, the string is less.
  55550. ** If both are strings, compare using the collating functions.
  55551. */
  55552. if( combined_flags&MEM_Str ){
  55553. if( (f1 & MEM_Str)==0 ){
  55554. return 1;
  55555. }
  55556. if( (f2 & MEM_Str)==0 ){
  55557. return -1;
  55558. }
  55559. assert( pMem1->enc==pMem2->enc );
  55560. assert( pMem1->enc==SQLITE_UTF8 ||
  55561. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  55562. /* The collation sequence must be defined at this point, even if
  55563. ** the user deletes the collation sequence after the vdbe program is
  55564. ** compiled (this was not always the case).
  55565. */
  55566. assert( !pColl || pColl->xCmp );
  55567. if( pColl ){
  55568. if( pMem1->enc==pColl->enc ){
  55569. /* The strings are already in the correct encoding. Call the
  55570. ** comparison function directly */
  55571. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  55572. }else{
  55573. const void *v1, *v2;
  55574. int n1, n2;
  55575. Mem c1;
  55576. Mem c2;
  55577. memset(&c1, 0, sizeof(c1));
  55578. memset(&c2, 0, sizeof(c2));
  55579. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  55580. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  55581. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  55582. n1 = v1==0 ? 0 : c1.n;
  55583. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  55584. n2 = v2==0 ? 0 : c2.n;
  55585. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  55586. sqlite3VdbeMemRelease(&c1);
  55587. sqlite3VdbeMemRelease(&c2);
  55588. return rc;
  55589. }
  55590. }
  55591. /* If a NULL pointer was passed as the collate function, fall through
  55592. ** to the blob case and use memcmp(). */
  55593. }
  55594. /* Both values must be blobs. Compare using memcmp(). */
  55595. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  55596. if( rc==0 ){
  55597. rc = pMem1->n - pMem2->n;
  55598. }
  55599. return rc;
  55600. }
  55601. /*
  55602. ** Move data out of a btree key or data field and into a Mem structure.
  55603. ** The data or key is taken from the entry that pCur is currently pointing
  55604. ** to. offset and amt determine what portion of the data or key to retrieve.
  55605. ** key is true to get the key or false to get data. The result is written
  55606. ** into the pMem element.
  55607. **
  55608. ** The pMem structure is assumed to be uninitialized. Any prior content
  55609. ** is overwritten without being freed.
  55610. **
  55611. ** If this routine fails for any reason (malloc returns NULL or unable
  55612. ** to read from the disk) then the pMem is left in an inconsistent state.
  55613. */
  55614. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  55615. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  55616. int offset, /* Offset from the start of data to return bytes from. */
  55617. int amt, /* Number of bytes to return. */
  55618. int key, /* If true, retrieve from the btree key, not data. */
  55619. Mem *pMem /* OUT: Return data in this Mem structure. */
  55620. ){
  55621. char *zData; /* Data from the btree layer */
  55622. int available = 0; /* Number of bytes available on the local btree page */
  55623. int rc = SQLITE_OK; /* Return code */
  55624. assert( sqlite3BtreeCursorIsValid(pCur) );
  55625. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  55626. ** that both the BtShared and database handle mutexes are held. */
  55627. assert( (pMem->flags & MEM_RowSet)==0 );
  55628. if( key ){
  55629. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  55630. }else{
  55631. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  55632. }
  55633. assert( zData!=0 );
  55634. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  55635. sqlite3VdbeMemRelease(pMem);
  55636. pMem->z = &zData[offset];
  55637. pMem->flags = MEM_Blob|MEM_Ephem;
  55638. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  55639. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  55640. pMem->enc = 0;
  55641. pMem->type = SQLITE_BLOB;
  55642. if( key ){
  55643. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  55644. }else{
  55645. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  55646. }
  55647. pMem->z[amt] = 0;
  55648. pMem->z[amt+1] = 0;
  55649. if( rc!=SQLITE_OK ){
  55650. sqlite3VdbeMemRelease(pMem);
  55651. }
  55652. }
  55653. pMem->n = amt;
  55654. return rc;
  55655. }
  55656. /* This function is only available internally, it is not part of the
  55657. ** external API. It works in a similar way to sqlite3_value_text(),
  55658. ** except the data returned is in the encoding specified by the second
  55659. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  55660. ** SQLITE_UTF8.
  55661. **
  55662. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  55663. ** If that is the case, then the result must be aligned on an even byte
  55664. ** boundary.
  55665. */
  55666. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  55667. if( !pVal ) return 0;
  55668. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  55669. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  55670. assert( (pVal->flags & MEM_RowSet)==0 );
  55671. if( pVal->flags&MEM_Null ){
  55672. return 0;
  55673. }
  55674. assert( (MEM_Blob>>3) == MEM_Str );
  55675. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  55676. ExpandBlob(pVal);
  55677. if( pVal->flags&MEM_Str ){
  55678. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  55679. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  55680. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  55681. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  55682. return 0;
  55683. }
  55684. }
  55685. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  55686. }else{
  55687. assert( (pVal->flags&MEM_Blob)==0 );
  55688. sqlite3VdbeMemStringify(pVal, enc);
  55689. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  55690. }
  55691. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  55692. || pVal->db->mallocFailed );
  55693. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  55694. return pVal->z;
  55695. }else{
  55696. return 0;
  55697. }
  55698. }
  55699. /*
  55700. ** Create a new sqlite3_value object.
  55701. */
  55702. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  55703. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  55704. if( p ){
  55705. p->flags = MEM_Null;
  55706. p->type = SQLITE_NULL;
  55707. p->db = db;
  55708. }
  55709. return p;
  55710. }
  55711. /*
  55712. ** Create a new sqlite3_value object, containing the value of pExpr.
  55713. **
  55714. ** This only works for very simple expressions that consist of one constant
  55715. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  55716. ** be converted directly into a value, then the value is allocated and
  55717. ** a pointer written to *ppVal. The caller is responsible for deallocating
  55718. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  55719. ** cannot be converted to a value, then *ppVal is set to NULL.
  55720. */
  55721. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  55722. sqlite3 *db, /* The database connection */
  55723. Expr *pExpr, /* The expression to evaluate */
  55724. u8 enc, /* Encoding to use */
  55725. u8 affinity, /* Affinity to use */
  55726. sqlite3_value **ppVal /* Write the new value here */
  55727. ){
  55728. int op;
  55729. char *zVal = 0;
  55730. sqlite3_value *pVal = 0;
  55731. int negInt = 1;
  55732. const char *zNeg = "";
  55733. if( !pExpr ){
  55734. *ppVal = 0;
  55735. return SQLITE_OK;
  55736. }
  55737. op = pExpr->op;
  55738. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
  55739. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  55740. ** when SQLITE_ENABLE_STAT3 is omitted.
  55741. */
  55742. #ifdef SQLITE_ENABLE_STAT3
  55743. if( op==TK_REGISTER ) op = pExpr->op2;
  55744. #else
  55745. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  55746. #endif
  55747. /* Handle negative integers in a single step. This is needed in the
  55748. ** case when the value is -9223372036854775808.
  55749. */
  55750. if( op==TK_UMINUS
  55751. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  55752. pExpr = pExpr->pLeft;
  55753. op = pExpr->op;
  55754. negInt = -1;
  55755. zNeg = "-";
  55756. }
  55757. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  55758. pVal = sqlite3ValueNew(db);
  55759. if( pVal==0 ) goto no_mem;
  55760. if( ExprHasProperty(pExpr, EP_IntValue) ){
  55761. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  55762. }else{
  55763. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  55764. if( zVal==0 ) goto no_mem;
  55765. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  55766. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  55767. }
  55768. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  55769. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  55770. }else{
  55771. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  55772. }
  55773. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  55774. if( enc!=SQLITE_UTF8 ){
  55775. sqlite3VdbeChangeEncoding(pVal, enc);
  55776. }
  55777. }else if( op==TK_UMINUS ) {
  55778. /* This branch happens for multiple negative signs. Ex: -(-5) */
  55779. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
  55780. sqlite3VdbeMemNumerify(pVal);
  55781. if( pVal->u.i==SMALLEST_INT64 ){
  55782. pVal->flags &= MEM_Int;
  55783. pVal->flags |= MEM_Real;
  55784. pVal->r = (double)LARGEST_INT64;
  55785. }else{
  55786. pVal->u.i = -pVal->u.i;
  55787. }
  55788. pVal->r = -pVal->r;
  55789. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  55790. }
  55791. }else if( op==TK_NULL ){
  55792. pVal = sqlite3ValueNew(db);
  55793. if( pVal==0 ) goto no_mem;
  55794. }
  55795. #ifndef SQLITE_OMIT_BLOB_LITERAL
  55796. else if( op==TK_BLOB ){
  55797. int nVal;
  55798. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  55799. assert( pExpr->u.zToken[1]=='\'' );
  55800. pVal = sqlite3ValueNew(db);
  55801. if( !pVal ) goto no_mem;
  55802. zVal = &pExpr->u.zToken[2];
  55803. nVal = sqlite3Strlen30(zVal)-1;
  55804. assert( zVal[nVal]=='\'' );
  55805. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  55806. 0, SQLITE_DYNAMIC);
  55807. }
  55808. #endif
  55809. if( pVal ){
  55810. sqlite3VdbeMemStoreType(pVal);
  55811. }
  55812. *ppVal = pVal;
  55813. return SQLITE_OK;
  55814. no_mem:
  55815. db->mallocFailed = 1;
  55816. sqlite3DbFree(db, zVal);
  55817. sqlite3ValueFree(pVal);
  55818. *ppVal = 0;
  55819. return SQLITE_NOMEM;
  55820. }
  55821. /*
  55822. ** Change the string value of an sqlite3_value object
  55823. */
  55824. SQLITE_PRIVATE void sqlite3ValueSetStr(
  55825. sqlite3_value *v, /* Value to be set */
  55826. int n, /* Length of string z */
  55827. const void *z, /* Text of the new string */
  55828. u8 enc, /* Encoding to use */
  55829. void (*xDel)(void*) /* Destructor for the string */
  55830. ){
  55831. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  55832. }
  55833. /*
  55834. ** Free an sqlite3_value object
  55835. */
  55836. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  55837. if( !v ) return;
  55838. sqlite3VdbeMemRelease((Mem *)v);
  55839. sqlite3DbFree(((Mem*)v)->db, v);
  55840. }
  55841. /*
  55842. ** Return the number of bytes in the sqlite3_value object assuming
  55843. ** that it uses the encoding "enc"
  55844. */
  55845. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  55846. Mem *p = (Mem*)pVal;
  55847. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  55848. if( p->flags & MEM_Zero ){
  55849. return p->n + p->u.nZero;
  55850. }else{
  55851. return p->n;
  55852. }
  55853. }
  55854. return 0;
  55855. }
  55856. /************** End of vdbemem.c *********************************************/
  55857. /************** Begin file vdbeaux.c *****************************************/
  55858. /*
  55859. ** 2003 September 6
  55860. **
  55861. ** The author disclaims copyright to this source code. In place of
  55862. ** a legal notice, here is a blessing:
  55863. **
  55864. ** May you do good and not evil.
  55865. ** May you find forgiveness for yourself and forgive others.
  55866. ** May you share freely, never taking more than you give.
  55867. **
  55868. *************************************************************************
  55869. ** This file contains code used for creating, destroying, and populating
  55870. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  55871. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  55872. ** But that file was getting too big so this subroutines were split out.
  55873. */
  55874. /*
  55875. ** Create a new virtual database engine.
  55876. */
  55877. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  55878. Vdbe *p;
  55879. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  55880. if( p==0 ) return 0;
  55881. p->db = db;
  55882. if( db->pVdbe ){
  55883. db->pVdbe->pPrev = p;
  55884. }
  55885. p->pNext = db->pVdbe;
  55886. p->pPrev = 0;
  55887. db->pVdbe = p;
  55888. p->magic = VDBE_MAGIC_INIT;
  55889. return p;
  55890. }
  55891. /*
  55892. ** Remember the SQL string for a prepared statement.
  55893. */
  55894. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  55895. assert( isPrepareV2==1 || isPrepareV2==0 );
  55896. if( p==0 ) return;
  55897. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  55898. if( !isPrepareV2 ) return;
  55899. #endif
  55900. assert( p->zSql==0 );
  55901. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  55902. p->isPrepareV2 = (u8)isPrepareV2;
  55903. }
  55904. /*
  55905. ** Return the SQL associated with a prepared statement
  55906. */
  55907. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  55908. Vdbe *p = (Vdbe *)pStmt;
  55909. return (p && p->isPrepareV2) ? p->zSql : 0;
  55910. }
  55911. /*
  55912. ** Swap all content between two VDBE structures.
  55913. */
  55914. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  55915. Vdbe tmp, *pTmp;
  55916. char *zTmp;
  55917. tmp = *pA;
  55918. *pA = *pB;
  55919. *pB = tmp;
  55920. pTmp = pA->pNext;
  55921. pA->pNext = pB->pNext;
  55922. pB->pNext = pTmp;
  55923. pTmp = pA->pPrev;
  55924. pA->pPrev = pB->pPrev;
  55925. pB->pPrev = pTmp;
  55926. zTmp = pA->zSql;
  55927. pA->zSql = pB->zSql;
  55928. pB->zSql = zTmp;
  55929. pB->isPrepareV2 = pA->isPrepareV2;
  55930. }
  55931. #ifdef SQLITE_DEBUG
  55932. /*
  55933. ** Turn tracing on or off
  55934. */
  55935. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  55936. p->trace = trace;
  55937. }
  55938. #endif
  55939. /*
  55940. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  55941. ** it was.
  55942. **
  55943. ** If an out-of-memory error occurs while resizing the array, return
  55944. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  55945. ** unchanged (this is so that any opcodes already allocated can be
  55946. ** correctly deallocated along with the rest of the Vdbe).
  55947. */
  55948. static int growOpArray(Vdbe *p){
  55949. VdbeOp *pNew;
  55950. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  55951. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  55952. if( pNew ){
  55953. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  55954. p->aOp = pNew;
  55955. }
  55956. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  55957. }
  55958. /*
  55959. ** Add a new instruction to the list of instructions current in the
  55960. ** VDBE. Return the address of the new instruction.
  55961. **
  55962. ** Parameters:
  55963. **
  55964. ** p Pointer to the VDBE
  55965. **
  55966. ** op The opcode for this instruction
  55967. **
  55968. ** p1, p2, p3 Operands
  55969. **
  55970. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  55971. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  55972. ** operand.
  55973. */
  55974. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  55975. int i;
  55976. VdbeOp *pOp;
  55977. i = p->nOp;
  55978. assert( p->magic==VDBE_MAGIC_INIT );
  55979. assert( op>0 && op<0xff );
  55980. if( p->nOpAlloc<=i ){
  55981. if( growOpArray(p) ){
  55982. return 1;
  55983. }
  55984. }
  55985. p->nOp++;
  55986. pOp = &p->aOp[i];
  55987. pOp->opcode = (u8)op;
  55988. pOp->p5 = 0;
  55989. pOp->p1 = p1;
  55990. pOp->p2 = p2;
  55991. pOp->p3 = p3;
  55992. pOp->p4.p = 0;
  55993. pOp->p4type = P4_NOTUSED;
  55994. #ifdef SQLITE_DEBUG
  55995. pOp->zComment = 0;
  55996. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  55997. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  55998. }
  55999. #endif
  56000. #ifdef VDBE_PROFILE
  56001. pOp->cycles = 0;
  56002. pOp->cnt = 0;
  56003. #endif
  56004. return i;
  56005. }
  56006. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  56007. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  56008. }
  56009. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  56010. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  56011. }
  56012. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  56013. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  56014. }
  56015. /*
  56016. ** Add an opcode that includes the p4 value as a pointer.
  56017. */
  56018. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  56019. Vdbe *p, /* Add the opcode to this VM */
  56020. int op, /* The new opcode */
  56021. int p1, /* The P1 operand */
  56022. int p2, /* The P2 operand */
  56023. int p3, /* The P3 operand */
  56024. const char *zP4, /* The P4 operand */
  56025. int p4type /* P4 operand type */
  56026. ){
  56027. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  56028. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  56029. return addr;
  56030. }
  56031. /*
  56032. ** Add an OP_ParseSchema opcode. This routine is broken out from
  56033. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  56034. ** as having been used.
  56035. **
  56036. ** The zWhere string must have been obtained from sqlite3_malloc().
  56037. ** This routine will take ownership of the allocated memory.
  56038. */
  56039. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  56040. int j;
  56041. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  56042. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  56043. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  56044. }
  56045. /*
  56046. ** Add an opcode that includes the p4 value as an integer.
  56047. */
  56048. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  56049. Vdbe *p, /* Add the opcode to this VM */
  56050. int op, /* The new opcode */
  56051. int p1, /* The P1 operand */
  56052. int p2, /* The P2 operand */
  56053. int p3, /* The P3 operand */
  56054. int p4 /* The P4 operand as an integer */
  56055. ){
  56056. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  56057. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  56058. return addr;
  56059. }
  56060. /*
  56061. ** Create a new symbolic label for an instruction that has yet to be
  56062. ** coded. The symbolic label is really just a negative number. The
  56063. ** label can be used as the P2 value of an operation. Later, when
  56064. ** the label is resolved to a specific address, the VDBE will scan
  56065. ** through its operation list and change all values of P2 which match
  56066. ** the label into the resolved address.
  56067. **
  56068. ** The VDBE knows that a P2 value is a label because labels are
  56069. ** always negative and P2 values are suppose to be non-negative.
  56070. ** Hence, a negative P2 value is a label that has yet to be resolved.
  56071. **
  56072. ** Zero is returned if a malloc() fails.
  56073. */
  56074. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  56075. int i = p->nLabel++;
  56076. assert( p->magic==VDBE_MAGIC_INIT );
  56077. if( (i & (i-1))==0 ){
  56078. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  56079. (i*2+1)*sizeof(p->aLabel[0]));
  56080. }
  56081. if( p->aLabel ){
  56082. p->aLabel[i] = -1;
  56083. }
  56084. return -1-i;
  56085. }
  56086. /*
  56087. ** Resolve label "x" to be the address of the next instruction to
  56088. ** be inserted. The parameter "x" must have been obtained from
  56089. ** a prior call to sqlite3VdbeMakeLabel().
  56090. */
  56091. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  56092. int j = -1-x;
  56093. assert( p->magic==VDBE_MAGIC_INIT );
  56094. assert( j>=0 && j<p->nLabel );
  56095. if( p->aLabel ){
  56096. p->aLabel[j] = p->nOp;
  56097. }
  56098. }
  56099. /*
  56100. ** Mark the VDBE as one that can only be run one time.
  56101. */
  56102. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  56103. p->runOnlyOnce = 1;
  56104. }
  56105. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  56106. /*
  56107. ** The following type and function are used to iterate through all opcodes
  56108. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  56109. ** invoke directly or indirectly. It should be used as follows:
  56110. **
  56111. ** Op *pOp;
  56112. ** VdbeOpIter sIter;
  56113. **
  56114. ** memset(&sIter, 0, sizeof(sIter));
  56115. ** sIter.v = v; // v is of type Vdbe*
  56116. ** while( (pOp = opIterNext(&sIter)) ){
  56117. ** // Do something with pOp
  56118. ** }
  56119. ** sqlite3DbFree(v->db, sIter.apSub);
  56120. **
  56121. */
  56122. typedef struct VdbeOpIter VdbeOpIter;
  56123. struct VdbeOpIter {
  56124. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  56125. SubProgram **apSub; /* Array of subprograms */
  56126. int nSub; /* Number of entries in apSub */
  56127. int iAddr; /* Address of next instruction to return */
  56128. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  56129. };
  56130. static Op *opIterNext(VdbeOpIter *p){
  56131. Vdbe *v = p->v;
  56132. Op *pRet = 0;
  56133. Op *aOp;
  56134. int nOp;
  56135. if( p->iSub<=p->nSub ){
  56136. if( p->iSub==0 ){
  56137. aOp = v->aOp;
  56138. nOp = v->nOp;
  56139. }else{
  56140. aOp = p->apSub[p->iSub-1]->aOp;
  56141. nOp = p->apSub[p->iSub-1]->nOp;
  56142. }
  56143. assert( p->iAddr<nOp );
  56144. pRet = &aOp[p->iAddr];
  56145. p->iAddr++;
  56146. if( p->iAddr==nOp ){
  56147. p->iSub++;
  56148. p->iAddr = 0;
  56149. }
  56150. if( pRet->p4type==P4_SUBPROGRAM ){
  56151. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  56152. int j;
  56153. for(j=0; j<p->nSub; j++){
  56154. if( p->apSub[j]==pRet->p4.pProgram ) break;
  56155. }
  56156. if( j==p->nSub ){
  56157. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  56158. if( !p->apSub ){
  56159. pRet = 0;
  56160. }else{
  56161. p->apSub[p->nSub++] = pRet->p4.pProgram;
  56162. }
  56163. }
  56164. }
  56165. }
  56166. return pRet;
  56167. }
  56168. /*
  56169. ** Check if the program stored in the VM associated with pParse may
  56170. ** throw an ABORT exception (causing the statement, but not entire transaction
  56171. ** to be rolled back). This condition is true if the main program or any
  56172. ** sub-programs contains any of the following:
  56173. **
  56174. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  56175. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  56176. ** * OP_Destroy
  56177. ** * OP_VUpdate
  56178. ** * OP_VRename
  56179. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  56180. **
  56181. ** Then check that the value of Parse.mayAbort is true if an
  56182. ** ABORT may be thrown, or false otherwise. Return true if it does
  56183. ** match, or false otherwise. This function is intended to be used as
  56184. ** part of an assert statement in the compiler. Similar to:
  56185. **
  56186. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  56187. */
  56188. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  56189. int hasAbort = 0;
  56190. Op *pOp;
  56191. VdbeOpIter sIter;
  56192. memset(&sIter, 0, sizeof(sIter));
  56193. sIter.v = v;
  56194. while( (pOp = opIterNext(&sIter))!=0 ){
  56195. int opcode = pOp->opcode;
  56196. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  56197. #ifndef SQLITE_OMIT_FOREIGN_KEY
  56198. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  56199. #endif
  56200. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  56201. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  56202. ){
  56203. hasAbort = 1;
  56204. break;
  56205. }
  56206. }
  56207. sqlite3DbFree(v->db, sIter.apSub);
  56208. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  56209. ** If malloc failed, then the while() loop above may not have iterated
  56210. ** through all opcodes and hasAbort may be set incorrectly. Return
  56211. ** true for this case to prevent the assert() in the callers frame
  56212. ** from failing. */
  56213. return ( v->db->mallocFailed || hasAbort==mayAbort );
  56214. }
  56215. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  56216. /*
  56217. ** Loop through the program looking for P2 values that are negative
  56218. ** on jump instructions. Each such value is a label. Resolve the
  56219. ** label by setting the P2 value to its correct non-zero value.
  56220. **
  56221. ** This routine is called once after all opcodes have been inserted.
  56222. **
  56223. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  56224. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  56225. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  56226. **
  56227. ** The Op.opflags field is set on all opcodes.
  56228. */
  56229. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  56230. int i;
  56231. int nMaxArgs = *pMaxFuncArgs;
  56232. Op *pOp;
  56233. int *aLabel = p->aLabel;
  56234. p->readOnly = 1;
  56235. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  56236. u8 opcode = pOp->opcode;
  56237. pOp->opflags = sqlite3OpcodeProperty[opcode];
  56238. if( opcode==OP_Function || opcode==OP_AggStep ){
  56239. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  56240. }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
  56241. p->readOnly = 0;
  56242. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56243. }else if( opcode==OP_VUpdate ){
  56244. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  56245. }else if( opcode==OP_VFilter ){
  56246. int n;
  56247. assert( p->nOp - i >= 3 );
  56248. assert( pOp[-1].opcode==OP_Integer );
  56249. n = pOp[-1].p1;
  56250. if( n>nMaxArgs ) nMaxArgs = n;
  56251. #endif
  56252. }else if( opcode==OP_Next || opcode==OP_SorterNext ){
  56253. pOp->p4.xAdvance = sqlite3BtreeNext;
  56254. pOp->p4type = P4_ADVANCE;
  56255. }else if( opcode==OP_Prev ){
  56256. pOp->p4.xAdvance = sqlite3BtreePrevious;
  56257. pOp->p4type = P4_ADVANCE;
  56258. }
  56259. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  56260. assert( -1-pOp->p2<p->nLabel );
  56261. pOp->p2 = aLabel[-1-pOp->p2];
  56262. }
  56263. }
  56264. sqlite3DbFree(p->db, p->aLabel);
  56265. p->aLabel = 0;
  56266. *pMaxFuncArgs = nMaxArgs;
  56267. }
  56268. /*
  56269. ** Return the address of the next instruction to be inserted.
  56270. */
  56271. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  56272. assert( p->magic==VDBE_MAGIC_INIT );
  56273. return p->nOp;
  56274. }
  56275. /*
  56276. ** This function returns a pointer to the array of opcodes associated with
  56277. ** the Vdbe passed as the first argument. It is the callers responsibility
  56278. ** to arrange for the returned array to be eventually freed using the
  56279. ** vdbeFreeOpArray() function.
  56280. **
  56281. ** Before returning, *pnOp is set to the number of entries in the returned
  56282. ** array. Also, *pnMaxArg is set to the larger of its current value and
  56283. ** the number of entries in the Vdbe.apArg[] array required to execute the
  56284. ** returned program.
  56285. */
  56286. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  56287. VdbeOp *aOp = p->aOp;
  56288. assert( aOp && !p->db->mallocFailed );
  56289. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  56290. assert( p->btreeMask==0 );
  56291. resolveP2Values(p, pnMaxArg);
  56292. *pnOp = p->nOp;
  56293. p->aOp = 0;
  56294. return aOp;
  56295. }
  56296. /*
  56297. ** Add a whole list of operations to the operation stack. Return the
  56298. ** address of the first operation added.
  56299. */
  56300. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  56301. int addr;
  56302. assert( p->magic==VDBE_MAGIC_INIT );
  56303. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  56304. return 0;
  56305. }
  56306. addr = p->nOp;
  56307. if( ALWAYS(nOp>0) ){
  56308. int i;
  56309. VdbeOpList const *pIn = aOp;
  56310. for(i=0; i<nOp; i++, pIn++){
  56311. int p2 = pIn->p2;
  56312. VdbeOp *pOut = &p->aOp[i+addr];
  56313. pOut->opcode = pIn->opcode;
  56314. pOut->p1 = pIn->p1;
  56315. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  56316. pOut->p2 = addr + ADDR(p2);
  56317. }else{
  56318. pOut->p2 = p2;
  56319. }
  56320. pOut->p3 = pIn->p3;
  56321. pOut->p4type = P4_NOTUSED;
  56322. pOut->p4.p = 0;
  56323. pOut->p5 = 0;
  56324. #ifdef SQLITE_DEBUG
  56325. pOut->zComment = 0;
  56326. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  56327. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  56328. }
  56329. #endif
  56330. }
  56331. p->nOp += nOp;
  56332. }
  56333. return addr;
  56334. }
  56335. /*
  56336. ** Change the value of the P1 operand for a specific instruction.
  56337. ** This routine is useful when a large program is loaded from a
  56338. ** static array using sqlite3VdbeAddOpList but we want to make a
  56339. ** few minor changes to the program.
  56340. */
  56341. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  56342. assert( p!=0 );
  56343. if( ((u32)p->nOp)>addr ){
  56344. p->aOp[addr].p1 = val;
  56345. }
  56346. }
  56347. /*
  56348. ** Change the value of the P2 operand for a specific instruction.
  56349. ** This routine is useful for setting a jump destination.
  56350. */
  56351. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  56352. assert( p!=0 );
  56353. if( ((u32)p->nOp)>addr ){
  56354. p->aOp[addr].p2 = val;
  56355. }
  56356. }
  56357. /*
  56358. ** Change the value of the P3 operand for a specific instruction.
  56359. */
  56360. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  56361. assert( p!=0 );
  56362. if( ((u32)p->nOp)>addr ){
  56363. p->aOp[addr].p3 = val;
  56364. }
  56365. }
  56366. /*
  56367. ** Change the value of the P5 operand for the most recently
  56368. ** added operation.
  56369. */
  56370. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  56371. assert( p!=0 );
  56372. if( p->aOp ){
  56373. assert( p->nOp>0 );
  56374. p->aOp[p->nOp-1].p5 = val;
  56375. }
  56376. }
  56377. /*
  56378. ** Change the P2 operand of instruction addr so that it points to
  56379. ** the address of the next instruction to be coded.
  56380. */
  56381. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  56382. assert( addr>=0 || p->db->mallocFailed );
  56383. if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  56384. }
  56385. /*
  56386. ** If the input FuncDef structure is ephemeral, then free it. If
  56387. ** the FuncDef is not ephermal, then do nothing.
  56388. */
  56389. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  56390. if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
  56391. sqlite3DbFree(db, pDef);
  56392. }
  56393. }
  56394. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  56395. /*
  56396. ** Delete a P4 value if necessary.
  56397. */
  56398. static void freeP4(sqlite3 *db, int p4type, void *p4){
  56399. if( p4 ){
  56400. assert( db );
  56401. switch( p4type ){
  56402. case P4_REAL:
  56403. case P4_INT64:
  56404. case P4_DYNAMIC:
  56405. case P4_KEYINFO:
  56406. case P4_INTARRAY:
  56407. case P4_KEYINFO_HANDOFF: {
  56408. sqlite3DbFree(db, p4);
  56409. break;
  56410. }
  56411. case P4_MPRINTF: {
  56412. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  56413. break;
  56414. }
  56415. case P4_VDBEFUNC: {
  56416. VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
  56417. freeEphemeralFunction(db, pVdbeFunc->pFunc);
  56418. if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
  56419. sqlite3DbFree(db, pVdbeFunc);
  56420. break;
  56421. }
  56422. case P4_FUNCDEF: {
  56423. freeEphemeralFunction(db, (FuncDef*)p4);
  56424. break;
  56425. }
  56426. case P4_MEM: {
  56427. if( db->pnBytesFreed==0 ){
  56428. sqlite3ValueFree((sqlite3_value*)p4);
  56429. }else{
  56430. Mem *p = (Mem*)p4;
  56431. sqlite3DbFree(db, p->zMalloc);
  56432. sqlite3DbFree(db, p);
  56433. }
  56434. break;
  56435. }
  56436. case P4_VTAB : {
  56437. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  56438. break;
  56439. }
  56440. }
  56441. }
  56442. }
  56443. /*
  56444. ** Free the space allocated for aOp and any p4 values allocated for the
  56445. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  56446. ** nOp entries.
  56447. */
  56448. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  56449. if( aOp ){
  56450. Op *pOp;
  56451. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  56452. freeP4(db, pOp->p4type, pOp->p4.p);
  56453. #ifdef SQLITE_DEBUG
  56454. sqlite3DbFree(db, pOp->zComment);
  56455. #endif
  56456. }
  56457. }
  56458. sqlite3DbFree(db, aOp);
  56459. }
  56460. /*
  56461. ** Link the SubProgram object passed as the second argument into the linked
  56462. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  56463. ** objects when the VM is no longer required.
  56464. */
  56465. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  56466. p->pNext = pVdbe->pProgram;
  56467. pVdbe->pProgram = p;
  56468. }
  56469. /*
  56470. ** Change the opcode at addr into OP_Noop
  56471. */
  56472. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  56473. if( p->aOp ){
  56474. VdbeOp *pOp = &p->aOp[addr];
  56475. sqlite3 *db = p->db;
  56476. freeP4(db, pOp->p4type, pOp->p4.p);
  56477. memset(pOp, 0, sizeof(pOp[0]));
  56478. pOp->opcode = OP_Noop;
  56479. }
  56480. }
  56481. /*
  56482. ** Change the value of the P4 operand for a specific instruction.
  56483. ** This routine is useful when a large program is loaded from a
  56484. ** static array using sqlite3VdbeAddOpList but we want to make a
  56485. ** few minor changes to the program.
  56486. **
  56487. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  56488. ** the string is made into memory obtained from sqlite3_malloc().
  56489. ** A value of n==0 means copy bytes of zP4 up to and including the
  56490. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  56491. **
  56492. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  56493. ** A copy is made of the KeyInfo structure into memory obtained from
  56494. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  56495. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  56496. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  56497. ** caller should not free the allocation, it will be freed when the Vdbe is
  56498. ** finalized.
  56499. **
  56500. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  56501. ** to a string or structure that is guaranteed to exist for the lifetime of
  56502. ** the Vdbe. In these cases we can just copy the pointer.
  56503. **
  56504. ** If addr<0 then change P4 on the most recently inserted instruction.
  56505. */
  56506. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  56507. Op *pOp;
  56508. sqlite3 *db;
  56509. assert( p!=0 );
  56510. db = p->db;
  56511. assert( p->magic==VDBE_MAGIC_INIT );
  56512. if( p->aOp==0 || db->mallocFailed ){
  56513. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  56514. freeP4(db, n, (void*)*(char**)&zP4);
  56515. }
  56516. return;
  56517. }
  56518. assert( p->nOp>0 );
  56519. assert( addr<p->nOp );
  56520. if( addr<0 ){
  56521. addr = p->nOp - 1;
  56522. }
  56523. pOp = &p->aOp[addr];
  56524. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  56525. freeP4(db, pOp->p4type, pOp->p4.p);
  56526. pOp->p4.p = 0;
  56527. if( n==P4_INT32 ){
  56528. /* Note: this cast is safe, because the origin data point was an int
  56529. ** that was cast to a (const char *). */
  56530. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  56531. pOp->p4type = P4_INT32;
  56532. }else if( zP4==0 ){
  56533. pOp->p4.p = 0;
  56534. pOp->p4type = P4_NOTUSED;
  56535. }else if( n==P4_KEYINFO ){
  56536. KeyInfo *pKeyInfo;
  56537. int nField, nByte;
  56538. nField = ((KeyInfo*)zP4)->nField;
  56539. nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
  56540. pKeyInfo = sqlite3DbMallocRaw(0, nByte);
  56541. pOp->p4.pKeyInfo = pKeyInfo;
  56542. if( pKeyInfo ){
  56543. u8 *aSortOrder;
  56544. memcpy((char*)pKeyInfo, zP4, nByte - nField);
  56545. aSortOrder = pKeyInfo->aSortOrder;
  56546. assert( aSortOrder!=0 );
  56547. pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
  56548. memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
  56549. pOp->p4type = P4_KEYINFO;
  56550. }else{
  56551. p->db->mallocFailed = 1;
  56552. pOp->p4type = P4_NOTUSED;
  56553. }
  56554. }else if( n==P4_KEYINFO_HANDOFF ){
  56555. pOp->p4.p = (void*)zP4;
  56556. pOp->p4type = P4_KEYINFO;
  56557. }else if( n==P4_VTAB ){
  56558. pOp->p4.p = (void*)zP4;
  56559. pOp->p4type = P4_VTAB;
  56560. sqlite3VtabLock((VTable *)zP4);
  56561. assert( ((VTable *)zP4)->db==p->db );
  56562. }else if( n<0 ){
  56563. pOp->p4.p = (void*)zP4;
  56564. pOp->p4type = (signed char)n;
  56565. }else{
  56566. if( n==0 ) n = sqlite3Strlen30(zP4);
  56567. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  56568. pOp->p4type = P4_DYNAMIC;
  56569. }
  56570. }
  56571. #ifndef NDEBUG
  56572. /*
  56573. ** Change the comment on the most recently coded instruction. Or
  56574. ** insert a No-op and add the comment to that new instruction. This
  56575. ** makes the code easier to read during debugging. None of this happens
  56576. ** in a production build.
  56577. */
  56578. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  56579. assert( p->nOp>0 || p->aOp==0 );
  56580. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  56581. if( p->nOp ){
  56582. assert( p->aOp );
  56583. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  56584. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  56585. }
  56586. }
  56587. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  56588. va_list ap;
  56589. if( p ){
  56590. va_start(ap, zFormat);
  56591. vdbeVComment(p, zFormat, ap);
  56592. va_end(ap);
  56593. }
  56594. }
  56595. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  56596. va_list ap;
  56597. if( p ){
  56598. sqlite3VdbeAddOp0(p, OP_Noop);
  56599. va_start(ap, zFormat);
  56600. vdbeVComment(p, zFormat, ap);
  56601. va_end(ap);
  56602. }
  56603. }
  56604. #endif /* NDEBUG */
  56605. /*
  56606. ** Return the opcode for a given address. If the address is -1, then
  56607. ** return the most recently inserted opcode.
  56608. **
  56609. ** If a memory allocation error has occurred prior to the calling of this
  56610. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  56611. ** is readable but not writable, though it is cast to a writable value.
  56612. ** The return of a dummy opcode allows the call to continue functioning
  56613. ** after a OOM fault without having to check to see if the return from
  56614. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  56615. ** dummy will never be written to. This is verified by code inspection and
  56616. ** by running with Valgrind.
  56617. **
  56618. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  56619. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  56620. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  56621. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  56622. ** having to double-check to make sure that the result is non-negative. But
  56623. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  56624. ** check the value of p->nOp-1 before continuing.
  56625. */
  56626. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  56627. /* C89 specifies that the constant "dummy" will be initialized to all
  56628. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  56629. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  56630. assert( p->magic==VDBE_MAGIC_INIT );
  56631. if( addr<0 ){
  56632. #ifdef SQLITE_OMIT_TRACE
  56633. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  56634. #endif
  56635. addr = p->nOp - 1;
  56636. }
  56637. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  56638. if( p->db->mallocFailed ){
  56639. return (VdbeOp*)&dummy;
  56640. }else{
  56641. return &p->aOp[addr];
  56642. }
  56643. }
  56644. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  56645. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  56646. /*
  56647. ** Compute a string that describes the P4 parameter for an opcode.
  56648. ** Use zTemp for any required temporary buffer space.
  56649. */
  56650. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  56651. char *zP4 = zTemp;
  56652. assert( nTemp>=20 );
  56653. switch( pOp->p4type ){
  56654. case P4_KEYINFO_STATIC:
  56655. case P4_KEYINFO: {
  56656. int i, j;
  56657. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  56658. assert( pKeyInfo->aSortOrder!=0 );
  56659. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  56660. i = sqlite3Strlen30(zTemp);
  56661. for(j=0; j<pKeyInfo->nField; j++){
  56662. CollSeq *pColl = pKeyInfo->aColl[j];
  56663. const char *zColl = pColl ? pColl->zName : "nil";
  56664. int n = sqlite3Strlen30(zColl);
  56665. if( i+n>nTemp-6 ){
  56666. memcpy(&zTemp[i],",...",4);
  56667. break;
  56668. }
  56669. zTemp[i++] = ',';
  56670. if( pKeyInfo->aSortOrder[j] ){
  56671. zTemp[i++] = '-';
  56672. }
  56673. memcpy(&zTemp[i], zColl, n+1);
  56674. i += n;
  56675. }
  56676. zTemp[i++] = ')';
  56677. zTemp[i] = 0;
  56678. assert( i<nTemp );
  56679. break;
  56680. }
  56681. case P4_COLLSEQ: {
  56682. CollSeq *pColl = pOp->p4.pColl;
  56683. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  56684. break;
  56685. }
  56686. case P4_FUNCDEF: {
  56687. FuncDef *pDef = pOp->p4.pFunc;
  56688. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  56689. break;
  56690. }
  56691. case P4_INT64: {
  56692. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  56693. break;
  56694. }
  56695. case P4_INT32: {
  56696. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  56697. break;
  56698. }
  56699. case P4_REAL: {
  56700. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  56701. break;
  56702. }
  56703. case P4_MEM: {
  56704. Mem *pMem = pOp->p4.pMem;
  56705. if( pMem->flags & MEM_Str ){
  56706. zP4 = pMem->z;
  56707. }else if( pMem->flags & MEM_Int ){
  56708. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  56709. }else if( pMem->flags & MEM_Real ){
  56710. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  56711. }else if( pMem->flags & MEM_Null ){
  56712. sqlite3_snprintf(nTemp, zTemp, "NULL");
  56713. }else{
  56714. assert( pMem->flags & MEM_Blob );
  56715. zP4 = "(blob)";
  56716. }
  56717. break;
  56718. }
  56719. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56720. case P4_VTAB: {
  56721. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  56722. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  56723. break;
  56724. }
  56725. #endif
  56726. case P4_INTARRAY: {
  56727. sqlite3_snprintf(nTemp, zTemp, "intarray");
  56728. break;
  56729. }
  56730. case P4_SUBPROGRAM: {
  56731. sqlite3_snprintf(nTemp, zTemp, "program");
  56732. break;
  56733. }
  56734. case P4_ADVANCE: {
  56735. zTemp[0] = 0;
  56736. break;
  56737. }
  56738. default: {
  56739. zP4 = pOp->p4.z;
  56740. if( zP4==0 ){
  56741. zP4 = zTemp;
  56742. zTemp[0] = 0;
  56743. }
  56744. }
  56745. }
  56746. assert( zP4!=0 );
  56747. return zP4;
  56748. }
  56749. #endif
  56750. /*
  56751. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  56752. **
  56753. ** The prepared statements need to know in advance the complete set of
  56754. ** attached databases that will be use. A mask of these databases
  56755. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  56756. ** p->btreeMask of databases that will require a lock.
  56757. */
  56758. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  56759. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  56760. assert( i<(int)sizeof(p->btreeMask)*8 );
  56761. p->btreeMask |= ((yDbMask)1)<<i;
  56762. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  56763. p->lockMask |= ((yDbMask)1)<<i;
  56764. }
  56765. }
  56766. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  56767. /*
  56768. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  56769. ** this routine obtains the mutex associated with each BtShared structure
  56770. ** that may be accessed by the VM passed as an argument. In doing so it also
  56771. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  56772. ** that the correct busy-handler callback is invoked if required.
  56773. **
  56774. ** If SQLite is not threadsafe but does support shared-cache mode, then
  56775. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  56776. ** of all of BtShared structures accessible via the database handle
  56777. ** associated with the VM.
  56778. **
  56779. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  56780. ** function is a no-op.
  56781. **
  56782. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  56783. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  56784. ** corresponding to btrees that use shared cache. Then the runtime of
  56785. ** this routine is N*N. But as N is rarely more than 1, this should not
  56786. ** be a problem.
  56787. */
  56788. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  56789. int i;
  56790. yDbMask mask;
  56791. sqlite3 *db;
  56792. Db *aDb;
  56793. int nDb;
  56794. if( p->lockMask==0 ) return; /* The common case */
  56795. db = p->db;
  56796. aDb = db->aDb;
  56797. nDb = db->nDb;
  56798. for(i=0, mask=1; i<nDb; i++, mask += mask){
  56799. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  56800. sqlite3BtreeEnter(aDb[i].pBt);
  56801. }
  56802. }
  56803. }
  56804. #endif
  56805. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  56806. /*
  56807. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  56808. */
  56809. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  56810. int i;
  56811. yDbMask mask;
  56812. sqlite3 *db;
  56813. Db *aDb;
  56814. int nDb;
  56815. if( p->lockMask==0 ) return; /* The common case */
  56816. db = p->db;
  56817. aDb = db->aDb;
  56818. nDb = db->nDb;
  56819. for(i=0, mask=1; i<nDb; i++, mask += mask){
  56820. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  56821. sqlite3BtreeLeave(aDb[i].pBt);
  56822. }
  56823. }
  56824. }
  56825. #endif
  56826. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  56827. /*
  56828. ** Print a single opcode. This routine is used for debugging only.
  56829. */
  56830. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  56831. char *zP4;
  56832. char zPtr[50];
  56833. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  56834. if( pOut==0 ) pOut = stdout;
  56835. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  56836. fprintf(pOut, zFormat1, pc,
  56837. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  56838. #ifdef SQLITE_DEBUG
  56839. pOp->zComment ? pOp->zComment : ""
  56840. #else
  56841. ""
  56842. #endif
  56843. );
  56844. fflush(pOut);
  56845. }
  56846. #endif
  56847. /*
  56848. ** Release an array of N Mem elements
  56849. */
  56850. static void releaseMemArray(Mem *p, int N){
  56851. if( p && N ){
  56852. Mem *pEnd;
  56853. sqlite3 *db = p->db;
  56854. u8 malloc_failed = db->mallocFailed;
  56855. if( db->pnBytesFreed ){
  56856. for(pEnd=&p[N]; p<pEnd; p++){
  56857. sqlite3DbFree(db, p->zMalloc);
  56858. }
  56859. return;
  56860. }
  56861. for(pEnd=&p[N]; p<pEnd; p++){
  56862. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  56863. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  56864. ** that takes advantage of the fact that the memory cell value is
  56865. ** being set to NULL after releasing any dynamic resources.
  56866. **
  56867. ** The justification for duplicating code is that according to
  56868. ** callgrind, this causes a certain test case to hit the CPU 4.7
  56869. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  56870. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  56871. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  56872. ** with no indexes using a single prepared INSERT statement, bind()
  56873. ** and reset(). Inserts are grouped into a transaction.
  56874. */
  56875. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  56876. sqlite3VdbeMemRelease(p);
  56877. }else if( p->zMalloc ){
  56878. sqlite3DbFree(db, p->zMalloc);
  56879. p->zMalloc = 0;
  56880. }
  56881. p->flags = MEM_Invalid;
  56882. }
  56883. db->mallocFailed = malloc_failed;
  56884. }
  56885. }
  56886. /*
  56887. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  56888. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  56889. */
  56890. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  56891. int i;
  56892. Mem *aMem = VdbeFrameMem(p);
  56893. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  56894. for(i=0; i<p->nChildCsr; i++){
  56895. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  56896. }
  56897. releaseMemArray(aMem, p->nChildMem);
  56898. sqlite3DbFree(p->v->db, p);
  56899. }
  56900. #ifndef SQLITE_OMIT_EXPLAIN
  56901. /*
  56902. ** Give a listing of the program in the virtual machine.
  56903. **
  56904. ** The interface is the same as sqlite3VdbeExec(). But instead of
  56905. ** running the code, it invokes the callback once for each instruction.
  56906. ** This feature is used to implement "EXPLAIN".
  56907. **
  56908. ** When p->explain==1, each instruction is listed. When
  56909. ** p->explain==2, only OP_Explain instructions are listed and these
  56910. ** are shown in a different format. p->explain==2 is used to implement
  56911. ** EXPLAIN QUERY PLAN.
  56912. **
  56913. ** When p->explain==1, first the main program is listed, then each of
  56914. ** the trigger subprograms are listed one by one.
  56915. */
  56916. SQLITE_PRIVATE int sqlite3VdbeList(
  56917. Vdbe *p /* The VDBE */
  56918. ){
  56919. int nRow; /* Stop when row count reaches this */
  56920. int nSub = 0; /* Number of sub-vdbes seen so far */
  56921. SubProgram **apSub = 0; /* Array of sub-vdbes */
  56922. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  56923. sqlite3 *db = p->db; /* The database connection */
  56924. int i; /* Loop counter */
  56925. int rc = SQLITE_OK; /* Return code */
  56926. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  56927. assert( p->explain );
  56928. assert( p->magic==VDBE_MAGIC_RUN );
  56929. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  56930. /* Even though this opcode does not use dynamic strings for
  56931. ** the result, result columns may become dynamic if the user calls
  56932. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  56933. */
  56934. releaseMemArray(pMem, 8);
  56935. p->pResultSet = 0;
  56936. if( p->rc==SQLITE_NOMEM ){
  56937. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  56938. ** sqlite3_column_text16() failed. */
  56939. db->mallocFailed = 1;
  56940. return SQLITE_ERROR;
  56941. }
  56942. /* When the number of output rows reaches nRow, that means the
  56943. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  56944. ** nRow is the sum of the number of rows in the main program, plus
  56945. ** the sum of the number of rows in all trigger subprograms encountered
  56946. ** so far. The nRow value will increase as new trigger subprograms are
  56947. ** encountered, but p->pc will eventually catch up to nRow.
  56948. */
  56949. nRow = p->nOp;
  56950. if( p->explain==1 ){
  56951. /* The first 8 memory cells are used for the result set. So we will
  56952. ** commandeer the 9th cell to use as storage for an array of pointers
  56953. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  56954. ** cells. */
  56955. assert( p->nMem>9 );
  56956. pSub = &p->aMem[9];
  56957. if( pSub->flags&MEM_Blob ){
  56958. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  56959. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  56960. nSub = pSub->n/sizeof(Vdbe*);
  56961. apSub = (SubProgram **)pSub->z;
  56962. }
  56963. for(i=0; i<nSub; i++){
  56964. nRow += apSub[i]->nOp;
  56965. }
  56966. }
  56967. do{
  56968. i = p->pc++;
  56969. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  56970. if( i>=nRow ){
  56971. p->rc = SQLITE_OK;
  56972. rc = SQLITE_DONE;
  56973. }else if( db->u1.isInterrupted ){
  56974. p->rc = SQLITE_INTERRUPT;
  56975. rc = SQLITE_ERROR;
  56976. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  56977. }else{
  56978. char *z;
  56979. Op *pOp;
  56980. if( i<p->nOp ){
  56981. /* The output line number is small enough that we are still in the
  56982. ** main program. */
  56983. pOp = &p->aOp[i];
  56984. }else{
  56985. /* We are currently listing subprograms. Figure out which one and
  56986. ** pick up the appropriate opcode. */
  56987. int j;
  56988. i -= p->nOp;
  56989. for(j=0; i>=apSub[j]->nOp; j++){
  56990. i -= apSub[j]->nOp;
  56991. }
  56992. pOp = &apSub[j]->aOp[i];
  56993. }
  56994. if( p->explain==1 ){
  56995. pMem->flags = MEM_Int;
  56996. pMem->type = SQLITE_INTEGER;
  56997. pMem->u.i = i; /* Program counter */
  56998. pMem++;
  56999. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  57000. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  57001. assert( pMem->z!=0 );
  57002. pMem->n = sqlite3Strlen30(pMem->z);
  57003. pMem->type = SQLITE_TEXT;
  57004. pMem->enc = SQLITE_UTF8;
  57005. pMem++;
  57006. /* When an OP_Program opcode is encounter (the only opcode that has
  57007. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  57008. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  57009. ** has not already been seen.
  57010. */
  57011. if( pOp->p4type==P4_SUBPROGRAM ){
  57012. int nByte = (nSub+1)*sizeof(SubProgram*);
  57013. int j;
  57014. for(j=0; j<nSub; j++){
  57015. if( apSub[j]==pOp->p4.pProgram ) break;
  57016. }
  57017. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  57018. apSub = (SubProgram **)pSub->z;
  57019. apSub[nSub++] = pOp->p4.pProgram;
  57020. pSub->flags |= MEM_Blob;
  57021. pSub->n = nSub*sizeof(SubProgram*);
  57022. }
  57023. }
  57024. }
  57025. pMem->flags = MEM_Int;
  57026. pMem->u.i = pOp->p1; /* P1 */
  57027. pMem->type = SQLITE_INTEGER;
  57028. pMem++;
  57029. pMem->flags = MEM_Int;
  57030. pMem->u.i = pOp->p2; /* P2 */
  57031. pMem->type = SQLITE_INTEGER;
  57032. pMem++;
  57033. pMem->flags = MEM_Int;
  57034. pMem->u.i = pOp->p3; /* P3 */
  57035. pMem->type = SQLITE_INTEGER;
  57036. pMem++;
  57037. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  57038. assert( p->db->mallocFailed );
  57039. return SQLITE_ERROR;
  57040. }
  57041. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  57042. z = displayP4(pOp, pMem->z, 32);
  57043. if( z!=pMem->z ){
  57044. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  57045. }else{
  57046. assert( pMem->z!=0 );
  57047. pMem->n = sqlite3Strlen30(pMem->z);
  57048. pMem->enc = SQLITE_UTF8;
  57049. }
  57050. pMem->type = SQLITE_TEXT;
  57051. pMem++;
  57052. if( p->explain==1 ){
  57053. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  57054. assert( p->db->mallocFailed );
  57055. return SQLITE_ERROR;
  57056. }
  57057. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  57058. pMem->n = 2;
  57059. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  57060. pMem->type = SQLITE_TEXT;
  57061. pMem->enc = SQLITE_UTF8;
  57062. pMem++;
  57063. #ifdef SQLITE_DEBUG
  57064. if( pOp->zComment ){
  57065. pMem->flags = MEM_Str|MEM_Term;
  57066. pMem->z = pOp->zComment;
  57067. pMem->n = sqlite3Strlen30(pMem->z);
  57068. pMem->enc = SQLITE_UTF8;
  57069. pMem->type = SQLITE_TEXT;
  57070. }else
  57071. #endif
  57072. {
  57073. pMem->flags = MEM_Null; /* Comment */
  57074. pMem->type = SQLITE_NULL;
  57075. }
  57076. }
  57077. p->nResColumn = 8 - 4*(p->explain-1);
  57078. p->pResultSet = &p->aMem[1];
  57079. p->rc = SQLITE_OK;
  57080. rc = SQLITE_ROW;
  57081. }
  57082. return rc;
  57083. }
  57084. #endif /* SQLITE_OMIT_EXPLAIN */
  57085. #ifdef SQLITE_DEBUG
  57086. /*
  57087. ** Print the SQL that was used to generate a VDBE program.
  57088. */
  57089. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  57090. int nOp = p->nOp;
  57091. VdbeOp *pOp;
  57092. if( nOp<1 ) return;
  57093. pOp = &p->aOp[0];
  57094. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  57095. const char *z = pOp->p4.z;
  57096. while( sqlite3Isspace(*z) ) z++;
  57097. printf("SQL: [%s]\n", z);
  57098. }
  57099. }
  57100. #endif
  57101. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  57102. /*
  57103. ** Print an IOTRACE message showing SQL content.
  57104. */
  57105. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  57106. int nOp = p->nOp;
  57107. VdbeOp *pOp;
  57108. if( sqlite3IoTrace==0 ) return;
  57109. if( nOp<1 ) return;
  57110. pOp = &p->aOp[0];
  57111. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  57112. int i, j;
  57113. char z[1000];
  57114. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  57115. for(i=0; sqlite3Isspace(z[i]); i++){}
  57116. for(j=0; z[i]; i++){
  57117. if( sqlite3Isspace(z[i]) ){
  57118. if( z[i-1]!=' ' ){
  57119. z[j++] = ' ';
  57120. }
  57121. }else{
  57122. z[j++] = z[i];
  57123. }
  57124. }
  57125. z[j] = 0;
  57126. sqlite3IoTrace("SQL %s\n", z);
  57127. }
  57128. }
  57129. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  57130. /*
  57131. ** Allocate space from a fixed size buffer and return a pointer to
  57132. ** that space. If insufficient space is available, return NULL.
  57133. **
  57134. ** The pBuf parameter is the initial value of a pointer which will
  57135. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  57136. ** NULL, it means that memory space has already been allocated and that
  57137. ** this routine should not allocate any new memory. When pBuf is not
  57138. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  57139. ** is NULL.
  57140. **
  57141. ** nByte is the number of bytes of space needed.
  57142. **
  57143. ** *ppFrom points to available space and pEnd points to the end of the
  57144. ** available space. When space is allocated, *ppFrom is advanced past
  57145. ** the end of the allocated space.
  57146. **
  57147. ** *pnByte is a counter of the number of bytes of space that have failed
  57148. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  57149. ** request, then increment *pnByte by the amount of the request.
  57150. */
  57151. static void *allocSpace(
  57152. void *pBuf, /* Where return pointer will be stored */
  57153. int nByte, /* Number of bytes to allocate */
  57154. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  57155. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  57156. int *pnByte /* If allocation cannot be made, increment *pnByte */
  57157. ){
  57158. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  57159. if( pBuf ) return pBuf;
  57160. nByte = ROUND8(nByte);
  57161. if( &(*ppFrom)[nByte] <= pEnd ){
  57162. pBuf = (void*)*ppFrom;
  57163. *ppFrom += nByte;
  57164. }else{
  57165. *pnByte += nByte;
  57166. }
  57167. return pBuf;
  57168. }
  57169. /*
  57170. ** Rewind the VDBE back to the beginning in preparation for
  57171. ** running it.
  57172. */
  57173. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  57174. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  57175. int i;
  57176. #endif
  57177. assert( p!=0 );
  57178. assert( p->magic==VDBE_MAGIC_INIT );
  57179. /* There should be at least one opcode.
  57180. */
  57181. assert( p->nOp>0 );
  57182. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  57183. p->magic = VDBE_MAGIC_RUN;
  57184. #ifdef SQLITE_DEBUG
  57185. for(i=1; i<p->nMem; i++){
  57186. assert( p->aMem[i].db==p->db );
  57187. }
  57188. #endif
  57189. p->pc = -1;
  57190. p->rc = SQLITE_OK;
  57191. p->errorAction = OE_Abort;
  57192. p->magic = VDBE_MAGIC_RUN;
  57193. p->nChange = 0;
  57194. p->cacheCtr = 1;
  57195. p->minWriteFileFormat = 255;
  57196. p->iStatement = 0;
  57197. p->nFkConstraint = 0;
  57198. #ifdef VDBE_PROFILE
  57199. for(i=0; i<p->nOp; i++){
  57200. p->aOp[i].cnt = 0;
  57201. p->aOp[i].cycles = 0;
  57202. }
  57203. #endif
  57204. }
  57205. /*
  57206. ** Prepare a virtual machine for execution for the first time after
  57207. ** creating the virtual machine. This involves things such
  57208. ** as allocating stack space and initializing the program counter.
  57209. ** After the VDBE has be prepped, it can be executed by one or more
  57210. ** calls to sqlite3VdbeExec().
  57211. **
  57212. ** This function may be called exact once on a each virtual machine.
  57213. ** After this routine is called the VM has been "packaged" and is ready
  57214. ** to run. After this routine is called, futher calls to
  57215. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  57216. ** the Vdbe from the Parse object that helped generate it so that the
  57217. ** the Vdbe becomes an independent entity and the Parse object can be
  57218. ** destroyed.
  57219. **
  57220. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  57221. ** to its initial state after it has been run.
  57222. */
  57223. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  57224. Vdbe *p, /* The VDBE */
  57225. Parse *pParse /* Parsing context */
  57226. ){
  57227. sqlite3 *db; /* The database connection */
  57228. int nVar; /* Number of parameters */
  57229. int nMem; /* Number of VM memory registers */
  57230. int nCursor; /* Number of cursors required */
  57231. int nArg; /* Number of arguments in subprograms */
  57232. int nOnce; /* Number of OP_Once instructions */
  57233. int n; /* Loop counter */
  57234. u8 *zCsr; /* Memory available for allocation */
  57235. u8 *zEnd; /* First byte past allocated memory */
  57236. int nByte; /* How much extra memory is needed */
  57237. assert( p!=0 );
  57238. assert( p->nOp>0 );
  57239. assert( pParse!=0 );
  57240. assert( p->magic==VDBE_MAGIC_INIT );
  57241. db = p->db;
  57242. assert( db->mallocFailed==0 );
  57243. nVar = pParse->nVar;
  57244. nMem = pParse->nMem;
  57245. nCursor = pParse->nTab;
  57246. nArg = pParse->nMaxArg;
  57247. nOnce = pParse->nOnce;
  57248. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  57249. /* For each cursor required, also allocate a memory cell. Memory
  57250. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  57251. ** the vdbe program. Instead they are used to allocate space for
  57252. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  57253. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  57254. ** stores the blob of memory associated with cursor 1, etc.
  57255. **
  57256. ** See also: allocateCursor().
  57257. */
  57258. nMem += nCursor;
  57259. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  57260. ** an array to marshal SQL function arguments in.
  57261. */
  57262. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  57263. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  57264. resolveP2Values(p, &nArg);
  57265. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  57266. if( pParse->explain && nMem<10 ){
  57267. nMem = 10;
  57268. }
  57269. memset(zCsr, 0, zEnd-zCsr);
  57270. zCsr += (zCsr - (u8*)0)&7;
  57271. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  57272. p->expired = 0;
  57273. /* Memory for registers, parameters, cursor, etc, is allocated in two
  57274. ** passes. On the first pass, we try to reuse unused space at the
  57275. ** end of the opcode array. If we are unable to satisfy all memory
  57276. ** requirements by reusing the opcode array tail, then the second
  57277. ** pass will fill in the rest using a fresh allocation.
  57278. **
  57279. ** This two-pass approach that reuses as much memory as possible from
  57280. ** the leftover space at the end of the opcode array can significantly
  57281. ** reduce the amount of memory held by a prepared statement.
  57282. */
  57283. do {
  57284. nByte = 0;
  57285. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  57286. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  57287. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  57288. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  57289. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  57290. &zCsr, zEnd, &nByte);
  57291. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  57292. if( nByte ){
  57293. p->pFree = sqlite3DbMallocZero(db, nByte);
  57294. }
  57295. zCsr = p->pFree;
  57296. zEnd = &zCsr[nByte];
  57297. }while( nByte && !db->mallocFailed );
  57298. p->nCursor = nCursor;
  57299. p->nOnceFlag = nOnce;
  57300. if( p->aVar ){
  57301. p->nVar = (ynVar)nVar;
  57302. for(n=0; n<nVar; n++){
  57303. p->aVar[n].flags = MEM_Null;
  57304. p->aVar[n].db = db;
  57305. }
  57306. }
  57307. if( p->azVar ){
  57308. p->nzVar = pParse->nzVar;
  57309. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  57310. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  57311. }
  57312. if( p->aMem ){
  57313. p->aMem--; /* aMem[] goes from 1..nMem */
  57314. p->nMem = nMem; /* not from 0..nMem-1 */
  57315. for(n=1; n<=nMem; n++){
  57316. p->aMem[n].flags = MEM_Invalid;
  57317. p->aMem[n].db = db;
  57318. }
  57319. }
  57320. p->explain = pParse->explain;
  57321. sqlite3VdbeRewind(p);
  57322. }
  57323. /*
  57324. ** Close a VDBE cursor and release all the resources that cursor
  57325. ** happens to hold.
  57326. */
  57327. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  57328. if( pCx==0 ){
  57329. return;
  57330. }
  57331. sqlite3VdbeSorterClose(p->db, pCx);
  57332. if( pCx->pBt ){
  57333. sqlite3BtreeClose(pCx->pBt);
  57334. /* The pCx->pCursor will be close automatically, if it exists, by
  57335. ** the call above. */
  57336. }else if( pCx->pCursor ){
  57337. sqlite3BtreeCloseCursor(pCx->pCursor);
  57338. }
  57339. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57340. if( pCx->pVtabCursor ){
  57341. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  57342. const sqlite3_module *pModule = pCx->pModule;
  57343. p->inVtabMethod = 1;
  57344. pModule->xClose(pVtabCursor);
  57345. p->inVtabMethod = 0;
  57346. }
  57347. #endif
  57348. }
  57349. /*
  57350. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  57351. ** is used, for example, when a trigger sub-program is halted to restore
  57352. ** control to the main program.
  57353. */
  57354. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  57355. Vdbe *v = pFrame->v;
  57356. v->aOnceFlag = pFrame->aOnceFlag;
  57357. v->nOnceFlag = pFrame->nOnceFlag;
  57358. v->aOp = pFrame->aOp;
  57359. v->nOp = pFrame->nOp;
  57360. v->aMem = pFrame->aMem;
  57361. v->nMem = pFrame->nMem;
  57362. v->apCsr = pFrame->apCsr;
  57363. v->nCursor = pFrame->nCursor;
  57364. v->db->lastRowid = pFrame->lastRowid;
  57365. v->nChange = pFrame->nChange;
  57366. return pFrame->pc;
  57367. }
  57368. /*
  57369. ** Close all cursors.
  57370. **
  57371. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  57372. ** cell array. This is necessary as the memory cell array may contain
  57373. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  57374. ** open cursors.
  57375. */
  57376. static void closeAllCursors(Vdbe *p){
  57377. if( p->pFrame ){
  57378. VdbeFrame *pFrame;
  57379. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  57380. sqlite3VdbeFrameRestore(pFrame);
  57381. }
  57382. p->pFrame = 0;
  57383. p->nFrame = 0;
  57384. if( p->apCsr ){
  57385. int i;
  57386. for(i=0; i<p->nCursor; i++){
  57387. VdbeCursor *pC = p->apCsr[i];
  57388. if( pC ){
  57389. sqlite3VdbeFreeCursor(p, pC);
  57390. p->apCsr[i] = 0;
  57391. }
  57392. }
  57393. }
  57394. if( p->aMem ){
  57395. releaseMemArray(&p->aMem[1], p->nMem);
  57396. }
  57397. while( p->pDelFrame ){
  57398. VdbeFrame *pDel = p->pDelFrame;
  57399. p->pDelFrame = pDel->pParent;
  57400. sqlite3VdbeFrameDelete(pDel);
  57401. }
  57402. }
  57403. /*
  57404. ** Clean up the VM after execution.
  57405. **
  57406. ** This routine will automatically close any cursors, lists, and/or
  57407. ** sorters that were left open. It also deletes the values of
  57408. ** variables in the aVar[] array.
  57409. */
  57410. static void Cleanup(Vdbe *p){
  57411. sqlite3 *db = p->db;
  57412. #ifdef SQLITE_DEBUG
  57413. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  57414. ** Vdbe.aMem[] arrays have already been cleaned up. */
  57415. int i;
  57416. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  57417. if( p->aMem ){
  57418. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  57419. }
  57420. #endif
  57421. sqlite3DbFree(db, p->zErrMsg);
  57422. p->zErrMsg = 0;
  57423. p->pResultSet = 0;
  57424. }
  57425. /*
  57426. ** Set the number of result columns that will be returned by this SQL
  57427. ** statement. This is now set at compile time, rather than during
  57428. ** execution of the vdbe program so that sqlite3_column_count() can
  57429. ** be called on an SQL statement before sqlite3_step().
  57430. */
  57431. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  57432. Mem *pColName;
  57433. int n;
  57434. sqlite3 *db = p->db;
  57435. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  57436. sqlite3DbFree(db, p->aColName);
  57437. n = nResColumn*COLNAME_N;
  57438. p->nResColumn = (u16)nResColumn;
  57439. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  57440. if( p->aColName==0 ) return;
  57441. while( n-- > 0 ){
  57442. pColName->flags = MEM_Null;
  57443. pColName->db = p->db;
  57444. pColName++;
  57445. }
  57446. }
  57447. /*
  57448. ** Set the name of the idx'th column to be returned by the SQL statement.
  57449. ** zName must be a pointer to a nul terminated string.
  57450. **
  57451. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  57452. **
  57453. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  57454. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  57455. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  57456. */
  57457. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  57458. Vdbe *p, /* Vdbe being configured */
  57459. int idx, /* Index of column zName applies to */
  57460. int var, /* One of the COLNAME_* constants */
  57461. const char *zName, /* Pointer to buffer containing name */
  57462. void (*xDel)(void*) /* Memory management strategy for zName */
  57463. ){
  57464. int rc;
  57465. Mem *pColName;
  57466. assert( idx<p->nResColumn );
  57467. assert( var<COLNAME_N );
  57468. if( p->db->mallocFailed ){
  57469. assert( !zName || xDel!=SQLITE_DYNAMIC );
  57470. return SQLITE_NOMEM;
  57471. }
  57472. assert( p->aColName!=0 );
  57473. pColName = &(p->aColName[idx+var*p->nResColumn]);
  57474. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  57475. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  57476. return rc;
  57477. }
  57478. /*
  57479. ** A read or write transaction may or may not be active on database handle
  57480. ** db. If a transaction is active, commit it. If there is a
  57481. ** write-transaction spanning more than one database file, this routine
  57482. ** takes care of the master journal trickery.
  57483. */
  57484. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  57485. int i;
  57486. int nTrans = 0; /* Number of databases with an active write-transaction */
  57487. int rc = SQLITE_OK;
  57488. int needXcommit = 0;
  57489. #ifdef SQLITE_OMIT_VIRTUALTABLE
  57490. /* With this option, sqlite3VtabSync() is defined to be simply
  57491. ** SQLITE_OK so p is not used.
  57492. */
  57493. UNUSED_PARAMETER(p);
  57494. #endif
  57495. /* Before doing anything else, call the xSync() callback for any
  57496. ** virtual module tables written in this transaction. This has to
  57497. ** be done before determining whether a master journal file is
  57498. ** required, as an xSync() callback may add an attached database
  57499. ** to the transaction.
  57500. */
  57501. rc = sqlite3VtabSync(db, &p->zErrMsg);
  57502. /* This loop determines (a) if the commit hook should be invoked and
  57503. ** (b) how many database files have open write transactions, not
  57504. ** including the temp database. (b) is important because if more than
  57505. ** one database file has an open write transaction, a master journal
  57506. ** file is required for an atomic commit.
  57507. */
  57508. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  57509. Btree *pBt = db->aDb[i].pBt;
  57510. if( sqlite3BtreeIsInTrans(pBt) ){
  57511. needXcommit = 1;
  57512. if( i!=1 ) nTrans++;
  57513. sqlite3BtreeEnter(pBt);
  57514. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  57515. sqlite3BtreeLeave(pBt);
  57516. }
  57517. }
  57518. if( rc!=SQLITE_OK ){
  57519. return rc;
  57520. }
  57521. /* If there are any write-transactions at all, invoke the commit hook */
  57522. if( needXcommit && db->xCommitCallback ){
  57523. rc = db->xCommitCallback(db->pCommitArg);
  57524. if( rc ){
  57525. return SQLITE_CONSTRAINT_COMMITHOOK;
  57526. }
  57527. }
  57528. /* The simple case - no more than one database file (not counting the
  57529. ** TEMP database) has a transaction active. There is no need for the
  57530. ** master-journal.
  57531. **
  57532. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  57533. ** string, it means the main database is :memory: or a temp file. In
  57534. ** that case we do not support atomic multi-file commits, so use the
  57535. ** simple case then too.
  57536. */
  57537. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  57538. || nTrans<=1
  57539. ){
  57540. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  57541. Btree *pBt = db->aDb[i].pBt;
  57542. if( pBt ){
  57543. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  57544. }
  57545. }
  57546. /* Do the commit only if all databases successfully complete phase 1.
  57547. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  57548. ** IO error while deleting or truncating a journal file. It is unlikely,
  57549. ** but could happen. In this case abandon processing and return the error.
  57550. */
  57551. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  57552. Btree *pBt = db->aDb[i].pBt;
  57553. if( pBt ){
  57554. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  57555. }
  57556. }
  57557. if( rc==SQLITE_OK ){
  57558. sqlite3VtabCommit(db);
  57559. }
  57560. }
  57561. /* The complex case - There is a multi-file write-transaction active.
  57562. ** This requires a master journal file to ensure the transaction is
  57563. ** committed atomicly.
  57564. */
  57565. #ifndef SQLITE_OMIT_DISKIO
  57566. else{
  57567. sqlite3_vfs *pVfs = db->pVfs;
  57568. int needSync = 0;
  57569. char *zMaster = 0; /* File-name for the master journal */
  57570. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  57571. sqlite3_file *pMaster = 0;
  57572. i64 offset = 0;
  57573. int res;
  57574. int retryCount = 0;
  57575. int nMainFile;
  57576. /* Select a master journal file name */
  57577. nMainFile = sqlite3Strlen30(zMainFile);
  57578. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  57579. if( zMaster==0 ) return SQLITE_NOMEM;
  57580. do {
  57581. u32 iRandom;
  57582. if( retryCount ){
  57583. if( retryCount>100 ){
  57584. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  57585. sqlite3OsDelete(pVfs, zMaster, 0);
  57586. break;
  57587. }else if( retryCount==1 ){
  57588. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  57589. }
  57590. }
  57591. retryCount++;
  57592. sqlite3_randomness(sizeof(iRandom), &iRandom);
  57593. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  57594. (iRandom>>8)&0xffffff, iRandom&0xff);
  57595. /* The antipenultimate character of the master journal name must
  57596. ** be "9" to avoid name collisions when using 8+3 filenames. */
  57597. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  57598. sqlite3FileSuffix3(zMainFile, zMaster);
  57599. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  57600. }while( rc==SQLITE_OK && res );
  57601. if( rc==SQLITE_OK ){
  57602. /* Open the master journal. */
  57603. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  57604. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  57605. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  57606. );
  57607. }
  57608. if( rc!=SQLITE_OK ){
  57609. sqlite3DbFree(db, zMaster);
  57610. return rc;
  57611. }
  57612. /* Write the name of each database file in the transaction into the new
  57613. ** master journal file. If an error occurs at this point close
  57614. ** and delete the master journal file. All the individual journal files
  57615. ** still have 'null' as the master journal pointer, so they will roll
  57616. ** back independently if a failure occurs.
  57617. */
  57618. for(i=0; i<db->nDb; i++){
  57619. Btree *pBt = db->aDb[i].pBt;
  57620. if( sqlite3BtreeIsInTrans(pBt) ){
  57621. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  57622. if( zFile==0 ){
  57623. continue; /* Ignore TEMP and :memory: databases */
  57624. }
  57625. assert( zFile[0]!=0 );
  57626. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  57627. needSync = 1;
  57628. }
  57629. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  57630. offset += sqlite3Strlen30(zFile)+1;
  57631. if( rc!=SQLITE_OK ){
  57632. sqlite3OsCloseFree(pMaster);
  57633. sqlite3OsDelete(pVfs, zMaster, 0);
  57634. sqlite3DbFree(db, zMaster);
  57635. return rc;
  57636. }
  57637. }
  57638. }
  57639. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  57640. ** flag is set this is not required.
  57641. */
  57642. if( needSync
  57643. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  57644. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  57645. ){
  57646. sqlite3OsCloseFree(pMaster);
  57647. sqlite3OsDelete(pVfs, zMaster, 0);
  57648. sqlite3DbFree(db, zMaster);
  57649. return rc;
  57650. }
  57651. /* Sync all the db files involved in the transaction. The same call
  57652. ** sets the master journal pointer in each individual journal. If
  57653. ** an error occurs here, do not delete the master journal file.
  57654. **
  57655. ** If the error occurs during the first call to
  57656. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  57657. ** master journal file will be orphaned. But we cannot delete it,
  57658. ** in case the master journal file name was written into the journal
  57659. ** file before the failure occurred.
  57660. */
  57661. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  57662. Btree *pBt = db->aDb[i].pBt;
  57663. if( pBt ){
  57664. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  57665. }
  57666. }
  57667. sqlite3OsCloseFree(pMaster);
  57668. assert( rc!=SQLITE_BUSY );
  57669. if( rc!=SQLITE_OK ){
  57670. sqlite3DbFree(db, zMaster);
  57671. return rc;
  57672. }
  57673. /* Delete the master journal file. This commits the transaction. After
  57674. ** doing this the directory is synced again before any individual
  57675. ** transaction files are deleted.
  57676. */
  57677. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  57678. sqlite3DbFree(db, zMaster);
  57679. zMaster = 0;
  57680. if( rc ){
  57681. return rc;
  57682. }
  57683. /* All files and directories have already been synced, so the following
  57684. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  57685. ** deleting or truncating journals. If something goes wrong while
  57686. ** this is happening we don't really care. The integrity of the
  57687. ** transaction is already guaranteed, but some stray 'cold' journals
  57688. ** may be lying around. Returning an error code won't help matters.
  57689. */
  57690. disable_simulated_io_errors();
  57691. sqlite3BeginBenignMalloc();
  57692. for(i=0; i<db->nDb; i++){
  57693. Btree *pBt = db->aDb[i].pBt;
  57694. if( pBt ){
  57695. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  57696. }
  57697. }
  57698. sqlite3EndBenignMalloc();
  57699. enable_simulated_io_errors();
  57700. sqlite3VtabCommit(db);
  57701. }
  57702. #endif
  57703. return rc;
  57704. }
  57705. /*
  57706. ** This routine checks that the sqlite3.activeVdbeCnt count variable
  57707. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  57708. ** currently active. An assertion fails if the two counts do not match.
  57709. ** This is an internal self-check only - it is not an essential processing
  57710. ** step.
  57711. **
  57712. ** This is a no-op if NDEBUG is defined.
  57713. */
  57714. #ifndef NDEBUG
  57715. static void checkActiveVdbeCnt(sqlite3 *db){
  57716. Vdbe *p;
  57717. int cnt = 0;
  57718. int nWrite = 0;
  57719. p = db->pVdbe;
  57720. while( p ){
  57721. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  57722. cnt++;
  57723. if( p->readOnly==0 ) nWrite++;
  57724. }
  57725. p = p->pNext;
  57726. }
  57727. assert( cnt==db->activeVdbeCnt );
  57728. assert( nWrite==db->writeVdbeCnt );
  57729. }
  57730. #else
  57731. #define checkActiveVdbeCnt(x)
  57732. #endif
  57733. /*
  57734. ** If the Vdbe passed as the first argument opened a statement-transaction,
  57735. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  57736. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  57737. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  57738. ** statement transaction is commtted.
  57739. **
  57740. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  57741. ** Otherwise SQLITE_OK.
  57742. */
  57743. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  57744. sqlite3 *const db = p->db;
  57745. int rc = SQLITE_OK;
  57746. /* If p->iStatement is greater than zero, then this Vdbe opened a
  57747. ** statement transaction that should be closed here. The only exception
  57748. ** is that an IO error may have occurred, causing an emergency rollback.
  57749. ** In this case (db->nStatement==0), and there is nothing to do.
  57750. */
  57751. if( db->nStatement && p->iStatement ){
  57752. int i;
  57753. const int iSavepoint = p->iStatement-1;
  57754. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  57755. assert( db->nStatement>0 );
  57756. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  57757. for(i=0; i<db->nDb; i++){
  57758. int rc2 = SQLITE_OK;
  57759. Btree *pBt = db->aDb[i].pBt;
  57760. if( pBt ){
  57761. if( eOp==SAVEPOINT_ROLLBACK ){
  57762. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  57763. }
  57764. if( rc2==SQLITE_OK ){
  57765. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  57766. }
  57767. if( rc==SQLITE_OK ){
  57768. rc = rc2;
  57769. }
  57770. }
  57771. }
  57772. db->nStatement--;
  57773. p->iStatement = 0;
  57774. if( rc==SQLITE_OK ){
  57775. if( eOp==SAVEPOINT_ROLLBACK ){
  57776. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  57777. }
  57778. if( rc==SQLITE_OK ){
  57779. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  57780. }
  57781. }
  57782. /* If the statement transaction is being rolled back, also restore the
  57783. ** database handles deferred constraint counter to the value it had when
  57784. ** the statement transaction was opened. */
  57785. if( eOp==SAVEPOINT_ROLLBACK ){
  57786. db->nDeferredCons = p->nStmtDefCons;
  57787. }
  57788. }
  57789. return rc;
  57790. }
  57791. /*
  57792. ** This function is called when a transaction opened by the database
  57793. ** handle associated with the VM passed as an argument is about to be
  57794. ** committed. If there are outstanding deferred foreign key constraint
  57795. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  57796. **
  57797. ** If there are outstanding FK violations and this function returns
  57798. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  57799. ** and write an error message to it. Then return SQLITE_ERROR.
  57800. */
  57801. #ifndef SQLITE_OMIT_FOREIGN_KEY
  57802. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  57803. sqlite3 *db = p->db;
  57804. if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
  57805. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  57806. p->errorAction = OE_Abort;
  57807. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  57808. return SQLITE_ERROR;
  57809. }
  57810. return SQLITE_OK;
  57811. }
  57812. #endif
  57813. /*
  57814. ** This routine is called the when a VDBE tries to halt. If the VDBE
  57815. ** has made changes and is in autocommit mode, then commit those
  57816. ** changes. If a rollback is needed, then do the rollback.
  57817. **
  57818. ** This routine is the only way to move the state of a VM from
  57819. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  57820. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  57821. **
  57822. ** Return an error code. If the commit could not complete because of
  57823. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  57824. ** means the close did not happen and needs to be repeated.
  57825. */
  57826. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  57827. int rc; /* Used to store transient return codes */
  57828. sqlite3 *db = p->db;
  57829. /* This function contains the logic that determines if a statement or
  57830. ** transaction will be committed or rolled back as a result of the
  57831. ** execution of this virtual machine.
  57832. **
  57833. ** If any of the following errors occur:
  57834. **
  57835. ** SQLITE_NOMEM
  57836. ** SQLITE_IOERR
  57837. ** SQLITE_FULL
  57838. ** SQLITE_INTERRUPT
  57839. **
  57840. ** Then the internal cache might have been left in an inconsistent
  57841. ** state. We need to rollback the statement transaction, if there is
  57842. ** one, or the complete transaction if there is no statement transaction.
  57843. */
  57844. if( p->db->mallocFailed ){
  57845. p->rc = SQLITE_NOMEM;
  57846. }
  57847. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  57848. closeAllCursors(p);
  57849. if( p->magic!=VDBE_MAGIC_RUN ){
  57850. return SQLITE_OK;
  57851. }
  57852. checkActiveVdbeCnt(db);
  57853. /* No commit or rollback needed if the program never started */
  57854. if( p->pc>=0 ){
  57855. int mrc; /* Primary error code from p->rc */
  57856. int eStatementOp = 0;
  57857. int isSpecialError; /* Set to true if a 'special' error */
  57858. /* Lock all btrees used by the statement */
  57859. sqlite3VdbeEnter(p);
  57860. /* Check for one of the special errors */
  57861. mrc = p->rc & 0xff;
  57862. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  57863. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  57864. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  57865. if( isSpecialError ){
  57866. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  57867. ** no rollback is necessary. Otherwise, at least a savepoint
  57868. ** transaction must be rolled back to restore the database to a
  57869. ** consistent state.
  57870. **
  57871. ** Even if the statement is read-only, it is important to perform
  57872. ** a statement or transaction rollback operation. If the error
  57873. ** occurred while writing to the journal, sub-journal or database
  57874. ** file as part of an effort to free up cache space (see function
  57875. ** pagerStress() in pager.c), the rollback is required to restore
  57876. ** the pager to a consistent state.
  57877. */
  57878. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  57879. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  57880. eStatementOp = SAVEPOINT_ROLLBACK;
  57881. }else{
  57882. /* We are forced to roll back the active transaction. Before doing
  57883. ** so, abort any other statements this handle currently has active.
  57884. */
  57885. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  57886. sqlite3CloseSavepoints(db);
  57887. db->autoCommit = 1;
  57888. }
  57889. }
  57890. }
  57891. /* Check for immediate foreign key violations. */
  57892. if( p->rc==SQLITE_OK ){
  57893. sqlite3VdbeCheckFk(p, 0);
  57894. }
  57895. /* If the auto-commit flag is set and this is the only active writer
  57896. ** VM, then we do either a commit or rollback of the current transaction.
  57897. **
  57898. ** Note: This block also runs if one of the special errors handled
  57899. ** above has occurred.
  57900. */
  57901. if( !sqlite3VtabInSync(db)
  57902. && db->autoCommit
  57903. && db->writeVdbeCnt==(p->readOnly==0)
  57904. ){
  57905. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  57906. rc = sqlite3VdbeCheckFk(p, 1);
  57907. if( rc!=SQLITE_OK ){
  57908. if( NEVER(p->readOnly) ){
  57909. sqlite3VdbeLeave(p);
  57910. return SQLITE_ERROR;
  57911. }
  57912. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  57913. }else{
  57914. /* The auto-commit flag is true, the vdbe program was successful
  57915. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  57916. ** key constraints to hold up the transaction. This means a commit
  57917. ** is required. */
  57918. rc = vdbeCommit(db, p);
  57919. }
  57920. if( rc==SQLITE_BUSY && p->readOnly ){
  57921. sqlite3VdbeLeave(p);
  57922. return SQLITE_BUSY;
  57923. }else if( rc!=SQLITE_OK ){
  57924. p->rc = rc;
  57925. sqlite3RollbackAll(db, SQLITE_OK);
  57926. }else{
  57927. db->nDeferredCons = 0;
  57928. sqlite3CommitInternalChanges(db);
  57929. }
  57930. }else{
  57931. sqlite3RollbackAll(db, SQLITE_OK);
  57932. }
  57933. db->nStatement = 0;
  57934. }else if( eStatementOp==0 ){
  57935. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  57936. eStatementOp = SAVEPOINT_RELEASE;
  57937. }else if( p->errorAction==OE_Abort ){
  57938. eStatementOp = SAVEPOINT_ROLLBACK;
  57939. }else{
  57940. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  57941. sqlite3CloseSavepoints(db);
  57942. db->autoCommit = 1;
  57943. }
  57944. }
  57945. /* If eStatementOp is non-zero, then a statement transaction needs to
  57946. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  57947. ** do so. If this operation returns an error, and the current statement
  57948. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  57949. ** current statement error code.
  57950. */
  57951. if( eStatementOp ){
  57952. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  57953. if( rc ){
  57954. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  57955. p->rc = rc;
  57956. sqlite3DbFree(db, p->zErrMsg);
  57957. p->zErrMsg = 0;
  57958. }
  57959. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  57960. sqlite3CloseSavepoints(db);
  57961. db->autoCommit = 1;
  57962. }
  57963. }
  57964. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  57965. ** has been rolled back, update the database connection change-counter.
  57966. */
  57967. if( p->changeCntOn ){
  57968. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  57969. sqlite3VdbeSetChanges(db, p->nChange);
  57970. }else{
  57971. sqlite3VdbeSetChanges(db, 0);
  57972. }
  57973. p->nChange = 0;
  57974. }
  57975. /* Release the locks */
  57976. sqlite3VdbeLeave(p);
  57977. }
  57978. /* We have successfully halted and closed the VM. Record this fact. */
  57979. if( p->pc>=0 ){
  57980. db->activeVdbeCnt--;
  57981. if( !p->readOnly ){
  57982. db->writeVdbeCnt--;
  57983. }
  57984. assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  57985. }
  57986. p->magic = VDBE_MAGIC_HALT;
  57987. checkActiveVdbeCnt(db);
  57988. if( p->db->mallocFailed ){
  57989. p->rc = SQLITE_NOMEM;
  57990. }
  57991. /* If the auto-commit flag is set to true, then any locks that were held
  57992. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  57993. ** to invoke any required unlock-notify callbacks.
  57994. */
  57995. if( db->autoCommit ){
  57996. sqlite3ConnectionUnlocked(db);
  57997. }
  57998. assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
  57999. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  58000. }
  58001. /*
  58002. ** Each VDBE holds the result of the most recent sqlite3_step() call
  58003. ** in p->rc. This routine sets that result back to SQLITE_OK.
  58004. */
  58005. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  58006. p->rc = SQLITE_OK;
  58007. }
  58008. /*
  58009. ** Copy the error code and error message belonging to the VDBE passed
  58010. ** as the first argument to its database handle (so that they will be
  58011. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  58012. **
  58013. ** This function does not clear the VDBE error code or message, just
  58014. ** copies them to the database handle.
  58015. */
  58016. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  58017. sqlite3 *db = p->db;
  58018. int rc = p->rc;
  58019. if( p->zErrMsg ){
  58020. u8 mallocFailed = db->mallocFailed;
  58021. sqlite3BeginBenignMalloc();
  58022. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  58023. sqlite3EndBenignMalloc();
  58024. db->mallocFailed = mallocFailed;
  58025. db->errCode = rc;
  58026. }else{
  58027. sqlite3Error(db, rc, 0);
  58028. }
  58029. return rc;
  58030. }
  58031. #ifdef SQLITE_ENABLE_SQLLOG
  58032. /*
  58033. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  58034. ** invoke it.
  58035. */
  58036. static void vdbeInvokeSqllog(Vdbe *v){
  58037. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  58038. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  58039. assert( v->db->init.busy==0 );
  58040. if( zExpanded ){
  58041. sqlite3GlobalConfig.xSqllog(
  58042. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  58043. );
  58044. sqlite3DbFree(v->db, zExpanded);
  58045. }
  58046. }
  58047. }
  58048. #else
  58049. # define vdbeInvokeSqllog(x)
  58050. #endif
  58051. /*
  58052. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  58053. ** Write any error messages into *pzErrMsg. Return the result code.
  58054. **
  58055. ** After this routine is run, the VDBE should be ready to be executed
  58056. ** again.
  58057. **
  58058. ** To look at it another way, this routine resets the state of the
  58059. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  58060. ** VDBE_MAGIC_INIT.
  58061. */
  58062. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  58063. sqlite3 *db;
  58064. db = p->db;
  58065. /* If the VM did not run to completion or if it encountered an
  58066. ** error, then it might not have been halted properly. So halt
  58067. ** it now.
  58068. */
  58069. sqlite3VdbeHalt(p);
  58070. /* If the VDBE has be run even partially, then transfer the error code
  58071. ** and error message from the VDBE into the main database structure. But
  58072. ** if the VDBE has just been set to run but has not actually executed any
  58073. ** instructions yet, leave the main database error information unchanged.
  58074. */
  58075. if( p->pc>=0 ){
  58076. vdbeInvokeSqllog(p);
  58077. sqlite3VdbeTransferError(p);
  58078. sqlite3DbFree(db, p->zErrMsg);
  58079. p->zErrMsg = 0;
  58080. if( p->runOnlyOnce ) p->expired = 1;
  58081. }else if( p->rc && p->expired ){
  58082. /* The expired flag was set on the VDBE before the first call
  58083. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  58084. ** called), set the database error in this case as well.
  58085. */
  58086. sqlite3Error(db, p->rc, 0);
  58087. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  58088. sqlite3DbFree(db, p->zErrMsg);
  58089. p->zErrMsg = 0;
  58090. }
  58091. /* Reclaim all memory used by the VDBE
  58092. */
  58093. Cleanup(p);
  58094. /* Save profiling information from this VDBE run.
  58095. */
  58096. #ifdef VDBE_PROFILE
  58097. {
  58098. FILE *out = fopen("vdbe_profile.out", "a");
  58099. if( out ){
  58100. int i;
  58101. fprintf(out, "---- ");
  58102. for(i=0; i<p->nOp; i++){
  58103. fprintf(out, "%02x", p->aOp[i].opcode);
  58104. }
  58105. fprintf(out, "\n");
  58106. for(i=0; i<p->nOp; i++){
  58107. fprintf(out, "%6d %10lld %8lld ",
  58108. p->aOp[i].cnt,
  58109. p->aOp[i].cycles,
  58110. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  58111. );
  58112. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  58113. }
  58114. fclose(out);
  58115. }
  58116. }
  58117. #endif
  58118. p->magic = VDBE_MAGIC_INIT;
  58119. return p->rc & db->errMask;
  58120. }
  58121. /*
  58122. ** Clean up and delete a VDBE after execution. Return an integer which is
  58123. ** the result code. Write any error message text into *pzErrMsg.
  58124. */
  58125. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  58126. int rc = SQLITE_OK;
  58127. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  58128. rc = sqlite3VdbeReset(p);
  58129. assert( (rc & p->db->errMask)==rc );
  58130. }
  58131. sqlite3VdbeDelete(p);
  58132. return rc;
  58133. }
  58134. /*
  58135. ** Call the destructor for each auxdata entry in pVdbeFunc for which
  58136. ** the corresponding bit in mask is clear. Auxdata entries beyond 31
  58137. ** are always destroyed. To destroy all auxdata entries, call this
  58138. ** routine with mask==0.
  58139. */
  58140. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  58141. int i;
  58142. for(i=0; i<pVdbeFunc->nAux; i++){
  58143. struct AuxData *pAux = &pVdbeFunc->apAux[i];
  58144. if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
  58145. if( pAux->xDelete ){
  58146. pAux->xDelete(pAux->pAux);
  58147. }
  58148. pAux->pAux = 0;
  58149. }
  58150. }
  58151. }
  58152. /*
  58153. ** Free all memory associated with the Vdbe passed as the second argument,
  58154. ** except for object itself, which is preserved.
  58155. **
  58156. ** The difference between this function and sqlite3VdbeDelete() is that
  58157. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  58158. ** the database connection and frees the object itself.
  58159. */
  58160. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  58161. SubProgram *pSub, *pNext;
  58162. int i;
  58163. assert( p->db==0 || p->db==db );
  58164. releaseMemArray(p->aVar, p->nVar);
  58165. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  58166. for(pSub=p->pProgram; pSub; pSub=pNext){
  58167. pNext = pSub->pNext;
  58168. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  58169. sqlite3DbFree(db, pSub);
  58170. }
  58171. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  58172. vdbeFreeOpArray(db, p->aOp, p->nOp);
  58173. sqlite3DbFree(db, p->aLabel);
  58174. sqlite3DbFree(db, p->aColName);
  58175. sqlite3DbFree(db, p->zSql);
  58176. sqlite3DbFree(db, p->pFree);
  58177. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  58178. sqlite3DbFree(db, p->zExplain);
  58179. sqlite3DbFree(db, p->pExplain);
  58180. #endif
  58181. }
  58182. /*
  58183. ** Delete an entire VDBE.
  58184. */
  58185. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  58186. sqlite3 *db;
  58187. if( NEVER(p==0) ) return;
  58188. db = p->db;
  58189. assert( sqlite3_mutex_held(db->mutex) );
  58190. sqlite3VdbeClearObject(db, p);
  58191. if( p->pPrev ){
  58192. p->pPrev->pNext = p->pNext;
  58193. }else{
  58194. assert( db->pVdbe==p );
  58195. db->pVdbe = p->pNext;
  58196. }
  58197. if( p->pNext ){
  58198. p->pNext->pPrev = p->pPrev;
  58199. }
  58200. p->magic = VDBE_MAGIC_DEAD;
  58201. p->db = 0;
  58202. sqlite3DbFree(db, p);
  58203. }
  58204. /*
  58205. ** Make sure the cursor p is ready to read or write the row to which it
  58206. ** was last positioned. Return an error code if an OOM fault or I/O error
  58207. ** prevents us from positioning the cursor to its correct position.
  58208. **
  58209. ** If a MoveTo operation is pending on the given cursor, then do that
  58210. ** MoveTo now. If no move is pending, check to see if the row has been
  58211. ** deleted out from under the cursor and if it has, mark the row as
  58212. ** a NULL row.
  58213. **
  58214. ** If the cursor is already pointing to the correct row and that row has
  58215. ** not been deleted out from under the cursor, then this routine is a no-op.
  58216. */
  58217. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  58218. if( p->deferredMoveto ){
  58219. int res, rc;
  58220. #ifdef SQLITE_TEST
  58221. extern int sqlite3_search_count;
  58222. #endif
  58223. assert( p->isTable );
  58224. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  58225. if( rc ) return rc;
  58226. p->lastRowid = p->movetoTarget;
  58227. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  58228. p->rowidIsValid = 1;
  58229. #ifdef SQLITE_TEST
  58230. sqlite3_search_count++;
  58231. #endif
  58232. p->deferredMoveto = 0;
  58233. p->cacheStatus = CACHE_STALE;
  58234. }else if( ALWAYS(p->pCursor) ){
  58235. int hasMoved;
  58236. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  58237. if( rc ) return rc;
  58238. if( hasMoved ){
  58239. p->cacheStatus = CACHE_STALE;
  58240. p->nullRow = 1;
  58241. }
  58242. }
  58243. return SQLITE_OK;
  58244. }
  58245. /*
  58246. ** The following functions:
  58247. **
  58248. ** sqlite3VdbeSerialType()
  58249. ** sqlite3VdbeSerialTypeLen()
  58250. ** sqlite3VdbeSerialLen()
  58251. ** sqlite3VdbeSerialPut()
  58252. ** sqlite3VdbeSerialGet()
  58253. **
  58254. ** encapsulate the code that serializes values for storage in SQLite
  58255. ** data and index records. Each serialized value consists of a
  58256. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  58257. ** integer, stored as a varint.
  58258. **
  58259. ** In an SQLite index record, the serial type is stored directly before
  58260. ** the blob of data that it corresponds to. In a table record, all serial
  58261. ** types are stored at the start of the record, and the blobs of data at
  58262. ** the end. Hence these functions allow the caller to handle the
  58263. ** serial-type and data blob separately.
  58264. **
  58265. ** The following table describes the various storage classes for data:
  58266. **
  58267. ** serial type bytes of data type
  58268. ** -------------- --------------- ---------------
  58269. ** 0 0 NULL
  58270. ** 1 1 signed integer
  58271. ** 2 2 signed integer
  58272. ** 3 3 signed integer
  58273. ** 4 4 signed integer
  58274. ** 5 6 signed integer
  58275. ** 6 8 signed integer
  58276. ** 7 8 IEEE float
  58277. ** 8 0 Integer constant 0
  58278. ** 9 0 Integer constant 1
  58279. ** 10,11 reserved for expansion
  58280. ** N>=12 and even (N-12)/2 BLOB
  58281. ** N>=13 and odd (N-13)/2 text
  58282. **
  58283. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  58284. ** of SQLite will not understand those serial types.
  58285. */
  58286. /*
  58287. ** Return the serial-type for the value stored in pMem.
  58288. */
  58289. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  58290. int flags = pMem->flags;
  58291. int n;
  58292. if( flags&MEM_Null ){
  58293. return 0;
  58294. }
  58295. if( flags&MEM_Int ){
  58296. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  58297. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  58298. i64 i = pMem->u.i;
  58299. u64 u;
  58300. if( i<0 ){
  58301. if( i<(-MAX_6BYTE) ) return 6;
  58302. /* Previous test prevents: u = -(-9223372036854775808) */
  58303. u = -i;
  58304. }else{
  58305. u = i;
  58306. }
  58307. if( u<=127 ){
  58308. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  58309. }
  58310. if( u<=32767 ) return 2;
  58311. if( u<=8388607 ) return 3;
  58312. if( u<=2147483647 ) return 4;
  58313. if( u<=MAX_6BYTE ) return 5;
  58314. return 6;
  58315. }
  58316. if( flags&MEM_Real ){
  58317. return 7;
  58318. }
  58319. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  58320. n = pMem->n;
  58321. if( flags & MEM_Zero ){
  58322. n += pMem->u.nZero;
  58323. }
  58324. assert( n>=0 );
  58325. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  58326. }
  58327. /*
  58328. ** Return the length of the data corresponding to the supplied serial-type.
  58329. */
  58330. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  58331. if( serial_type>=12 ){
  58332. return (serial_type-12)/2;
  58333. }else{
  58334. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  58335. return aSize[serial_type];
  58336. }
  58337. }
  58338. /*
  58339. ** If we are on an architecture with mixed-endian floating
  58340. ** points (ex: ARM7) then swap the lower 4 bytes with the
  58341. ** upper 4 bytes. Return the result.
  58342. **
  58343. ** For most architectures, this is a no-op.
  58344. **
  58345. ** (later): It is reported to me that the mixed-endian problem
  58346. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  58347. ** that early versions of GCC stored the two words of a 64-bit
  58348. ** float in the wrong order. And that error has been propagated
  58349. ** ever since. The blame is not necessarily with GCC, though.
  58350. ** GCC might have just copying the problem from a prior compiler.
  58351. ** I am also told that newer versions of GCC that follow a different
  58352. ** ABI get the byte order right.
  58353. **
  58354. ** Developers using SQLite on an ARM7 should compile and run their
  58355. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  58356. ** enabled, some asserts below will ensure that the byte order of
  58357. ** floating point values is correct.
  58358. **
  58359. ** (2007-08-30) Frank van Vugt has studied this problem closely
  58360. ** and has send his findings to the SQLite developers. Frank
  58361. ** writes that some Linux kernels offer floating point hardware
  58362. ** emulation that uses only 32-bit mantissas instead of a full
  58363. ** 48-bits as required by the IEEE standard. (This is the
  58364. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  58365. ** byte swapping becomes very complicated. To avoid problems,
  58366. ** the necessary byte swapping is carried out using a 64-bit integer
  58367. ** rather than a 64-bit float. Frank assures us that the code here
  58368. ** works for him. We, the developers, have no way to independently
  58369. ** verify this, but Frank seems to know what he is talking about
  58370. ** so we trust him.
  58371. */
  58372. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  58373. static u64 floatSwap(u64 in){
  58374. union {
  58375. u64 r;
  58376. u32 i[2];
  58377. } u;
  58378. u32 t;
  58379. u.r = in;
  58380. t = u.i[0];
  58381. u.i[0] = u.i[1];
  58382. u.i[1] = t;
  58383. return u.r;
  58384. }
  58385. # define swapMixedEndianFloat(X) X = floatSwap(X)
  58386. #else
  58387. # define swapMixedEndianFloat(X)
  58388. #endif
  58389. /*
  58390. ** Write the serialized data blob for the value stored in pMem into
  58391. ** buf. It is assumed that the caller has allocated sufficient space.
  58392. ** Return the number of bytes written.
  58393. **
  58394. ** nBuf is the amount of space left in buf[]. nBuf must always be
  58395. ** large enough to hold the entire field. Except, if the field is
  58396. ** a blob with a zero-filled tail, then buf[] might be just the right
  58397. ** size to hold everything except for the zero-filled tail. If buf[]
  58398. ** is only big enough to hold the non-zero prefix, then only write that
  58399. ** prefix into buf[]. But if buf[] is large enough to hold both the
  58400. ** prefix and the tail then write the prefix and set the tail to all
  58401. ** zeros.
  58402. **
  58403. ** Return the number of bytes actually written into buf[]. The number
  58404. ** of bytes in the zero-filled tail is included in the return value only
  58405. ** if those bytes were zeroed in buf[].
  58406. */
  58407. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  58408. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  58409. u32 len;
  58410. /* Integer and Real */
  58411. if( serial_type<=7 && serial_type>0 ){
  58412. u64 v;
  58413. u32 i;
  58414. if( serial_type==7 ){
  58415. assert( sizeof(v)==sizeof(pMem->r) );
  58416. memcpy(&v, &pMem->r, sizeof(v));
  58417. swapMixedEndianFloat(v);
  58418. }else{
  58419. v = pMem->u.i;
  58420. }
  58421. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  58422. assert( len<=(u32)nBuf );
  58423. while( i-- ){
  58424. buf[i] = (u8)(v&0xFF);
  58425. v >>= 8;
  58426. }
  58427. return len;
  58428. }
  58429. /* String or blob */
  58430. if( serial_type>=12 ){
  58431. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  58432. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  58433. assert( pMem->n<=nBuf );
  58434. len = pMem->n;
  58435. memcpy(buf, pMem->z, len);
  58436. if( pMem->flags & MEM_Zero ){
  58437. len += pMem->u.nZero;
  58438. assert( nBuf>=0 );
  58439. if( len > (u32)nBuf ){
  58440. len = (u32)nBuf;
  58441. }
  58442. memset(&buf[pMem->n], 0, len-pMem->n);
  58443. }
  58444. return len;
  58445. }
  58446. /* NULL or constants 0 or 1 */
  58447. return 0;
  58448. }
  58449. /*
  58450. ** Deserialize the data blob pointed to by buf as serial type serial_type
  58451. ** and store the result in pMem. Return the number of bytes read.
  58452. */
  58453. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  58454. const unsigned char *buf, /* Buffer to deserialize from */
  58455. u32 serial_type, /* Serial type to deserialize */
  58456. Mem *pMem /* Memory cell to write value into */
  58457. ){
  58458. switch( serial_type ){
  58459. case 10: /* Reserved for future use */
  58460. case 11: /* Reserved for future use */
  58461. case 0: { /* NULL */
  58462. pMem->flags = MEM_Null;
  58463. break;
  58464. }
  58465. case 1: { /* 1-byte signed integer */
  58466. pMem->u.i = (signed char)buf[0];
  58467. pMem->flags = MEM_Int;
  58468. return 1;
  58469. }
  58470. case 2: { /* 2-byte signed integer */
  58471. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  58472. pMem->flags = MEM_Int;
  58473. return 2;
  58474. }
  58475. case 3: { /* 3-byte signed integer */
  58476. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  58477. pMem->flags = MEM_Int;
  58478. return 3;
  58479. }
  58480. case 4: { /* 4-byte signed integer */
  58481. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  58482. pMem->flags = MEM_Int;
  58483. return 4;
  58484. }
  58485. case 5: { /* 6-byte signed integer */
  58486. u64 x = (((signed char)buf[0])<<8) | buf[1];
  58487. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  58488. x = (x<<32) | y;
  58489. pMem->u.i = *(i64*)&x;
  58490. pMem->flags = MEM_Int;
  58491. return 6;
  58492. }
  58493. case 6: /* 8-byte signed integer */
  58494. case 7: { /* IEEE floating point */
  58495. u64 x;
  58496. u32 y;
  58497. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  58498. /* Verify that integers and floating point values use the same
  58499. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  58500. ** defined that 64-bit floating point values really are mixed
  58501. ** endian.
  58502. */
  58503. static const u64 t1 = ((u64)0x3ff00000)<<32;
  58504. static const double r1 = 1.0;
  58505. u64 t2 = t1;
  58506. swapMixedEndianFloat(t2);
  58507. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  58508. #endif
  58509. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  58510. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  58511. x = (x<<32) | y;
  58512. if( serial_type==6 ){
  58513. pMem->u.i = *(i64*)&x;
  58514. pMem->flags = MEM_Int;
  58515. }else{
  58516. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  58517. swapMixedEndianFloat(x);
  58518. memcpy(&pMem->r, &x, sizeof(x));
  58519. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  58520. }
  58521. return 8;
  58522. }
  58523. case 8: /* Integer 0 */
  58524. case 9: { /* Integer 1 */
  58525. pMem->u.i = serial_type-8;
  58526. pMem->flags = MEM_Int;
  58527. return 0;
  58528. }
  58529. default: {
  58530. u32 len = (serial_type-12)/2;
  58531. pMem->z = (char *)buf;
  58532. pMem->n = len;
  58533. pMem->xDel = 0;
  58534. if( serial_type&0x01 ){
  58535. pMem->flags = MEM_Str | MEM_Ephem;
  58536. }else{
  58537. pMem->flags = MEM_Blob | MEM_Ephem;
  58538. }
  58539. return len;
  58540. }
  58541. }
  58542. return 0;
  58543. }
  58544. /*
  58545. ** This routine is used to allocate sufficient space for an UnpackedRecord
  58546. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  58547. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  58548. **
  58549. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  58550. ** the unaligned buffer passed via the second and third arguments (presumably
  58551. ** stack space). If the former, then *ppFree is set to a pointer that should
  58552. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  58553. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  58554. ** before returning.
  58555. **
  58556. ** If an OOM error occurs, NULL is returned.
  58557. */
  58558. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  58559. KeyInfo *pKeyInfo, /* Description of the record */
  58560. char *pSpace, /* Unaligned space available */
  58561. int szSpace, /* Size of pSpace[] in bytes */
  58562. char **ppFree /* OUT: Caller should free this pointer */
  58563. ){
  58564. UnpackedRecord *p; /* Unpacked record to return */
  58565. int nOff; /* Increment pSpace by nOff to align it */
  58566. int nByte; /* Number of bytes required for *p */
  58567. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  58568. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  58569. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  58570. */
  58571. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  58572. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  58573. if( nByte>szSpace+nOff ){
  58574. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  58575. *ppFree = (char *)p;
  58576. if( !p ) return 0;
  58577. }else{
  58578. p = (UnpackedRecord*)&pSpace[nOff];
  58579. *ppFree = 0;
  58580. }
  58581. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  58582. assert( pKeyInfo->aSortOrder!=0 );
  58583. p->pKeyInfo = pKeyInfo;
  58584. p->nField = pKeyInfo->nField + 1;
  58585. return p;
  58586. }
  58587. /*
  58588. ** Given the nKey-byte encoding of a record in pKey[], populate the
  58589. ** UnpackedRecord structure indicated by the fourth argument with the
  58590. ** contents of the decoded record.
  58591. */
  58592. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  58593. KeyInfo *pKeyInfo, /* Information about the record format */
  58594. int nKey, /* Size of the binary record */
  58595. const void *pKey, /* The binary record */
  58596. UnpackedRecord *p /* Populate this structure before returning. */
  58597. ){
  58598. const unsigned char *aKey = (const unsigned char *)pKey;
  58599. int d;
  58600. u32 idx; /* Offset in aKey[] to read from */
  58601. u16 u; /* Unsigned loop counter */
  58602. u32 szHdr;
  58603. Mem *pMem = p->aMem;
  58604. p->flags = 0;
  58605. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58606. idx = getVarint32(aKey, szHdr);
  58607. d = szHdr;
  58608. u = 0;
  58609. while( idx<szHdr && u<p->nField && d<=nKey ){
  58610. u32 serial_type;
  58611. idx += getVarint32(&aKey[idx], serial_type);
  58612. pMem->enc = pKeyInfo->enc;
  58613. pMem->db = pKeyInfo->db;
  58614. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  58615. pMem->zMalloc = 0;
  58616. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  58617. pMem++;
  58618. u++;
  58619. }
  58620. assert( u<=pKeyInfo->nField + 1 );
  58621. p->nField = u;
  58622. }
  58623. /*
  58624. ** This function compares the two table rows or index records
  58625. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  58626. ** or positive integer if key1 is less than, equal to or
  58627. ** greater than key2. The {nKey1, pKey1} key must be a blob
  58628. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  58629. ** key must be a parsed key such as obtained from
  58630. ** sqlite3VdbeParseRecord.
  58631. **
  58632. ** Key1 and Key2 do not have to contain the same number of fields.
  58633. ** The key with fewer fields is usually compares less than the
  58634. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  58635. ** and the common prefixes are equal, then key1 is less than key2.
  58636. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  58637. ** equal, then the keys are considered to be equal and
  58638. ** the parts beyond the common prefix are ignored.
  58639. */
  58640. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  58641. int nKey1, const void *pKey1, /* Left key */
  58642. UnpackedRecord *pPKey2 /* Right key */
  58643. ){
  58644. int d1; /* Offset into aKey[] of next data element */
  58645. u32 idx1; /* Offset into aKey[] of next header element */
  58646. u32 szHdr1; /* Number of bytes in header */
  58647. int i = 0;
  58648. int nField;
  58649. int rc = 0;
  58650. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  58651. KeyInfo *pKeyInfo;
  58652. Mem mem1;
  58653. pKeyInfo = pPKey2->pKeyInfo;
  58654. mem1.enc = pKeyInfo->enc;
  58655. mem1.db = pKeyInfo->db;
  58656. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  58657. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  58658. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  58659. ** We could initialize it, as shown here, to silence those complaints.
  58660. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  58661. ** the unnecessary initialization has a measurable negative performance
  58662. ** impact, since this routine is a very high runner. And so, we choose
  58663. ** to ignore the compiler warnings and leave this variable uninitialized.
  58664. */
  58665. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  58666. idx1 = getVarint32(aKey1, szHdr1);
  58667. d1 = szHdr1;
  58668. nField = pKeyInfo->nField;
  58669. assert( pKeyInfo->aSortOrder!=0 );
  58670. while( idx1<szHdr1 && i<pPKey2->nField ){
  58671. u32 serial_type1;
  58672. /* Read the serial types for the next element in each key. */
  58673. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  58674. if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  58675. /* Extract the values to be compared.
  58676. */
  58677. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  58678. /* Do the comparison
  58679. */
  58680. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  58681. i<nField ? pKeyInfo->aColl[i] : 0);
  58682. if( rc!=0 ){
  58683. assert( mem1.zMalloc==0 ); /* See comment below */
  58684. /* Invert the result if we are using DESC sort order. */
  58685. if( i<nField && pKeyInfo->aSortOrder[i] ){
  58686. rc = -rc;
  58687. }
  58688. /* If the PREFIX_SEARCH flag is set and all fields except the final
  58689. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  58690. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  58691. ** This is used by the OP_IsUnique opcode.
  58692. */
  58693. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  58694. assert( idx1==szHdr1 && rc );
  58695. assert( mem1.flags & MEM_Int );
  58696. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  58697. pPKey2->rowid = mem1.u.i;
  58698. }
  58699. return rc;
  58700. }
  58701. i++;
  58702. }
  58703. /* No memory allocation is ever used on mem1. Prove this using
  58704. ** the following assert(). If the assert() fails, it indicates a
  58705. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  58706. */
  58707. assert( mem1.zMalloc==0 );
  58708. /* rc==0 here means that one of the keys ran out of fields and
  58709. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  58710. ** flag is set, then break the tie by treating key2 as larger.
  58711. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  58712. ** are considered to be equal. Otherwise, the longer key is the
  58713. ** larger. As it happens, the pPKey2 will always be the longer
  58714. ** if there is a difference.
  58715. */
  58716. assert( rc==0 );
  58717. if( pPKey2->flags & UNPACKED_INCRKEY ){
  58718. rc = -1;
  58719. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  58720. /* Leave rc==0 */
  58721. }else if( idx1<szHdr1 ){
  58722. rc = 1;
  58723. }
  58724. return rc;
  58725. }
  58726. /*
  58727. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  58728. ** Read the rowid (the last field in the record) and store it in *rowid.
  58729. ** Return SQLITE_OK if everything works, or an error code otherwise.
  58730. **
  58731. ** pCur might be pointing to text obtained from a corrupt database file.
  58732. ** So the content cannot be trusted. Do appropriate checks on the content.
  58733. */
  58734. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  58735. i64 nCellKey = 0;
  58736. int rc;
  58737. u32 szHdr; /* Size of the header */
  58738. u32 typeRowid; /* Serial type of the rowid */
  58739. u32 lenRowid; /* Size of the rowid */
  58740. Mem m, v;
  58741. UNUSED_PARAMETER(db);
  58742. /* Get the size of the index entry. Only indices entries of less
  58743. ** than 2GiB are support - anything large must be database corruption.
  58744. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  58745. ** this code can safely assume that nCellKey is 32-bits
  58746. */
  58747. assert( sqlite3BtreeCursorIsValid(pCur) );
  58748. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  58749. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  58750. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  58751. /* Read in the complete content of the index entry */
  58752. memset(&m, 0, sizeof(m));
  58753. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  58754. if( rc ){
  58755. return rc;
  58756. }
  58757. /* The index entry must begin with a header size */
  58758. (void)getVarint32((u8*)m.z, szHdr);
  58759. testcase( szHdr==3 );
  58760. testcase( szHdr==m.n );
  58761. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  58762. goto idx_rowid_corruption;
  58763. }
  58764. /* The last field of the index should be an integer - the ROWID.
  58765. ** Verify that the last entry really is an integer. */
  58766. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  58767. testcase( typeRowid==1 );
  58768. testcase( typeRowid==2 );
  58769. testcase( typeRowid==3 );
  58770. testcase( typeRowid==4 );
  58771. testcase( typeRowid==5 );
  58772. testcase( typeRowid==6 );
  58773. testcase( typeRowid==8 );
  58774. testcase( typeRowid==9 );
  58775. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  58776. goto idx_rowid_corruption;
  58777. }
  58778. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  58779. testcase( (u32)m.n==szHdr+lenRowid );
  58780. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  58781. goto idx_rowid_corruption;
  58782. }
  58783. /* Fetch the integer off the end of the index record */
  58784. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  58785. *rowid = v.u.i;
  58786. sqlite3VdbeMemRelease(&m);
  58787. return SQLITE_OK;
  58788. /* Jump here if database corruption is detected after m has been
  58789. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  58790. idx_rowid_corruption:
  58791. testcase( m.zMalloc!=0 );
  58792. sqlite3VdbeMemRelease(&m);
  58793. return SQLITE_CORRUPT_BKPT;
  58794. }
  58795. /*
  58796. ** Compare the key of the index entry that cursor pC is pointing to against
  58797. ** the key string in pUnpacked. Write into *pRes a number
  58798. ** that is negative, zero, or positive if pC is less than, equal to,
  58799. ** or greater than pUnpacked. Return SQLITE_OK on success.
  58800. **
  58801. ** pUnpacked is either created without a rowid or is truncated so that it
  58802. ** omits the rowid at the end. The rowid at the end of the index entry
  58803. ** is ignored as well. Hence, this routine only compares the prefixes
  58804. ** of the keys prior to the final rowid, not the entire key.
  58805. */
  58806. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  58807. VdbeCursor *pC, /* The cursor to compare against */
  58808. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  58809. int *res /* Write the comparison result here */
  58810. ){
  58811. i64 nCellKey = 0;
  58812. int rc;
  58813. BtCursor *pCur = pC->pCursor;
  58814. Mem m;
  58815. assert( sqlite3BtreeCursorIsValid(pCur) );
  58816. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  58817. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  58818. /* nCellKey will always be between 0 and 0xffffffff because of the say
  58819. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  58820. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  58821. *res = 0;
  58822. return SQLITE_CORRUPT_BKPT;
  58823. }
  58824. memset(&m, 0, sizeof(m));
  58825. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  58826. if( rc ){
  58827. return rc;
  58828. }
  58829. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  58830. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  58831. sqlite3VdbeMemRelease(&m);
  58832. return SQLITE_OK;
  58833. }
  58834. /*
  58835. ** This routine sets the value to be returned by subsequent calls to
  58836. ** sqlite3_changes() on the database handle 'db'.
  58837. */
  58838. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  58839. assert( sqlite3_mutex_held(db->mutex) );
  58840. db->nChange = nChange;
  58841. db->nTotalChange += nChange;
  58842. }
  58843. /*
  58844. ** Set a flag in the vdbe to update the change counter when it is finalised
  58845. ** or reset.
  58846. */
  58847. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  58848. v->changeCntOn = 1;
  58849. }
  58850. /*
  58851. ** Mark every prepared statement associated with a database connection
  58852. ** as expired.
  58853. **
  58854. ** An expired statement means that recompilation of the statement is
  58855. ** recommend. Statements expire when things happen that make their
  58856. ** programs obsolete. Removing user-defined functions or collating
  58857. ** sequences, or changing an authorization function are the types of
  58858. ** things that make prepared statements obsolete.
  58859. */
  58860. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  58861. Vdbe *p;
  58862. for(p = db->pVdbe; p; p=p->pNext){
  58863. p->expired = 1;
  58864. }
  58865. }
  58866. /*
  58867. ** Return the database associated with the Vdbe.
  58868. */
  58869. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  58870. return v->db;
  58871. }
  58872. /*
  58873. ** Return a pointer to an sqlite3_value structure containing the value bound
  58874. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  58875. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  58876. ** constants) to the value before returning it.
  58877. **
  58878. ** The returned value must be freed by the caller using sqlite3ValueFree().
  58879. */
  58880. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
  58881. assert( iVar>0 );
  58882. if( v ){
  58883. Mem *pMem = &v->aVar[iVar-1];
  58884. if( 0==(pMem->flags & MEM_Null) ){
  58885. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  58886. if( pRet ){
  58887. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  58888. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  58889. sqlite3VdbeMemStoreType((Mem *)pRet);
  58890. }
  58891. return pRet;
  58892. }
  58893. }
  58894. return 0;
  58895. }
  58896. /*
  58897. ** Configure SQL variable iVar so that binding a new value to it signals
  58898. ** to sqlite3_reoptimize() that re-preparing the statement may result
  58899. ** in a better query plan.
  58900. */
  58901. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  58902. assert( iVar>0 );
  58903. if( iVar>32 ){
  58904. v->expmask = 0xffffffff;
  58905. }else{
  58906. v->expmask |= ((u32)1 << (iVar-1));
  58907. }
  58908. }
  58909. /************** End of vdbeaux.c *********************************************/
  58910. /************** Begin file vdbeapi.c *****************************************/
  58911. /*
  58912. ** 2004 May 26
  58913. **
  58914. ** The author disclaims copyright to this source code. In place of
  58915. ** a legal notice, here is a blessing:
  58916. **
  58917. ** May you do good and not evil.
  58918. ** May you find forgiveness for yourself and forgive others.
  58919. ** May you share freely, never taking more than you give.
  58920. **
  58921. *************************************************************************
  58922. **
  58923. ** This file contains code use to implement APIs that are part of the
  58924. ** VDBE.
  58925. */
  58926. #ifndef SQLITE_OMIT_DEPRECATED
  58927. /*
  58928. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  58929. ** to be recompiled. A statement needs to be recompiled whenever the
  58930. ** execution environment changes in a way that would alter the program
  58931. ** that sqlite3_prepare() generates. For example, if new functions or
  58932. ** collating sequences are registered or if an authorizer function is
  58933. ** added or changed.
  58934. */
  58935. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  58936. Vdbe *p = (Vdbe*)pStmt;
  58937. return p==0 || p->expired;
  58938. }
  58939. #endif
  58940. /*
  58941. ** Check on a Vdbe to make sure it has not been finalized. Log
  58942. ** an error and return true if it has been finalized (or is otherwise
  58943. ** invalid). Return false if it is ok.
  58944. */
  58945. static int vdbeSafety(Vdbe *p){
  58946. if( p->db==0 ){
  58947. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  58948. return 1;
  58949. }else{
  58950. return 0;
  58951. }
  58952. }
  58953. static int vdbeSafetyNotNull(Vdbe *p){
  58954. if( p==0 ){
  58955. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  58956. return 1;
  58957. }else{
  58958. return vdbeSafety(p);
  58959. }
  58960. }
  58961. /*
  58962. ** The following routine destroys a virtual machine that is created by
  58963. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  58964. ** success/failure code that describes the result of executing the virtual
  58965. ** machine.
  58966. **
  58967. ** This routine sets the error code and string returned by
  58968. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  58969. */
  58970. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  58971. int rc;
  58972. if( pStmt==0 ){
  58973. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  58974. ** pointer is a harmless no-op. */
  58975. rc = SQLITE_OK;
  58976. }else{
  58977. Vdbe *v = (Vdbe*)pStmt;
  58978. sqlite3 *db = v->db;
  58979. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  58980. sqlite3_mutex_enter(db->mutex);
  58981. rc = sqlite3VdbeFinalize(v);
  58982. rc = sqlite3ApiExit(db, rc);
  58983. sqlite3LeaveMutexAndCloseZombie(db);
  58984. }
  58985. return rc;
  58986. }
  58987. /*
  58988. ** Terminate the current execution of an SQL statement and reset it
  58989. ** back to its starting state so that it can be reused. A success code from
  58990. ** the prior execution is returned.
  58991. **
  58992. ** This routine sets the error code and string returned by
  58993. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  58994. */
  58995. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  58996. int rc;
  58997. if( pStmt==0 ){
  58998. rc = SQLITE_OK;
  58999. }else{
  59000. Vdbe *v = (Vdbe*)pStmt;
  59001. sqlite3_mutex_enter(v->db->mutex);
  59002. rc = sqlite3VdbeReset(v);
  59003. sqlite3VdbeRewind(v);
  59004. assert( (rc & (v->db->errMask))==rc );
  59005. rc = sqlite3ApiExit(v->db, rc);
  59006. sqlite3_mutex_leave(v->db->mutex);
  59007. }
  59008. return rc;
  59009. }
  59010. /*
  59011. ** Set all the parameters in the compiled SQL statement to NULL.
  59012. */
  59013. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  59014. int i;
  59015. int rc = SQLITE_OK;
  59016. Vdbe *p = (Vdbe*)pStmt;
  59017. #if SQLITE_THREADSAFE
  59018. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  59019. #endif
  59020. sqlite3_mutex_enter(mutex);
  59021. for(i=0; i<p->nVar; i++){
  59022. sqlite3VdbeMemRelease(&p->aVar[i]);
  59023. p->aVar[i].flags = MEM_Null;
  59024. }
  59025. if( p->isPrepareV2 && p->expmask ){
  59026. p->expired = 1;
  59027. }
  59028. sqlite3_mutex_leave(mutex);
  59029. return rc;
  59030. }
  59031. /**************************** sqlite3_value_ *******************************
  59032. ** The following routines extract information from a Mem or sqlite3_value
  59033. ** structure.
  59034. */
  59035. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  59036. Mem *p = (Mem*)pVal;
  59037. if( p->flags & (MEM_Blob|MEM_Str) ){
  59038. sqlite3VdbeMemExpandBlob(p);
  59039. p->flags &= ~MEM_Str;
  59040. p->flags |= MEM_Blob;
  59041. return p->n ? p->z : 0;
  59042. }else{
  59043. return sqlite3_value_text(pVal);
  59044. }
  59045. }
  59046. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  59047. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  59048. }
  59049. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  59050. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  59051. }
  59052. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  59053. return sqlite3VdbeRealValue((Mem*)pVal);
  59054. }
  59055. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  59056. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  59057. }
  59058. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  59059. return sqlite3VdbeIntValue((Mem*)pVal);
  59060. }
  59061. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  59062. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  59063. }
  59064. #ifndef SQLITE_OMIT_UTF16
  59065. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  59066. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  59067. }
  59068. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  59069. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  59070. }
  59071. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  59072. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  59073. }
  59074. #endif /* SQLITE_OMIT_UTF16 */
  59075. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  59076. return pVal->type;
  59077. }
  59078. /**************************** sqlite3_result_ *******************************
  59079. ** The following routines are used by user-defined functions to specify
  59080. ** the function result.
  59081. **
  59082. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  59083. ** result as a string or blob but if the string or blob is too large, it
  59084. ** then sets the error code to SQLITE_TOOBIG
  59085. */
  59086. static void setResultStrOrError(
  59087. sqlite3_context *pCtx, /* Function context */
  59088. const char *z, /* String pointer */
  59089. int n, /* Bytes in string, or negative */
  59090. u8 enc, /* Encoding of z. 0 for BLOBs */
  59091. void (*xDel)(void*) /* Destructor function */
  59092. ){
  59093. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  59094. sqlite3_result_error_toobig(pCtx);
  59095. }
  59096. }
  59097. SQLITE_API void sqlite3_result_blob(
  59098. sqlite3_context *pCtx,
  59099. const void *z,
  59100. int n,
  59101. void (*xDel)(void *)
  59102. ){
  59103. assert( n>=0 );
  59104. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59105. setResultStrOrError(pCtx, z, n, 0, xDel);
  59106. }
  59107. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  59108. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59109. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  59110. }
  59111. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  59112. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59113. pCtx->isError = SQLITE_ERROR;
  59114. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  59115. }
  59116. #ifndef SQLITE_OMIT_UTF16
  59117. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  59118. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59119. pCtx->isError = SQLITE_ERROR;
  59120. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  59121. }
  59122. #endif
  59123. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  59124. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59125. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  59126. }
  59127. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  59128. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59129. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  59130. }
  59131. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  59132. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59133. sqlite3VdbeMemSetNull(&pCtx->s);
  59134. }
  59135. SQLITE_API void sqlite3_result_text(
  59136. sqlite3_context *pCtx,
  59137. const char *z,
  59138. int n,
  59139. void (*xDel)(void *)
  59140. ){
  59141. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59142. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  59143. }
  59144. #ifndef SQLITE_OMIT_UTF16
  59145. SQLITE_API void sqlite3_result_text16(
  59146. sqlite3_context *pCtx,
  59147. const void *z,
  59148. int n,
  59149. void (*xDel)(void *)
  59150. ){
  59151. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59152. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  59153. }
  59154. SQLITE_API void sqlite3_result_text16be(
  59155. sqlite3_context *pCtx,
  59156. const void *z,
  59157. int n,
  59158. void (*xDel)(void *)
  59159. ){
  59160. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59161. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  59162. }
  59163. SQLITE_API void sqlite3_result_text16le(
  59164. sqlite3_context *pCtx,
  59165. const void *z,
  59166. int n,
  59167. void (*xDel)(void *)
  59168. ){
  59169. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59170. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  59171. }
  59172. #endif /* SQLITE_OMIT_UTF16 */
  59173. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  59174. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59175. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  59176. }
  59177. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  59178. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59179. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  59180. }
  59181. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  59182. pCtx->isError = errCode;
  59183. if( pCtx->s.flags & MEM_Null ){
  59184. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  59185. SQLITE_UTF8, SQLITE_STATIC);
  59186. }
  59187. }
  59188. /* Force an SQLITE_TOOBIG error. */
  59189. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  59190. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59191. pCtx->isError = SQLITE_TOOBIG;
  59192. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  59193. SQLITE_UTF8, SQLITE_STATIC);
  59194. }
  59195. /* An SQLITE_NOMEM error. */
  59196. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  59197. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59198. sqlite3VdbeMemSetNull(&pCtx->s);
  59199. pCtx->isError = SQLITE_NOMEM;
  59200. pCtx->s.db->mallocFailed = 1;
  59201. }
  59202. /*
  59203. ** This function is called after a transaction has been committed. It
  59204. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  59205. */
  59206. static int doWalCallbacks(sqlite3 *db){
  59207. int rc = SQLITE_OK;
  59208. #ifndef SQLITE_OMIT_WAL
  59209. int i;
  59210. for(i=0; i<db->nDb; i++){
  59211. Btree *pBt = db->aDb[i].pBt;
  59212. if( pBt ){
  59213. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  59214. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  59215. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  59216. }
  59217. }
  59218. }
  59219. #endif
  59220. return rc;
  59221. }
  59222. /*
  59223. ** Execute the statement pStmt, either until a row of data is ready, the
  59224. ** statement is completely executed or an error occurs.
  59225. **
  59226. ** This routine implements the bulk of the logic behind the sqlite_step()
  59227. ** API. The only thing omitted is the automatic recompile if a
  59228. ** schema change has occurred. That detail is handled by the
  59229. ** outer sqlite3_step() wrapper procedure.
  59230. */
  59231. static int sqlite3Step(Vdbe *p){
  59232. sqlite3 *db;
  59233. int rc;
  59234. assert(p);
  59235. if( p->magic!=VDBE_MAGIC_RUN ){
  59236. /* We used to require that sqlite3_reset() be called before retrying
  59237. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  59238. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  59239. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  59240. ** This "automatic-reset" change is not technically an incompatibility,
  59241. ** since any application that receives an SQLITE_MISUSE is broken by
  59242. ** definition.
  59243. **
  59244. ** Nevertheless, some published applications that were originally written
  59245. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  59246. ** returns, and those were broken by the automatic-reset change. As a
  59247. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  59248. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  59249. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  59250. ** or SQLITE_BUSY error.
  59251. */
  59252. #ifdef SQLITE_OMIT_AUTORESET
  59253. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  59254. sqlite3_reset((sqlite3_stmt*)p);
  59255. }else{
  59256. return SQLITE_MISUSE_BKPT;
  59257. }
  59258. #else
  59259. sqlite3_reset((sqlite3_stmt*)p);
  59260. #endif
  59261. }
  59262. /* Check that malloc() has not failed. If it has, return early. */
  59263. db = p->db;
  59264. if( db->mallocFailed ){
  59265. p->rc = SQLITE_NOMEM;
  59266. return SQLITE_NOMEM;
  59267. }
  59268. if( p->pc<=0 && p->expired ){
  59269. p->rc = SQLITE_SCHEMA;
  59270. rc = SQLITE_ERROR;
  59271. goto end_of_step;
  59272. }
  59273. if( p->pc<0 ){
  59274. /* If there are no other statements currently running, then
  59275. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  59276. ** from interrupting a statement that has not yet started.
  59277. */
  59278. if( db->activeVdbeCnt==0 ){
  59279. db->u1.isInterrupted = 0;
  59280. }
  59281. assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
  59282. #ifndef SQLITE_OMIT_TRACE
  59283. if( db->xProfile && !db->init.busy ){
  59284. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  59285. }
  59286. #endif
  59287. db->activeVdbeCnt++;
  59288. if( p->readOnly==0 ) db->writeVdbeCnt++;
  59289. p->pc = 0;
  59290. }
  59291. #ifndef SQLITE_OMIT_EXPLAIN
  59292. if( p->explain ){
  59293. rc = sqlite3VdbeList(p);
  59294. }else
  59295. #endif /* SQLITE_OMIT_EXPLAIN */
  59296. {
  59297. db->vdbeExecCnt++;
  59298. rc = sqlite3VdbeExec(p);
  59299. db->vdbeExecCnt--;
  59300. }
  59301. #ifndef SQLITE_OMIT_TRACE
  59302. /* Invoke the profile callback if there is one
  59303. */
  59304. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  59305. sqlite3_int64 iNow;
  59306. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  59307. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  59308. }
  59309. #endif
  59310. if( rc==SQLITE_DONE ){
  59311. assert( p->rc==SQLITE_OK );
  59312. p->rc = doWalCallbacks(db);
  59313. if( p->rc!=SQLITE_OK ){
  59314. rc = SQLITE_ERROR;
  59315. }
  59316. }
  59317. db->errCode = rc;
  59318. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  59319. p->rc = SQLITE_NOMEM;
  59320. }
  59321. end_of_step:
  59322. /* At this point local variable rc holds the value that should be
  59323. ** returned if this statement was compiled using the legacy
  59324. ** sqlite3_prepare() interface. According to the docs, this can only
  59325. ** be one of the values in the first assert() below. Variable p->rc
  59326. ** contains the value that would be returned if sqlite3_finalize()
  59327. ** were called on statement p.
  59328. */
  59329. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  59330. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  59331. );
  59332. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  59333. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  59334. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  59335. ** error has occurred, then return the error code in p->rc to the
  59336. ** caller. Set the error code in the database handle to the same value.
  59337. */
  59338. rc = sqlite3VdbeTransferError(p);
  59339. }
  59340. return (rc&db->errMask);
  59341. }
  59342. /*
  59343. ** This is the top-level implementation of sqlite3_step(). Call
  59344. ** sqlite3Step() to do most of the work. If a schema error occurs,
  59345. ** call sqlite3Reprepare() and try again.
  59346. */
  59347. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  59348. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  59349. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  59350. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  59351. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  59352. sqlite3 *db; /* The database connection */
  59353. if( vdbeSafetyNotNull(v) ){
  59354. return SQLITE_MISUSE_BKPT;
  59355. }
  59356. db = v->db;
  59357. sqlite3_mutex_enter(db->mutex);
  59358. v->doingRerun = 0;
  59359. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  59360. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  59361. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  59362. sqlite3_reset(pStmt);
  59363. v->doingRerun = 1;
  59364. assert( v->expired==0 );
  59365. }
  59366. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  59367. /* This case occurs after failing to recompile an sql statement.
  59368. ** The error message from the SQL compiler has already been loaded
  59369. ** into the database handle. This block copies the error message
  59370. ** from the database handle into the statement and sets the statement
  59371. ** program counter to 0 to ensure that when the statement is
  59372. ** finalized or reset the parser error message is available via
  59373. ** sqlite3_errmsg() and sqlite3_errcode().
  59374. */
  59375. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  59376. sqlite3DbFree(db, v->zErrMsg);
  59377. if( !db->mallocFailed ){
  59378. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  59379. v->rc = rc2;
  59380. } else {
  59381. v->zErrMsg = 0;
  59382. v->rc = rc = SQLITE_NOMEM;
  59383. }
  59384. }
  59385. rc = sqlite3ApiExit(db, rc);
  59386. sqlite3_mutex_leave(db->mutex);
  59387. return rc;
  59388. }
  59389. /*
  59390. ** Extract the user data from a sqlite3_context structure and return a
  59391. ** pointer to it.
  59392. */
  59393. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  59394. assert( p && p->pFunc );
  59395. return p->pFunc->pUserData;
  59396. }
  59397. /*
  59398. ** Extract the user data from a sqlite3_context structure and return a
  59399. ** pointer to it.
  59400. **
  59401. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  59402. ** returns a copy of the pointer to the database connection (the 1st
  59403. ** parameter) of the sqlite3_create_function() and
  59404. ** sqlite3_create_function16() routines that originally registered the
  59405. ** application defined function.
  59406. */
  59407. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  59408. assert( p && p->pFunc );
  59409. return p->s.db;
  59410. }
  59411. /*
  59412. ** The following is the implementation of an SQL function that always
  59413. ** fails with an error message stating that the function is used in the
  59414. ** wrong context. The sqlite3_overload_function() API might construct
  59415. ** SQL function that use this routine so that the functions will exist
  59416. ** for name resolution but are actually overloaded by the xFindFunction
  59417. ** method of virtual tables.
  59418. */
  59419. SQLITE_PRIVATE void sqlite3InvalidFunction(
  59420. sqlite3_context *context, /* The function calling context */
  59421. int NotUsed, /* Number of arguments to the function */
  59422. sqlite3_value **NotUsed2 /* Value of each argument */
  59423. ){
  59424. const char *zName = context->pFunc->zName;
  59425. char *zErr;
  59426. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  59427. zErr = sqlite3_mprintf(
  59428. "unable to use function %s in the requested context", zName);
  59429. sqlite3_result_error(context, zErr, -1);
  59430. sqlite3_free(zErr);
  59431. }
  59432. /*
  59433. ** Allocate or return the aggregate context for a user function. A new
  59434. ** context is allocated on the first call. Subsequent calls return the
  59435. ** same context that was returned on prior calls.
  59436. */
  59437. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  59438. Mem *pMem;
  59439. assert( p && p->pFunc && p->pFunc->xStep );
  59440. assert( sqlite3_mutex_held(p->s.db->mutex) );
  59441. pMem = p->pMem;
  59442. testcase( nByte<0 );
  59443. if( (pMem->flags & MEM_Agg)==0 ){
  59444. if( nByte<=0 ){
  59445. sqlite3VdbeMemReleaseExternal(pMem);
  59446. pMem->flags = MEM_Null;
  59447. pMem->z = 0;
  59448. }else{
  59449. sqlite3VdbeMemGrow(pMem, nByte, 0);
  59450. pMem->flags = MEM_Agg;
  59451. pMem->u.pDef = p->pFunc;
  59452. if( pMem->z ){
  59453. memset(pMem->z, 0, nByte);
  59454. }
  59455. }
  59456. }
  59457. return (void*)pMem->z;
  59458. }
  59459. /*
  59460. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  59461. ** the user-function defined by pCtx.
  59462. */
  59463. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  59464. VdbeFunc *pVdbeFunc;
  59465. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59466. pVdbeFunc = pCtx->pVdbeFunc;
  59467. if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
  59468. return 0;
  59469. }
  59470. return pVdbeFunc->apAux[iArg].pAux;
  59471. }
  59472. /*
  59473. ** Set the auxilary data pointer and delete function, for the iArg'th
  59474. ** argument to the user-function defined by pCtx. Any previous value is
  59475. ** deleted by calling the delete function specified when it was set.
  59476. */
  59477. SQLITE_API void sqlite3_set_auxdata(
  59478. sqlite3_context *pCtx,
  59479. int iArg,
  59480. void *pAux,
  59481. void (*xDelete)(void*)
  59482. ){
  59483. struct AuxData *pAuxData;
  59484. VdbeFunc *pVdbeFunc;
  59485. if( iArg<0 ) goto failed;
  59486. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  59487. pVdbeFunc = pCtx->pVdbeFunc;
  59488. if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
  59489. int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
  59490. int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
  59491. pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
  59492. if( !pVdbeFunc ){
  59493. goto failed;
  59494. }
  59495. pCtx->pVdbeFunc = pVdbeFunc;
  59496. memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
  59497. pVdbeFunc->nAux = iArg+1;
  59498. pVdbeFunc->pFunc = pCtx->pFunc;
  59499. }
  59500. pAuxData = &pVdbeFunc->apAux[iArg];
  59501. if( pAuxData->pAux && pAuxData->xDelete ){
  59502. pAuxData->xDelete(pAuxData->pAux);
  59503. }
  59504. pAuxData->pAux = pAux;
  59505. pAuxData->xDelete = xDelete;
  59506. return;
  59507. failed:
  59508. if( xDelete ){
  59509. xDelete(pAux);
  59510. }
  59511. }
  59512. #ifndef SQLITE_OMIT_DEPRECATED
  59513. /*
  59514. ** Return the number of times the Step function of a aggregate has been
  59515. ** called.
  59516. **
  59517. ** This function is deprecated. Do not use it for new code. It is
  59518. ** provide only to avoid breaking legacy code. New aggregate function
  59519. ** implementations should keep their own counts within their aggregate
  59520. ** context.
  59521. */
  59522. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  59523. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  59524. return p->pMem->n;
  59525. }
  59526. #endif
  59527. /*
  59528. ** Return the number of columns in the result set for the statement pStmt.
  59529. */
  59530. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  59531. Vdbe *pVm = (Vdbe *)pStmt;
  59532. return pVm ? pVm->nResColumn : 0;
  59533. }
  59534. /*
  59535. ** Return the number of values available from the current row of the
  59536. ** currently executing statement pStmt.
  59537. */
  59538. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  59539. Vdbe *pVm = (Vdbe *)pStmt;
  59540. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  59541. return pVm->nResColumn;
  59542. }
  59543. /*
  59544. ** Check to see if column iCol of the given statement is valid. If
  59545. ** it is, return a pointer to the Mem for the value of that column.
  59546. ** If iCol is not valid, return a pointer to a Mem which has a value
  59547. ** of NULL.
  59548. */
  59549. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  59550. Vdbe *pVm;
  59551. Mem *pOut;
  59552. pVm = (Vdbe *)pStmt;
  59553. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  59554. sqlite3_mutex_enter(pVm->db->mutex);
  59555. pOut = &pVm->pResultSet[i];
  59556. }else{
  59557. /* If the value passed as the second argument is out of range, return
  59558. ** a pointer to the following static Mem object which contains the
  59559. ** value SQL NULL. Even though the Mem structure contains an element
  59560. ** of type i64, on certain architectures (x86) with certain compiler
  59561. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  59562. ** instead of an 8-byte one. This all works fine, except that when
  59563. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  59564. ** that a Mem structure is located on an 8-byte boundary. To prevent
  59565. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  59566. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  59567. ** __attribute__((aligned(8))) macro. */
  59568. static const Mem nullMem
  59569. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  59570. __attribute__((aligned(8)))
  59571. #endif
  59572. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  59573. #ifdef SQLITE_DEBUG
  59574. 0, 0, /* pScopyFrom, pFiller */
  59575. #endif
  59576. 0, 0 };
  59577. if( pVm && ALWAYS(pVm->db) ){
  59578. sqlite3_mutex_enter(pVm->db->mutex);
  59579. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  59580. }
  59581. pOut = (Mem*)&nullMem;
  59582. }
  59583. return pOut;
  59584. }
  59585. /*
  59586. ** This function is called after invoking an sqlite3_value_XXX function on a
  59587. ** column value (i.e. a value returned by evaluating an SQL expression in the
  59588. ** select list of a SELECT statement) that may cause a malloc() failure. If
  59589. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  59590. ** code of statement pStmt set to SQLITE_NOMEM.
  59591. **
  59592. ** Specifically, this is called from within:
  59593. **
  59594. ** sqlite3_column_int()
  59595. ** sqlite3_column_int64()
  59596. ** sqlite3_column_text()
  59597. ** sqlite3_column_text16()
  59598. ** sqlite3_column_real()
  59599. ** sqlite3_column_bytes()
  59600. ** sqlite3_column_bytes16()
  59601. ** sqiite3_column_blob()
  59602. */
  59603. static void columnMallocFailure(sqlite3_stmt *pStmt)
  59604. {
  59605. /* If malloc() failed during an encoding conversion within an
  59606. ** sqlite3_column_XXX API, then set the return code of the statement to
  59607. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  59608. ** and _finalize() will return NOMEM.
  59609. */
  59610. Vdbe *p = (Vdbe *)pStmt;
  59611. if( p ){
  59612. p->rc = sqlite3ApiExit(p->db, p->rc);
  59613. sqlite3_mutex_leave(p->db->mutex);
  59614. }
  59615. }
  59616. /**************************** sqlite3_column_ *******************************
  59617. ** The following routines are used to access elements of the current row
  59618. ** in the result set.
  59619. */
  59620. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  59621. const void *val;
  59622. val = sqlite3_value_blob( columnMem(pStmt,i) );
  59623. /* Even though there is no encoding conversion, value_blob() might
  59624. ** need to call malloc() to expand the result of a zeroblob()
  59625. ** expression.
  59626. */
  59627. columnMallocFailure(pStmt);
  59628. return val;
  59629. }
  59630. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  59631. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  59632. columnMallocFailure(pStmt);
  59633. return val;
  59634. }
  59635. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  59636. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  59637. columnMallocFailure(pStmt);
  59638. return val;
  59639. }
  59640. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  59641. double val = sqlite3_value_double( columnMem(pStmt,i) );
  59642. columnMallocFailure(pStmt);
  59643. return val;
  59644. }
  59645. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  59646. int val = sqlite3_value_int( columnMem(pStmt,i) );
  59647. columnMallocFailure(pStmt);
  59648. return val;
  59649. }
  59650. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  59651. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  59652. columnMallocFailure(pStmt);
  59653. return val;
  59654. }
  59655. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  59656. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  59657. columnMallocFailure(pStmt);
  59658. return val;
  59659. }
  59660. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  59661. Mem *pOut = columnMem(pStmt, i);
  59662. if( pOut->flags&MEM_Static ){
  59663. pOut->flags &= ~MEM_Static;
  59664. pOut->flags |= MEM_Ephem;
  59665. }
  59666. columnMallocFailure(pStmt);
  59667. return (sqlite3_value *)pOut;
  59668. }
  59669. #ifndef SQLITE_OMIT_UTF16
  59670. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  59671. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  59672. columnMallocFailure(pStmt);
  59673. return val;
  59674. }
  59675. #endif /* SQLITE_OMIT_UTF16 */
  59676. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  59677. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  59678. columnMallocFailure(pStmt);
  59679. return iType;
  59680. }
  59681. /* The following function is experimental and subject to change or
  59682. ** removal */
  59683. /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
  59684. ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
  59685. **}
  59686. */
  59687. /*
  59688. ** Convert the N-th element of pStmt->pColName[] into a string using
  59689. ** xFunc() then return that string. If N is out of range, return 0.
  59690. **
  59691. ** There are up to 5 names for each column. useType determines which
  59692. ** name is returned. Here are the names:
  59693. **
  59694. ** 0 The column name as it should be displayed for output
  59695. ** 1 The datatype name for the column
  59696. ** 2 The name of the database that the column derives from
  59697. ** 3 The name of the table that the column derives from
  59698. ** 4 The name of the table column that the result column derives from
  59699. **
  59700. ** If the result is not a simple column reference (if it is an expression
  59701. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  59702. */
  59703. static const void *columnName(
  59704. sqlite3_stmt *pStmt,
  59705. int N,
  59706. const void *(*xFunc)(Mem*),
  59707. int useType
  59708. ){
  59709. const void *ret = 0;
  59710. Vdbe *p = (Vdbe *)pStmt;
  59711. int n;
  59712. sqlite3 *db = p->db;
  59713. assert( db!=0 );
  59714. n = sqlite3_column_count(pStmt);
  59715. if( N<n && N>=0 ){
  59716. N += useType*n;
  59717. sqlite3_mutex_enter(db->mutex);
  59718. assert( db->mallocFailed==0 );
  59719. ret = xFunc(&p->aColName[N]);
  59720. /* A malloc may have failed inside of the xFunc() call. If this
  59721. ** is the case, clear the mallocFailed flag and return NULL.
  59722. */
  59723. if( db->mallocFailed ){
  59724. db->mallocFailed = 0;
  59725. ret = 0;
  59726. }
  59727. sqlite3_mutex_leave(db->mutex);
  59728. }
  59729. return ret;
  59730. }
  59731. /*
  59732. ** Return the name of the Nth column of the result set returned by SQL
  59733. ** statement pStmt.
  59734. */
  59735. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  59736. return columnName(
  59737. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  59738. }
  59739. #ifndef SQLITE_OMIT_UTF16
  59740. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  59741. return columnName(
  59742. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  59743. }
  59744. #endif
  59745. /*
  59746. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  59747. ** not define OMIT_DECLTYPE.
  59748. */
  59749. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  59750. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  59751. and SQLITE_ENABLE_COLUMN_METADATA"
  59752. #endif
  59753. #ifndef SQLITE_OMIT_DECLTYPE
  59754. /*
  59755. ** Return the column declaration type (if applicable) of the 'i'th column
  59756. ** of the result set of SQL statement pStmt.
  59757. */
  59758. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  59759. return columnName(
  59760. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  59761. }
  59762. #ifndef SQLITE_OMIT_UTF16
  59763. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  59764. return columnName(
  59765. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  59766. }
  59767. #endif /* SQLITE_OMIT_UTF16 */
  59768. #endif /* SQLITE_OMIT_DECLTYPE */
  59769. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  59770. /*
  59771. ** Return the name of the database from which a result column derives.
  59772. ** NULL is returned if the result column is an expression or constant or
  59773. ** anything else which is not an unabiguous reference to a database column.
  59774. */
  59775. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  59776. return columnName(
  59777. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  59778. }
  59779. #ifndef SQLITE_OMIT_UTF16
  59780. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  59781. return columnName(
  59782. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  59783. }
  59784. #endif /* SQLITE_OMIT_UTF16 */
  59785. /*
  59786. ** Return the name of the table from which a result column derives.
  59787. ** NULL is returned if the result column is an expression or constant or
  59788. ** anything else which is not an unabiguous reference to a database column.
  59789. */
  59790. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  59791. return columnName(
  59792. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  59793. }
  59794. #ifndef SQLITE_OMIT_UTF16
  59795. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  59796. return columnName(
  59797. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  59798. }
  59799. #endif /* SQLITE_OMIT_UTF16 */
  59800. /*
  59801. ** Return the name of the table column from which a result column derives.
  59802. ** NULL is returned if the result column is an expression or constant or
  59803. ** anything else which is not an unabiguous reference to a database column.
  59804. */
  59805. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  59806. return columnName(
  59807. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  59808. }
  59809. #ifndef SQLITE_OMIT_UTF16
  59810. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  59811. return columnName(
  59812. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  59813. }
  59814. #endif /* SQLITE_OMIT_UTF16 */
  59815. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  59816. /******************************* sqlite3_bind_ ***************************
  59817. **
  59818. ** Routines used to attach values to wildcards in a compiled SQL statement.
  59819. */
  59820. /*
  59821. ** Unbind the value bound to variable i in virtual machine p. This is the
  59822. ** the same as binding a NULL value to the column. If the "i" parameter is
  59823. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  59824. **
  59825. ** A successful evaluation of this routine acquires the mutex on p.
  59826. ** the mutex is released if any kind of error occurs.
  59827. **
  59828. ** The error code stored in database p->db is overwritten with the return
  59829. ** value in any case.
  59830. */
  59831. static int vdbeUnbind(Vdbe *p, int i){
  59832. Mem *pVar;
  59833. if( vdbeSafetyNotNull(p) ){
  59834. return SQLITE_MISUSE_BKPT;
  59835. }
  59836. sqlite3_mutex_enter(p->db->mutex);
  59837. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  59838. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  59839. sqlite3_mutex_leave(p->db->mutex);
  59840. sqlite3_log(SQLITE_MISUSE,
  59841. "bind on a busy prepared statement: [%s]", p->zSql);
  59842. return SQLITE_MISUSE_BKPT;
  59843. }
  59844. if( i<1 || i>p->nVar ){
  59845. sqlite3Error(p->db, SQLITE_RANGE, 0);
  59846. sqlite3_mutex_leave(p->db->mutex);
  59847. return SQLITE_RANGE;
  59848. }
  59849. i--;
  59850. pVar = &p->aVar[i];
  59851. sqlite3VdbeMemRelease(pVar);
  59852. pVar->flags = MEM_Null;
  59853. sqlite3Error(p->db, SQLITE_OK, 0);
  59854. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  59855. ** binding a new value to this variable invalidates the current query plan.
  59856. **
  59857. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  59858. ** parameter in the WHERE clause might influence the choice of query plan
  59859. ** for a statement, then the statement will be automatically recompiled,
  59860. ** as if there had been a schema change, on the first sqlite3_step() call
  59861. ** following any change to the bindings of that parameter.
  59862. */
  59863. if( p->isPrepareV2 &&
  59864. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  59865. ){
  59866. p->expired = 1;
  59867. }
  59868. return SQLITE_OK;
  59869. }
  59870. /*
  59871. ** Bind a text or BLOB value.
  59872. */
  59873. static int bindText(
  59874. sqlite3_stmt *pStmt, /* The statement to bind against */
  59875. int i, /* Index of the parameter to bind */
  59876. const void *zData, /* Pointer to the data to be bound */
  59877. int nData, /* Number of bytes of data to be bound */
  59878. void (*xDel)(void*), /* Destructor for the data */
  59879. u8 encoding /* Encoding for the data */
  59880. ){
  59881. Vdbe *p = (Vdbe *)pStmt;
  59882. Mem *pVar;
  59883. int rc;
  59884. rc = vdbeUnbind(p, i);
  59885. if( rc==SQLITE_OK ){
  59886. if( zData!=0 ){
  59887. pVar = &p->aVar[i-1];
  59888. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  59889. if( rc==SQLITE_OK && encoding!=0 ){
  59890. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  59891. }
  59892. sqlite3Error(p->db, rc, 0);
  59893. rc = sqlite3ApiExit(p->db, rc);
  59894. }
  59895. sqlite3_mutex_leave(p->db->mutex);
  59896. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  59897. xDel((void*)zData);
  59898. }
  59899. return rc;
  59900. }
  59901. /*
  59902. ** Bind a blob value to an SQL statement variable.
  59903. */
  59904. SQLITE_API int sqlite3_bind_blob(
  59905. sqlite3_stmt *pStmt,
  59906. int i,
  59907. const void *zData,
  59908. int nData,
  59909. void (*xDel)(void*)
  59910. ){
  59911. return bindText(pStmt, i, zData, nData, xDel, 0);
  59912. }
  59913. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  59914. int rc;
  59915. Vdbe *p = (Vdbe *)pStmt;
  59916. rc = vdbeUnbind(p, i);
  59917. if( rc==SQLITE_OK ){
  59918. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  59919. sqlite3_mutex_leave(p->db->mutex);
  59920. }
  59921. return rc;
  59922. }
  59923. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  59924. return sqlite3_bind_int64(p, i, (i64)iValue);
  59925. }
  59926. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  59927. int rc;
  59928. Vdbe *p = (Vdbe *)pStmt;
  59929. rc = vdbeUnbind(p, i);
  59930. if( rc==SQLITE_OK ){
  59931. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  59932. sqlite3_mutex_leave(p->db->mutex);
  59933. }
  59934. return rc;
  59935. }
  59936. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  59937. int rc;
  59938. Vdbe *p = (Vdbe*)pStmt;
  59939. rc = vdbeUnbind(p, i);
  59940. if( rc==SQLITE_OK ){
  59941. sqlite3_mutex_leave(p->db->mutex);
  59942. }
  59943. return rc;
  59944. }
  59945. SQLITE_API int sqlite3_bind_text(
  59946. sqlite3_stmt *pStmt,
  59947. int i,
  59948. const char *zData,
  59949. int nData,
  59950. void (*xDel)(void*)
  59951. ){
  59952. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  59953. }
  59954. #ifndef SQLITE_OMIT_UTF16
  59955. SQLITE_API int sqlite3_bind_text16(
  59956. sqlite3_stmt *pStmt,
  59957. int i,
  59958. const void *zData,
  59959. int nData,
  59960. void (*xDel)(void*)
  59961. ){
  59962. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  59963. }
  59964. #endif /* SQLITE_OMIT_UTF16 */
  59965. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  59966. int rc;
  59967. switch( pValue->type ){
  59968. case SQLITE_INTEGER: {
  59969. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  59970. break;
  59971. }
  59972. case SQLITE_FLOAT: {
  59973. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  59974. break;
  59975. }
  59976. case SQLITE_BLOB: {
  59977. if( pValue->flags & MEM_Zero ){
  59978. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  59979. }else{
  59980. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  59981. }
  59982. break;
  59983. }
  59984. case SQLITE_TEXT: {
  59985. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  59986. pValue->enc);
  59987. break;
  59988. }
  59989. default: {
  59990. rc = sqlite3_bind_null(pStmt, i);
  59991. break;
  59992. }
  59993. }
  59994. return rc;
  59995. }
  59996. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  59997. int rc;
  59998. Vdbe *p = (Vdbe *)pStmt;
  59999. rc = vdbeUnbind(p, i);
  60000. if( rc==SQLITE_OK ){
  60001. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  60002. sqlite3_mutex_leave(p->db->mutex);
  60003. }
  60004. return rc;
  60005. }
  60006. /*
  60007. ** Return the number of wildcards that can be potentially bound to.
  60008. ** This routine is added to support DBD::SQLite.
  60009. */
  60010. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  60011. Vdbe *p = (Vdbe*)pStmt;
  60012. return p ? p->nVar : 0;
  60013. }
  60014. /*
  60015. ** Return the name of a wildcard parameter. Return NULL if the index
  60016. ** is out of range or if the wildcard is unnamed.
  60017. **
  60018. ** The result is always UTF-8.
  60019. */
  60020. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  60021. Vdbe *p = (Vdbe*)pStmt;
  60022. if( p==0 || i<1 || i>p->nzVar ){
  60023. return 0;
  60024. }
  60025. return p->azVar[i-1];
  60026. }
  60027. /*
  60028. ** Given a wildcard parameter name, return the index of the variable
  60029. ** with that name. If there is no variable with the given name,
  60030. ** return 0.
  60031. */
  60032. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  60033. int i;
  60034. if( p==0 ){
  60035. return 0;
  60036. }
  60037. if( zName ){
  60038. for(i=0; i<p->nzVar; i++){
  60039. const char *z = p->azVar[i];
  60040. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  60041. return i+1;
  60042. }
  60043. }
  60044. }
  60045. return 0;
  60046. }
  60047. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  60048. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  60049. }
  60050. /*
  60051. ** Transfer all bindings from the first statement over to the second.
  60052. */
  60053. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  60054. Vdbe *pFrom = (Vdbe*)pFromStmt;
  60055. Vdbe *pTo = (Vdbe*)pToStmt;
  60056. int i;
  60057. assert( pTo->db==pFrom->db );
  60058. assert( pTo->nVar==pFrom->nVar );
  60059. sqlite3_mutex_enter(pTo->db->mutex);
  60060. for(i=0; i<pFrom->nVar; i++){
  60061. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  60062. }
  60063. sqlite3_mutex_leave(pTo->db->mutex);
  60064. return SQLITE_OK;
  60065. }
  60066. #ifndef SQLITE_OMIT_DEPRECATED
  60067. /*
  60068. ** Deprecated external interface. Internal/core SQLite code
  60069. ** should call sqlite3TransferBindings.
  60070. **
  60071. ** Is is misuse to call this routine with statements from different
  60072. ** database connections. But as this is a deprecated interface, we
  60073. ** will not bother to check for that condition.
  60074. **
  60075. ** If the two statements contain a different number of bindings, then
  60076. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  60077. ** SQLITE_OK is returned.
  60078. */
  60079. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  60080. Vdbe *pFrom = (Vdbe*)pFromStmt;
  60081. Vdbe *pTo = (Vdbe*)pToStmt;
  60082. if( pFrom->nVar!=pTo->nVar ){
  60083. return SQLITE_ERROR;
  60084. }
  60085. if( pTo->isPrepareV2 && pTo->expmask ){
  60086. pTo->expired = 1;
  60087. }
  60088. if( pFrom->isPrepareV2 && pFrom->expmask ){
  60089. pFrom->expired = 1;
  60090. }
  60091. return sqlite3TransferBindings(pFromStmt, pToStmt);
  60092. }
  60093. #endif
  60094. /*
  60095. ** Return the sqlite3* database handle to which the prepared statement given
  60096. ** in the argument belongs. This is the same database handle that was
  60097. ** the first argument to the sqlite3_prepare() that was used to create
  60098. ** the statement in the first place.
  60099. */
  60100. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  60101. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  60102. }
  60103. /*
  60104. ** Return true if the prepared statement is guaranteed to not modify the
  60105. ** database.
  60106. */
  60107. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  60108. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  60109. }
  60110. /*
  60111. ** Return true if the prepared statement is in need of being reset.
  60112. */
  60113. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  60114. Vdbe *v = (Vdbe*)pStmt;
  60115. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  60116. }
  60117. /*
  60118. ** Return a pointer to the next prepared statement after pStmt associated
  60119. ** with database connection pDb. If pStmt is NULL, return the first
  60120. ** prepared statement for the database connection. Return NULL if there
  60121. ** are no more.
  60122. */
  60123. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  60124. sqlite3_stmt *pNext;
  60125. sqlite3_mutex_enter(pDb->mutex);
  60126. if( pStmt==0 ){
  60127. pNext = (sqlite3_stmt*)pDb->pVdbe;
  60128. }else{
  60129. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  60130. }
  60131. sqlite3_mutex_leave(pDb->mutex);
  60132. return pNext;
  60133. }
  60134. /*
  60135. ** Return the value of a status counter for a prepared statement
  60136. */
  60137. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  60138. Vdbe *pVdbe = (Vdbe*)pStmt;
  60139. int v = pVdbe->aCounter[op-1];
  60140. if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  60141. return v;
  60142. }
  60143. /************** End of vdbeapi.c *********************************************/
  60144. /************** Begin file vdbetrace.c ***************************************/
  60145. /*
  60146. ** 2009 November 25
  60147. **
  60148. ** The author disclaims copyright to this source code. In place of
  60149. ** a legal notice, here is a blessing:
  60150. **
  60151. ** May you do good and not evil.
  60152. ** May you find forgiveness for yourself and forgive others.
  60153. ** May you share freely, never taking more than you give.
  60154. **
  60155. *************************************************************************
  60156. **
  60157. ** This file contains code used to insert the values of host parameters
  60158. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  60159. **
  60160. ** The Vdbe parse-tree explainer is also found here.
  60161. */
  60162. #ifndef SQLITE_OMIT_TRACE
  60163. /*
  60164. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  60165. ** bytes in this text up to but excluding the first character in
  60166. ** a host parameter. If the text contains no host parameters, return
  60167. ** the total number of bytes in the text.
  60168. */
  60169. static int findNextHostParameter(const char *zSql, int *pnToken){
  60170. int tokenType;
  60171. int nTotal = 0;
  60172. int n;
  60173. *pnToken = 0;
  60174. while( zSql[0] ){
  60175. n = sqlite3GetToken((u8*)zSql, &tokenType);
  60176. assert( n>0 && tokenType!=TK_ILLEGAL );
  60177. if( tokenType==TK_VARIABLE ){
  60178. *pnToken = n;
  60179. break;
  60180. }
  60181. nTotal += n;
  60182. zSql += n;
  60183. }
  60184. return nTotal;
  60185. }
  60186. /*
  60187. ** This function returns a pointer to a nul-terminated string in memory
  60188. ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
  60189. ** string contains a copy of zRawSql but with host parameters expanded to
  60190. ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
  60191. ** then the returned string holds a copy of zRawSql with "-- " prepended
  60192. ** to each line of text.
  60193. **
  60194. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  60195. ** then long strings and blobs are truncated to that many bytes. This
  60196. ** can be used to prevent unreasonably large trace strings when dealing
  60197. ** with large (multi-megabyte) strings and blobs.
  60198. **
  60199. ** The calling function is responsible for making sure the memory returned
  60200. ** is eventually freed.
  60201. **
  60202. ** ALGORITHM: Scan the input string looking for host parameters in any of
  60203. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  60204. ** string literals, quoted identifier names, and comments. For text forms,
  60205. ** the host parameter index is found by scanning the perpared
  60206. ** statement for the corresponding OP_Variable opcode. Once the host
  60207. ** parameter index is known, locate the value in p->aVar[]. Then render
  60208. ** the value as a literal in place of the host parameter name.
  60209. */
  60210. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  60211. Vdbe *p, /* The prepared statement being evaluated */
  60212. const char *zRawSql /* Raw text of the SQL statement */
  60213. ){
  60214. sqlite3 *db; /* The database connection */
  60215. int idx = 0; /* Index of a host parameter */
  60216. int nextIndex = 1; /* Index of next ? host parameter */
  60217. int n; /* Length of a token prefix */
  60218. int nToken; /* Length of the parameter token */
  60219. int i; /* Loop counter */
  60220. Mem *pVar; /* Value of a host parameter */
  60221. StrAccum out; /* Accumulate the output here */
  60222. char zBase[100]; /* Initial working space */
  60223. db = p->db;
  60224. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  60225. db->aLimit[SQLITE_LIMIT_LENGTH]);
  60226. out.db = db;
  60227. if( db->vdbeExecCnt>1 ){
  60228. while( *zRawSql ){
  60229. const char *zStart = zRawSql;
  60230. while( *(zRawSql++)!='\n' && *zRawSql );
  60231. sqlite3StrAccumAppend(&out, "-- ", 3);
  60232. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  60233. }
  60234. }else{
  60235. while( zRawSql[0] ){
  60236. n = findNextHostParameter(zRawSql, &nToken);
  60237. assert( n>0 );
  60238. sqlite3StrAccumAppend(&out, zRawSql, n);
  60239. zRawSql += n;
  60240. assert( zRawSql[0] || nToken==0 );
  60241. if( nToken==0 ) break;
  60242. if( zRawSql[0]=='?' ){
  60243. if( nToken>1 ){
  60244. assert( sqlite3Isdigit(zRawSql[1]) );
  60245. sqlite3GetInt32(&zRawSql[1], &idx);
  60246. }else{
  60247. idx = nextIndex;
  60248. }
  60249. }else{
  60250. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  60251. testcase( zRawSql[0]==':' );
  60252. testcase( zRawSql[0]=='$' );
  60253. testcase( zRawSql[0]=='@' );
  60254. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  60255. assert( idx>0 );
  60256. }
  60257. zRawSql += nToken;
  60258. nextIndex = idx + 1;
  60259. assert( idx>0 && idx<=p->nVar );
  60260. pVar = &p->aVar[idx-1];
  60261. if( pVar->flags & MEM_Null ){
  60262. sqlite3StrAccumAppend(&out, "NULL", 4);
  60263. }else if( pVar->flags & MEM_Int ){
  60264. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  60265. }else if( pVar->flags & MEM_Real ){
  60266. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  60267. }else if( pVar->flags & MEM_Str ){
  60268. int nOut; /* Number of bytes of the string text to include in output */
  60269. #ifndef SQLITE_OMIT_UTF16
  60270. u8 enc = ENC(db);
  60271. Mem utf8;
  60272. if( enc!=SQLITE_UTF8 ){
  60273. memset(&utf8, 0, sizeof(utf8));
  60274. utf8.db = db;
  60275. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  60276. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  60277. pVar = &utf8;
  60278. }
  60279. #endif
  60280. nOut = pVar->n;
  60281. #ifdef SQLITE_TRACE_SIZE_LIMIT
  60282. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  60283. nOut = SQLITE_TRACE_SIZE_LIMIT;
  60284. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  60285. }
  60286. #endif
  60287. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  60288. #ifdef SQLITE_TRACE_SIZE_LIMIT
  60289. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  60290. #endif
  60291. #ifndef SQLITE_OMIT_UTF16
  60292. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  60293. #endif
  60294. }else if( pVar->flags & MEM_Zero ){
  60295. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  60296. }else{
  60297. int nOut; /* Number of bytes of the blob to include in output */
  60298. assert( pVar->flags & MEM_Blob );
  60299. sqlite3StrAccumAppend(&out, "x'", 2);
  60300. nOut = pVar->n;
  60301. #ifdef SQLITE_TRACE_SIZE_LIMIT
  60302. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  60303. #endif
  60304. for(i=0; i<nOut; i++){
  60305. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  60306. }
  60307. sqlite3StrAccumAppend(&out, "'", 1);
  60308. #ifdef SQLITE_TRACE_SIZE_LIMIT
  60309. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  60310. #endif
  60311. }
  60312. }
  60313. }
  60314. return sqlite3StrAccumFinish(&out);
  60315. }
  60316. #endif /* #ifndef SQLITE_OMIT_TRACE */
  60317. /*****************************************************************************
  60318. ** The following code implements the data-structure explaining logic
  60319. ** for the Vdbe.
  60320. */
  60321. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  60322. /*
  60323. ** Allocate a new Explain object
  60324. */
  60325. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  60326. if( pVdbe ){
  60327. Explain *p;
  60328. sqlite3BeginBenignMalloc();
  60329. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  60330. if( p ){
  60331. p->pVdbe = pVdbe;
  60332. sqlite3_free(pVdbe->pExplain);
  60333. pVdbe->pExplain = p;
  60334. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  60335. SQLITE_MAX_LENGTH);
  60336. p->str.useMalloc = 2;
  60337. }else{
  60338. sqlite3EndBenignMalloc();
  60339. }
  60340. }
  60341. }
  60342. /*
  60343. ** Return true if the Explain ends with a new-line.
  60344. */
  60345. static int endsWithNL(Explain *p){
  60346. return p && p->str.zText && p->str.nChar
  60347. && p->str.zText[p->str.nChar-1]=='\n';
  60348. }
  60349. /*
  60350. ** Append text to the indentation
  60351. */
  60352. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  60353. Explain *p;
  60354. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  60355. va_list ap;
  60356. if( p->nIndent && endsWithNL(p) ){
  60357. int n = p->nIndent;
  60358. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  60359. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  60360. }
  60361. va_start(ap, zFormat);
  60362. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  60363. va_end(ap);
  60364. }
  60365. }
  60366. /*
  60367. ** Append a '\n' if there is not already one.
  60368. */
  60369. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  60370. Explain *p;
  60371. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  60372. sqlite3StrAccumAppend(&p->str, "\n", 1);
  60373. }
  60374. }
  60375. /*
  60376. ** Push a new indentation level. Subsequent lines will be indented
  60377. ** so that they begin at the current cursor position.
  60378. */
  60379. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  60380. Explain *p;
  60381. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  60382. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  60383. const char *z = p->str.zText;
  60384. int i = p->str.nChar-1;
  60385. int x;
  60386. while( i>=0 && z[i]!='\n' ){ i--; }
  60387. x = (p->str.nChar - 1) - i;
  60388. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  60389. x = p->aIndent[p->nIndent-1];
  60390. }
  60391. p->aIndent[p->nIndent] = x;
  60392. }
  60393. p->nIndent++;
  60394. }
  60395. }
  60396. /*
  60397. ** Pop the indentation stack by one level.
  60398. */
  60399. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  60400. if( p && p->pExplain ) p->pExplain->nIndent--;
  60401. }
  60402. /*
  60403. ** Free the indentation structure
  60404. */
  60405. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  60406. if( pVdbe && pVdbe->pExplain ){
  60407. sqlite3_free(pVdbe->zExplain);
  60408. sqlite3ExplainNL(pVdbe);
  60409. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  60410. sqlite3_free(pVdbe->pExplain);
  60411. pVdbe->pExplain = 0;
  60412. sqlite3EndBenignMalloc();
  60413. }
  60414. }
  60415. /*
  60416. ** Return the explanation of a virtual machine.
  60417. */
  60418. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  60419. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  60420. }
  60421. #endif /* defined(SQLITE_DEBUG) */
  60422. /************** End of vdbetrace.c *******************************************/
  60423. /************** Begin file vdbe.c ********************************************/
  60424. /*
  60425. ** 2001 September 15
  60426. **
  60427. ** The author disclaims copyright to this source code. In place of
  60428. ** a legal notice, here is a blessing:
  60429. **
  60430. ** May you do good and not evil.
  60431. ** May you find forgiveness for yourself and forgive others.
  60432. ** May you share freely, never taking more than you give.
  60433. **
  60434. *************************************************************************
  60435. ** The code in this file implements execution method of the
  60436. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  60437. ** handles housekeeping details such as creating and deleting
  60438. ** VDBE instances. This file is solely interested in executing
  60439. ** the VDBE program.
  60440. **
  60441. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  60442. ** to a VDBE.
  60443. **
  60444. ** The SQL parser generates a program which is then executed by
  60445. ** the VDBE to do the work of the SQL statement. VDBE programs are
  60446. ** similar in form to assembly language. The program consists of
  60447. ** a linear sequence of operations. Each operation has an opcode
  60448. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  60449. ** is a null-terminated string. Operand P5 is an unsigned character.
  60450. ** Few opcodes use all 5 operands.
  60451. **
  60452. ** Computation results are stored on a set of registers numbered beginning
  60453. ** with 1 and going up to Vdbe.nMem. Each register can store
  60454. ** either an integer, a null-terminated string, a floating point
  60455. ** number, or the SQL "NULL" value. An implicit conversion from one
  60456. ** type to the other occurs as necessary.
  60457. **
  60458. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  60459. ** function which does the work of interpreting a VDBE program.
  60460. ** But other routines are also provided to help in building up
  60461. ** a program instruction by instruction.
  60462. **
  60463. ** Various scripts scan this source file in order to generate HTML
  60464. ** documentation, headers files, or other derived files. The formatting
  60465. ** of the code in this file is, therefore, important. See other comments
  60466. ** in this file for details. If in doubt, do not deviate from existing
  60467. ** commenting and indentation practices when changing or adding code.
  60468. */
  60469. /*
  60470. ** Invoke this macro on memory cells just prior to changing the
  60471. ** value of the cell. This macro verifies that shallow copies are
  60472. ** not misused.
  60473. */
  60474. #ifdef SQLITE_DEBUG
  60475. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  60476. #else
  60477. # define memAboutToChange(P,M)
  60478. #endif
  60479. /*
  60480. ** The following global variable is incremented every time a cursor
  60481. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  60482. ** procedures use this information to make sure that indices are
  60483. ** working correctly. This variable has no function other than to
  60484. ** help verify the correct operation of the library.
  60485. */
  60486. #ifdef SQLITE_TEST
  60487. SQLITE_API int sqlite3_search_count = 0;
  60488. #endif
  60489. /*
  60490. ** When this global variable is positive, it gets decremented once before
  60491. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  60492. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  60493. **
  60494. ** This facility is used for testing purposes only. It does not function
  60495. ** in an ordinary build.
  60496. */
  60497. #ifdef SQLITE_TEST
  60498. SQLITE_API int sqlite3_interrupt_count = 0;
  60499. #endif
  60500. /*
  60501. ** The next global variable is incremented each type the OP_Sort opcode
  60502. ** is executed. The test procedures use this information to make sure that
  60503. ** sorting is occurring or not occurring at appropriate times. This variable
  60504. ** has no function other than to help verify the correct operation of the
  60505. ** library.
  60506. */
  60507. #ifdef SQLITE_TEST
  60508. SQLITE_API int sqlite3_sort_count = 0;
  60509. #endif
  60510. /*
  60511. ** The next global variable records the size of the largest MEM_Blob
  60512. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  60513. ** use this information to make sure that the zero-blob functionality
  60514. ** is working correctly. This variable has no function other than to
  60515. ** help verify the correct operation of the library.
  60516. */
  60517. #ifdef SQLITE_TEST
  60518. SQLITE_API int sqlite3_max_blobsize = 0;
  60519. static void updateMaxBlobsize(Mem *p){
  60520. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  60521. sqlite3_max_blobsize = p->n;
  60522. }
  60523. }
  60524. #endif
  60525. /*
  60526. ** The next global variable is incremented each type the OP_Found opcode
  60527. ** is executed. This is used to test whether or not the foreign key
  60528. ** operation implemented using OP_FkIsZero is working. This variable
  60529. ** has no function other than to help verify the correct operation of the
  60530. ** library.
  60531. */
  60532. #ifdef SQLITE_TEST
  60533. SQLITE_API int sqlite3_found_count = 0;
  60534. #endif
  60535. /*
  60536. ** Test a register to see if it exceeds the current maximum blob size.
  60537. ** If it does, record the new maximum blob size.
  60538. */
  60539. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  60540. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  60541. #else
  60542. # define UPDATE_MAX_BLOBSIZE(P)
  60543. #endif
  60544. /*
  60545. ** Convert the given register into a string if it isn't one
  60546. ** already. Return non-zero if a malloc() fails.
  60547. */
  60548. #define Stringify(P, enc) \
  60549. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  60550. { goto no_mem; }
  60551. /*
  60552. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  60553. ** a pointer to a dynamically allocated string where some other entity
  60554. ** is responsible for deallocating that string. Because the register
  60555. ** does not control the string, it might be deleted without the register
  60556. ** knowing it.
  60557. **
  60558. ** This routine converts an ephemeral string into a dynamically allocated
  60559. ** string that the register itself controls. In other words, it
  60560. ** converts an MEM_Ephem string into an MEM_Dyn string.
  60561. */
  60562. #define Deephemeralize(P) \
  60563. if( ((P)->flags&MEM_Ephem)!=0 \
  60564. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  60565. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  60566. # define isSorter(x) ((x)->pSorter!=0)
  60567. /*
  60568. ** Argument pMem points at a register that will be passed to a
  60569. ** user-defined function or returned to the user as the result of a query.
  60570. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  60571. ** routines.
  60572. */
  60573. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  60574. int flags = pMem->flags;
  60575. if( flags & MEM_Null ){
  60576. pMem->type = SQLITE_NULL;
  60577. }
  60578. else if( flags & MEM_Int ){
  60579. pMem->type = SQLITE_INTEGER;
  60580. }
  60581. else if( flags & MEM_Real ){
  60582. pMem->type = SQLITE_FLOAT;
  60583. }
  60584. else if( flags & MEM_Str ){
  60585. pMem->type = SQLITE_TEXT;
  60586. }else{
  60587. pMem->type = SQLITE_BLOB;
  60588. }
  60589. }
  60590. /*
  60591. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  60592. ** if we run out of memory.
  60593. */
  60594. static VdbeCursor *allocateCursor(
  60595. Vdbe *p, /* The virtual machine */
  60596. int iCur, /* Index of the new VdbeCursor */
  60597. int nField, /* Number of fields in the table or index */
  60598. int iDb, /* Database the cursor belongs to, or -1 */
  60599. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  60600. ){
  60601. /* Find the memory cell that will be used to store the blob of memory
  60602. ** required for this VdbeCursor structure. It is convenient to use a
  60603. ** vdbe memory cell to manage the memory allocation required for a
  60604. ** VdbeCursor structure for the following reasons:
  60605. **
  60606. ** * Sometimes cursor numbers are used for a couple of different
  60607. ** purposes in a vdbe program. The different uses might require
  60608. ** different sized allocations. Memory cells provide growable
  60609. ** allocations.
  60610. **
  60611. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  60612. ** be freed lazily via the sqlite3_release_memory() API. This
  60613. ** minimizes the number of malloc calls made by the system.
  60614. **
  60615. ** Memory cells for cursors are allocated at the top of the address
  60616. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  60617. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  60618. */
  60619. Mem *pMem = &p->aMem[p->nMem-iCur];
  60620. int nByte;
  60621. VdbeCursor *pCx = 0;
  60622. nByte =
  60623. ROUND8(sizeof(VdbeCursor)) +
  60624. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  60625. 2*nField*sizeof(u32);
  60626. assert( iCur<p->nCursor );
  60627. if( p->apCsr[iCur] ){
  60628. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  60629. p->apCsr[iCur] = 0;
  60630. }
  60631. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  60632. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  60633. memset(pCx, 0, sizeof(VdbeCursor));
  60634. pCx->iDb = iDb;
  60635. pCx->nField = nField;
  60636. if( nField ){
  60637. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  60638. }
  60639. if( isBtreeCursor ){
  60640. pCx->pCursor = (BtCursor*)
  60641. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  60642. sqlite3BtreeCursorZero(pCx->pCursor);
  60643. }
  60644. }
  60645. return pCx;
  60646. }
  60647. /*
  60648. ** Try to convert a value into a numeric representation if we can
  60649. ** do so without loss of information. In other words, if the string
  60650. ** looks like a number, convert it into a number. If it does not
  60651. ** look like a number, leave it alone.
  60652. */
  60653. static void applyNumericAffinity(Mem *pRec){
  60654. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  60655. double rValue;
  60656. i64 iValue;
  60657. u8 enc = pRec->enc;
  60658. if( (pRec->flags&MEM_Str)==0 ) return;
  60659. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  60660. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  60661. pRec->u.i = iValue;
  60662. pRec->flags |= MEM_Int;
  60663. }else{
  60664. pRec->r = rValue;
  60665. pRec->flags |= MEM_Real;
  60666. }
  60667. }
  60668. }
  60669. /*
  60670. ** Processing is determine by the affinity parameter:
  60671. **
  60672. ** SQLITE_AFF_INTEGER:
  60673. ** SQLITE_AFF_REAL:
  60674. ** SQLITE_AFF_NUMERIC:
  60675. ** Try to convert pRec to an integer representation or a
  60676. ** floating-point representation if an integer representation
  60677. ** is not possible. Note that the integer representation is
  60678. ** always preferred, even if the affinity is REAL, because
  60679. ** an integer representation is more space efficient on disk.
  60680. **
  60681. ** SQLITE_AFF_TEXT:
  60682. ** Convert pRec to a text representation.
  60683. **
  60684. ** SQLITE_AFF_NONE:
  60685. ** No-op. pRec is unchanged.
  60686. */
  60687. static void applyAffinity(
  60688. Mem *pRec, /* The value to apply affinity to */
  60689. char affinity, /* The affinity to be applied */
  60690. u8 enc /* Use this text encoding */
  60691. ){
  60692. if( affinity==SQLITE_AFF_TEXT ){
  60693. /* Only attempt the conversion to TEXT if there is an integer or real
  60694. ** representation (blob and NULL do not get converted) but no string
  60695. ** representation.
  60696. */
  60697. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  60698. sqlite3VdbeMemStringify(pRec, enc);
  60699. }
  60700. pRec->flags &= ~(MEM_Real|MEM_Int);
  60701. }else if( affinity!=SQLITE_AFF_NONE ){
  60702. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  60703. || affinity==SQLITE_AFF_NUMERIC );
  60704. applyNumericAffinity(pRec);
  60705. if( pRec->flags & MEM_Real ){
  60706. sqlite3VdbeIntegerAffinity(pRec);
  60707. }
  60708. }
  60709. }
  60710. /*
  60711. ** Try to convert the type of a function argument or a result column
  60712. ** into a numeric representation. Use either INTEGER or REAL whichever
  60713. ** is appropriate. But only do the conversion if it is possible without
  60714. ** loss of information and return the revised type of the argument.
  60715. */
  60716. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  60717. Mem *pMem = (Mem*)pVal;
  60718. if( pMem->type==SQLITE_TEXT ){
  60719. applyNumericAffinity(pMem);
  60720. sqlite3VdbeMemStoreType(pMem);
  60721. }
  60722. return pMem->type;
  60723. }
  60724. /*
  60725. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  60726. ** not the internal Mem* type.
  60727. */
  60728. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  60729. sqlite3_value *pVal,
  60730. u8 affinity,
  60731. u8 enc
  60732. ){
  60733. applyAffinity((Mem *)pVal, affinity, enc);
  60734. }
  60735. #ifdef SQLITE_DEBUG
  60736. /*
  60737. ** Write a nice string representation of the contents of cell pMem
  60738. ** into buffer zBuf, length nBuf.
  60739. */
  60740. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  60741. char *zCsr = zBuf;
  60742. int f = pMem->flags;
  60743. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  60744. if( f&MEM_Blob ){
  60745. int i;
  60746. char c;
  60747. if( f & MEM_Dyn ){
  60748. c = 'z';
  60749. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  60750. }else if( f & MEM_Static ){
  60751. c = 't';
  60752. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  60753. }else if( f & MEM_Ephem ){
  60754. c = 'e';
  60755. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  60756. }else{
  60757. c = 's';
  60758. }
  60759. sqlite3_snprintf(100, zCsr, "%c", c);
  60760. zCsr += sqlite3Strlen30(zCsr);
  60761. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  60762. zCsr += sqlite3Strlen30(zCsr);
  60763. for(i=0; i<16 && i<pMem->n; i++){
  60764. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  60765. zCsr += sqlite3Strlen30(zCsr);
  60766. }
  60767. for(i=0; i<16 && i<pMem->n; i++){
  60768. char z = pMem->z[i];
  60769. if( z<32 || z>126 ) *zCsr++ = '.';
  60770. else *zCsr++ = z;
  60771. }
  60772. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  60773. zCsr += sqlite3Strlen30(zCsr);
  60774. if( f & MEM_Zero ){
  60775. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  60776. zCsr += sqlite3Strlen30(zCsr);
  60777. }
  60778. *zCsr = '\0';
  60779. }else if( f & MEM_Str ){
  60780. int j, k;
  60781. zBuf[0] = ' ';
  60782. if( f & MEM_Dyn ){
  60783. zBuf[1] = 'z';
  60784. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  60785. }else if( f & MEM_Static ){
  60786. zBuf[1] = 't';
  60787. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  60788. }else if( f & MEM_Ephem ){
  60789. zBuf[1] = 'e';
  60790. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  60791. }else{
  60792. zBuf[1] = 's';
  60793. }
  60794. k = 2;
  60795. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  60796. k += sqlite3Strlen30(&zBuf[k]);
  60797. zBuf[k++] = '[';
  60798. for(j=0; j<15 && j<pMem->n; j++){
  60799. u8 c = pMem->z[j];
  60800. if( c>=0x20 && c<0x7f ){
  60801. zBuf[k++] = c;
  60802. }else{
  60803. zBuf[k++] = '.';
  60804. }
  60805. }
  60806. zBuf[k++] = ']';
  60807. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  60808. k += sqlite3Strlen30(&zBuf[k]);
  60809. zBuf[k++] = 0;
  60810. }
  60811. }
  60812. #endif
  60813. #ifdef SQLITE_DEBUG
  60814. /*
  60815. ** Print the value of a register for tracing purposes:
  60816. */
  60817. static void memTracePrint(FILE *out, Mem *p){
  60818. if( p->flags & MEM_Invalid ){
  60819. fprintf(out, " undefined");
  60820. }else if( p->flags & MEM_Null ){
  60821. fprintf(out, " NULL");
  60822. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  60823. fprintf(out, " si:%lld", p->u.i);
  60824. }else if( p->flags & MEM_Int ){
  60825. fprintf(out, " i:%lld", p->u.i);
  60826. #ifndef SQLITE_OMIT_FLOATING_POINT
  60827. }else if( p->flags & MEM_Real ){
  60828. fprintf(out, " r:%g", p->r);
  60829. #endif
  60830. }else if( p->flags & MEM_RowSet ){
  60831. fprintf(out, " (rowset)");
  60832. }else{
  60833. char zBuf[200];
  60834. sqlite3VdbeMemPrettyPrint(p, zBuf);
  60835. fprintf(out, " ");
  60836. fprintf(out, "%s", zBuf);
  60837. }
  60838. }
  60839. static void registerTrace(FILE *out, int iReg, Mem *p){
  60840. fprintf(out, "REG[%d] = ", iReg);
  60841. memTracePrint(out, p);
  60842. fprintf(out, "\n");
  60843. }
  60844. #endif
  60845. #ifdef SQLITE_DEBUG
  60846. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  60847. #else
  60848. # define REGISTER_TRACE(R,M)
  60849. #endif
  60850. #ifdef VDBE_PROFILE
  60851. /*
  60852. ** hwtime.h contains inline assembler code for implementing
  60853. ** high-performance timing routines.
  60854. */
  60855. /************** Include hwtime.h in the middle of vdbe.c *********************/
  60856. /************** Begin file hwtime.h ******************************************/
  60857. /*
  60858. ** 2008 May 27
  60859. **
  60860. ** The author disclaims copyright to this source code. In place of
  60861. ** a legal notice, here is a blessing:
  60862. **
  60863. ** May you do good and not evil.
  60864. ** May you find forgiveness for yourself and forgive others.
  60865. ** May you share freely, never taking more than you give.
  60866. **
  60867. ******************************************************************************
  60868. **
  60869. ** This file contains inline asm code for retrieving "high-performance"
  60870. ** counters for x86 class CPUs.
  60871. */
  60872. #ifndef _HWTIME_H_
  60873. #define _HWTIME_H_
  60874. /*
  60875. ** The following routine only works on pentium-class (or newer) processors.
  60876. ** It uses the RDTSC opcode to read the cycle count value out of the
  60877. ** processor and returns that value. This can be used for high-res
  60878. ** profiling.
  60879. */
  60880. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  60881. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  60882. #if defined(__GNUC__)
  60883. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  60884. unsigned int lo, hi;
  60885. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  60886. return (sqlite_uint64)hi << 32 | lo;
  60887. }
  60888. #elif defined(_MSC_VER)
  60889. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  60890. __asm {
  60891. rdtsc
  60892. ret ; return value at EDX:EAX
  60893. }
  60894. }
  60895. #endif
  60896. #elif (defined(__GNUC__) && defined(__x86_64__))
  60897. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  60898. unsigned long val;
  60899. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  60900. return val;
  60901. }
  60902. #elif (defined(__GNUC__) && defined(__ppc__))
  60903. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  60904. unsigned long long retval;
  60905. unsigned long junk;
  60906. __asm__ __volatile__ ("\n\
  60907. 1: mftbu %1\n\
  60908. mftb %L0\n\
  60909. mftbu %0\n\
  60910. cmpw %0,%1\n\
  60911. bne 1b"
  60912. : "=r" (retval), "=r" (junk));
  60913. return retval;
  60914. }
  60915. #else
  60916. #error Need implementation of sqlite3Hwtime() for your platform.
  60917. /*
  60918. ** To compile without implementing sqlite3Hwtime() for your platform,
  60919. ** you can remove the above #error and use the following
  60920. ** stub function. You will lose timing support for many
  60921. ** of the debugging and testing utilities, but it should at
  60922. ** least compile and run.
  60923. */
  60924. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  60925. #endif
  60926. #endif /* !defined(_HWTIME_H_) */
  60927. /************** End of hwtime.h **********************************************/
  60928. /************** Continuing where we left off in vdbe.c ***********************/
  60929. #endif
  60930. /*
  60931. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  60932. ** sqlite3_interrupt() routine has been called. If it has been, then
  60933. ** processing of the VDBE program is interrupted.
  60934. **
  60935. ** This macro added to every instruction that does a jump in order to
  60936. ** implement a loop. This test used to be on every single instruction,
  60937. ** but that meant we more testing than we needed. By only testing the
  60938. ** flag on jump instructions, we get a (small) speed improvement.
  60939. */
  60940. #define CHECK_FOR_INTERRUPT \
  60941. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  60942. #ifndef NDEBUG
  60943. /*
  60944. ** This function is only called from within an assert() expression. It
  60945. ** checks that the sqlite3.nTransaction variable is correctly set to
  60946. ** the number of non-transaction savepoints currently in the
  60947. ** linked list starting at sqlite3.pSavepoint.
  60948. **
  60949. ** Usage:
  60950. **
  60951. ** assert( checkSavepointCount(db) );
  60952. */
  60953. static int checkSavepointCount(sqlite3 *db){
  60954. int n = 0;
  60955. Savepoint *p;
  60956. for(p=db->pSavepoint; p; p=p->pNext) n++;
  60957. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  60958. return 1;
  60959. }
  60960. #endif
  60961. /*
  60962. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  60963. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  60964. ** in memory obtained from sqlite3DbMalloc).
  60965. */
  60966. static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
  60967. sqlite3 *db = p->db;
  60968. sqlite3DbFree(db, p->zErrMsg);
  60969. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  60970. sqlite3_free(pVtab->zErrMsg);
  60971. pVtab->zErrMsg = 0;
  60972. }
  60973. /*
  60974. ** Execute as much of a VDBE program as we can then return.
  60975. **
  60976. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  60977. ** close the program with a final OP_Halt and to set up the callbacks
  60978. ** and the error message pointer.
  60979. **
  60980. ** Whenever a row or result data is available, this routine will either
  60981. ** invoke the result callback (if there is one) or return with
  60982. ** SQLITE_ROW.
  60983. **
  60984. ** If an attempt is made to open a locked database, then this routine
  60985. ** will either invoke the busy callback (if there is one) or it will
  60986. ** return SQLITE_BUSY.
  60987. **
  60988. ** If an error occurs, an error message is written to memory obtained
  60989. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  60990. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  60991. **
  60992. ** If the callback ever returns non-zero, then the program exits
  60993. ** immediately. There will be no error message but the p->rc field is
  60994. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  60995. **
  60996. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  60997. ** routine to return SQLITE_ERROR.
  60998. **
  60999. ** Other fatal errors return SQLITE_ERROR.
  61000. **
  61001. ** After this routine has finished, sqlite3VdbeFinalize() should be
  61002. ** used to clean up the mess that was left behind.
  61003. */
  61004. SQLITE_PRIVATE int sqlite3VdbeExec(
  61005. Vdbe *p /* The VDBE */
  61006. ){
  61007. int pc=0; /* The program counter */
  61008. Op *aOp = p->aOp; /* Copy of p->aOp */
  61009. Op *pOp; /* Current operation */
  61010. int rc = SQLITE_OK; /* Value to return */
  61011. sqlite3 *db = p->db; /* The database */
  61012. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  61013. u8 encoding = ENC(db); /* The database encoding */
  61014. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  61015. int checkProgress; /* True if progress callbacks are enabled */
  61016. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  61017. #endif
  61018. Mem *aMem = p->aMem; /* Copy of p->aMem */
  61019. Mem *pIn1 = 0; /* 1st input operand */
  61020. Mem *pIn2 = 0; /* 2nd input operand */
  61021. Mem *pIn3 = 0; /* 3rd input operand */
  61022. Mem *pOut = 0; /* Output operand */
  61023. int iCompare = 0; /* Result of last OP_Compare operation */
  61024. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  61025. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  61026. #ifdef VDBE_PROFILE
  61027. u64 start; /* CPU clock count at start of opcode */
  61028. int origPc; /* Program counter at start of opcode */
  61029. #endif
  61030. /********************************************************************
  61031. ** Automatically generated code
  61032. **
  61033. ** The following union is automatically generated by the
  61034. ** vdbe-compress.tcl script. The purpose of this union is to
  61035. ** reduce the amount of stack space required by this function.
  61036. ** See comments in the vdbe-compress.tcl script for details.
  61037. */
  61038. union vdbeExecUnion {
  61039. struct OP_Yield_stack_vars {
  61040. int pcDest;
  61041. } aa;
  61042. struct OP_Null_stack_vars {
  61043. int cnt;
  61044. u16 nullFlag;
  61045. } ab;
  61046. struct OP_Variable_stack_vars {
  61047. Mem *pVar; /* Value being transferred */
  61048. } ac;
  61049. struct OP_Move_stack_vars {
  61050. char *zMalloc; /* Holding variable for allocated memory */
  61051. int n; /* Number of registers left to copy */
  61052. int p1; /* Register to copy from */
  61053. int p2; /* Register to copy to */
  61054. } ad;
  61055. struct OP_Copy_stack_vars {
  61056. int n;
  61057. } ae;
  61058. struct OP_ResultRow_stack_vars {
  61059. Mem *pMem;
  61060. int i;
  61061. } af;
  61062. struct OP_Concat_stack_vars {
  61063. i64 nByte;
  61064. } ag;
  61065. struct OP_Remainder_stack_vars {
  61066. char bIntint; /* Started out as two integer operands */
  61067. int flags; /* Combined MEM_* flags from both inputs */
  61068. i64 iA; /* Integer value of left operand */
  61069. i64 iB; /* Integer value of right operand */
  61070. double rA; /* Real value of left operand */
  61071. double rB; /* Real value of right operand */
  61072. } ah;
  61073. struct OP_Function_stack_vars {
  61074. int i;
  61075. Mem *pArg;
  61076. sqlite3_context ctx;
  61077. sqlite3_value **apVal;
  61078. int n;
  61079. } ai;
  61080. struct OP_ShiftRight_stack_vars {
  61081. i64 iA;
  61082. u64 uA;
  61083. i64 iB;
  61084. u8 op;
  61085. } aj;
  61086. struct OP_Ge_stack_vars {
  61087. int res; /* Result of the comparison of pIn1 against pIn3 */
  61088. char affinity; /* Affinity to use for comparison */
  61089. u16 flags1; /* Copy of initial value of pIn1->flags */
  61090. u16 flags3; /* Copy of initial value of pIn3->flags */
  61091. } ak;
  61092. struct OP_Compare_stack_vars {
  61093. int n;
  61094. int i;
  61095. int p1;
  61096. int p2;
  61097. const KeyInfo *pKeyInfo;
  61098. int idx;
  61099. CollSeq *pColl; /* Collating sequence to use on this term */
  61100. int bRev; /* True for DESCENDING sort order */
  61101. } al;
  61102. struct OP_Or_stack_vars {
  61103. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61104. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61105. } am;
  61106. struct OP_IfNot_stack_vars {
  61107. int c;
  61108. } an;
  61109. struct OP_Column_stack_vars {
  61110. u32 payloadSize; /* Number of bytes in the record */
  61111. i64 payloadSize64; /* Number of bytes in the record */
  61112. int p1; /* P1 value of the opcode */
  61113. int p2; /* column number to retrieve */
  61114. VdbeCursor *pC; /* The VDBE cursor */
  61115. char *zRec; /* Pointer to complete record-data */
  61116. BtCursor *pCrsr; /* The BTree cursor */
  61117. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  61118. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  61119. int nField; /* number of fields in the record */
  61120. int len; /* The length of the serialized data for the column */
  61121. int i; /* Loop counter */
  61122. char *zData; /* Part of the record being decoded */
  61123. Mem *pDest; /* Where to write the extracted value */
  61124. Mem sMem; /* For storing the record being decoded */
  61125. u8 *zIdx; /* Index into header */
  61126. u8 *zEndHdr; /* Pointer to first byte after the header */
  61127. u32 offset; /* Offset into the data */
  61128. u32 szField; /* Number of bytes in the content of a field */
  61129. int szHdr; /* Size of the header size field at start of record */
  61130. int avail; /* Number of bytes of available data */
  61131. u32 t; /* A type code from the record header */
  61132. Mem *pReg; /* PseudoTable input register */
  61133. } ao;
  61134. struct OP_Affinity_stack_vars {
  61135. const char *zAffinity; /* The affinity to be applied */
  61136. char cAff; /* A single character of affinity */
  61137. } ap;
  61138. struct OP_MakeRecord_stack_vars {
  61139. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  61140. Mem *pRec; /* The new record */
  61141. u64 nData; /* Number of bytes of data space */
  61142. int nHdr; /* Number of bytes of header space */
  61143. i64 nByte; /* Data space required for this record */
  61144. int nZero; /* Number of zero bytes at the end of the record */
  61145. int nVarint; /* Number of bytes in a varint */
  61146. u32 serial_type; /* Type field */
  61147. Mem *pData0; /* First field to be combined into the record */
  61148. Mem *pLast; /* Last field of the record */
  61149. int nField; /* Number of fields in the record */
  61150. char *zAffinity; /* The affinity string for the record */
  61151. int file_format; /* File format to use for encoding */
  61152. int i; /* Space used in zNewRecord[] */
  61153. int len; /* Length of a field */
  61154. } aq;
  61155. struct OP_Count_stack_vars {
  61156. i64 nEntry;
  61157. BtCursor *pCrsr;
  61158. } ar;
  61159. struct OP_Savepoint_stack_vars {
  61160. int p1; /* Value of P1 operand */
  61161. char *zName; /* Name of savepoint */
  61162. int nName;
  61163. Savepoint *pNew;
  61164. Savepoint *pSavepoint;
  61165. Savepoint *pTmp;
  61166. int iSavepoint;
  61167. int ii;
  61168. } as;
  61169. struct OP_AutoCommit_stack_vars {
  61170. int desiredAutoCommit;
  61171. int iRollback;
  61172. int turnOnAC;
  61173. } at;
  61174. struct OP_Transaction_stack_vars {
  61175. Btree *pBt;
  61176. } au;
  61177. struct OP_ReadCookie_stack_vars {
  61178. int iMeta;
  61179. int iDb;
  61180. int iCookie;
  61181. } av;
  61182. struct OP_SetCookie_stack_vars {
  61183. Db *pDb;
  61184. } aw;
  61185. struct OP_VerifyCookie_stack_vars {
  61186. int iMeta;
  61187. int iGen;
  61188. Btree *pBt;
  61189. } ax;
  61190. struct OP_OpenWrite_stack_vars {
  61191. int nField;
  61192. KeyInfo *pKeyInfo;
  61193. int p2;
  61194. int iDb;
  61195. int wrFlag;
  61196. Btree *pX;
  61197. VdbeCursor *pCur;
  61198. Db *pDb;
  61199. } ay;
  61200. struct OP_OpenEphemeral_stack_vars {
  61201. VdbeCursor *pCx;
  61202. } az;
  61203. struct OP_SorterOpen_stack_vars {
  61204. VdbeCursor *pCx;
  61205. } ba;
  61206. struct OP_OpenPseudo_stack_vars {
  61207. VdbeCursor *pCx;
  61208. } bb;
  61209. struct OP_SeekGt_stack_vars {
  61210. int res;
  61211. int oc;
  61212. VdbeCursor *pC;
  61213. UnpackedRecord r;
  61214. int nField;
  61215. i64 iKey; /* The rowid we are to seek to */
  61216. } bc;
  61217. struct OP_Seek_stack_vars {
  61218. VdbeCursor *pC;
  61219. } bd;
  61220. struct OP_Found_stack_vars {
  61221. int alreadyExists;
  61222. VdbeCursor *pC;
  61223. int res;
  61224. char *pFree;
  61225. UnpackedRecord *pIdxKey;
  61226. UnpackedRecord r;
  61227. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  61228. } be;
  61229. struct OP_IsUnique_stack_vars {
  61230. u16 ii;
  61231. VdbeCursor *pCx;
  61232. BtCursor *pCrsr;
  61233. u16 nField;
  61234. Mem *aMx;
  61235. UnpackedRecord r; /* B-Tree index search key */
  61236. i64 R; /* Rowid stored in register P3 */
  61237. } bf;
  61238. struct OP_NotExists_stack_vars {
  61239. VdbeCursor *pC;
  61240. BtCursor *pCrsr;
  61241. int res;
  61242. u64 iKey;
  61243. } bg;
  61244. struct OP_NewRowid_stack_vars {
  61245. i64 v; /* The new rowid */
  61246. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  61247. int res; /* Result of an sqlite3BtreeLast() */
  61248. int cnt; /* Counter to limit the number of searches */
  61249. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  61250. VdbeFrame *pFrame; /* Root frame of VDBE */
  61251. } bh;
  61252. struct OP_InsertInt_stack_vars {
  61253. Mem *pData; /* MEM cell holding data for the record to be inserted */
  61254. Mem *pKey; /* MEM cell holding key for the record */
  61255. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  61256. VdbeCursor *pC; /* Cursor to table into which insert is written */
  61257. int nZero; /* Number of zero-bytes to append */
  61258. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  61259. const char *zDb; /* database name - used by the update hook */
  61260. const char *zTbl; /* Table name - used by the opdate hook */
  61261. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  61262. } bi;
  61263. struct OP_Delete_stack_vars {
  61264. i64 iKey;
  61265. VdbeCursor *pC;
  61266. } bj;
  61267. struct OP_SorterCompare_stack_vars {
  61268. VdbeCursor *pC;
  61269. int res;
  61270. } bk;
  61271. struct OP_SorterData_stack_vars {
  61272. VdbeCursor *pC;
  61273. } bl;
  61274. struct OP_RowData_stack_vars {
  61275. VdbeCursor *pC;
  61276. BtCursor *pCrsr;
  61277. u32 n;
  61278. i64 n64;
  61279. } bm;
  61280. struct OP_Rowid_stack_vars {
  61281. VdbeCursor *pC;
  61282. i64 v;
  61283. sqlite3_vtab *pVtab;
  61284. const sqlite3_module *pModule;
  61285. } bn;
  61286. struct OP_NullRow_stack_vars {
  61287. VdbeCursor *pC;
  61288. } bo;
  61289. struct OP_Last_stack_vars {
  61290. VdbeCursor *pC;
  61291. BtCursor *pCrsr;
  61292. int res;
  61293. } bp;
  61294. struct OP_Rewind_stack_vars {
  61295. VdbeCursor *pC;
  61296. BtCursor *pCrsr;
  61297. int res;
  61298. } bq;
  61299. struct OP_Next_stack_vars {
  61300. VdbeCursor *pC;
  61301. int res;
  61302. } br;
  61303. struct OP_IdxInsert_stack_vars {
  61304. VdbeCursor *pC;
  61305. BtCursor *pCrsr;
  61306. int nKey;
  61307. const char *zKey;
  61308. } bs;
  61309. struct OP_IdxDelete_stack_vars {
  61310. VdbeCursor *pC;
  61311. BtCursor *pCrsr;
  61312. int res;
  61313. UnpackedRecord r;
  61314. } bt;
  61315. struct OP_IdxRowid_stack_vars {
  61316. BtCursor *pCrsr;
  61317. VdbeCursor *pC;
  61318. i64 rowid;
  61319. } bu;
  61320. struct OP_IdxGE_stack_vars {
  61321. VdbeCursor *pC;
  61322. int res;
  61323. UnpackedRecord r;
  61324. } bv;
  61325. struct OP_Destroy_stack_vars {
  61326. int iMoved;
  61327. int iCnt;
  61328. Vdbe *pVdbe;
  61329. int iDb;
  61330. } bw;
  61331. struct OP_Clear_stack_vars {
  61332. int nChange;
  61333. } bx;
  61334. struct OP_CreateTable_stack_vars {
  61335. int pgno;
  61336. int flags;
  61337. Db *pDb;
  61338. } by;
  61339. struct OP_ParseSchema_stack_vars {
  61340. int iDb;
  61341. const char *zMaster;
  61342. char *zSql;
  61343. InitData initData;
  61344. } bz;
  61345. struct OP_IntegrityCk_stack_vars {
  61346. int nRoot; /* Number of tables to check. (Number of root pages.) */
  61347. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  61348. int j; /* Loop counter */
  61349. int nErr; /* Number of errors reported */
  61350. char *z; /* Text of the error report */
  61351. Mem *pnErr; /* Register keeping track of errors remaining */
  61352. } ca;
  61353. struct OP_RowSetRead_stack_vars {
  61354. i64 val;
  61355. } cb;
  61356. struct OP_RowSetTest_stack_vars {
  61357. int iSet;
  61358. int exists;
  61359. } cc;
  61360. struct OP_Program_stack_vars {
  61361. int nMem; /* Number of memory registers for sub-program */
  61362. int nByte; /* Bytes of runtime space required for sub-program */
  61363. Mem *pRt; /* Register to allocate runtime space */
  61364. Mem *pMem; /* Used to iterate through memory cells */
  61365. Mem *pEnd; /* Last memory cell in new array */
  61366. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  61367. SubProgram *pProgram; /* Sub-program to execute */
  61368. void *t; /* Token identifying trigger */
  61369. } cd;
  61370. struct OP_Param_stack_vars {
  61371. VdbeFrame *pFrame;
  61372. Mem *pIn;
  61373. } ce;
  61374. struct OP_MemMax_stack_vars {
  61375. Mem *pIn1;
  61376. VdbeFrame *pFrame;
  61377. } cf;
  61378. struct OP_AggStep_stack_vars {
  61379. int n;
  61380. int i;
  61381. Mem *pMem;
  61382. Mem *pRec;
  61383. sqlite3_context ctx;
  61384. sqlite3_value **apVal;
  61385. } cg;
  61386. struct OP_AggFinal_stack_vars {
  61387. Mem *pMem;
  61388. } ch;
  61389. struct OP_Checkpoint_stack_vars {
  61390. int i; /* Loop counter */
  61391. int aRes[3]; /* Results */
  61392. Mem *pMem; /* Write results here */
  61393. } ci;
  61394. struct OP_JournalMode_stack_vars {
  61395. Btree *pBt; /* Btree to change journal mode of */
  61396. Pager *pPager; /* Pager associated with pBt */
  61397. int eNew; /* New journal mode */
  61398. int eOld; /* The old journal mode */
  61399. #ifndef SQLITE_OMIT_WAL
  61400. const char *zFilename; /* Name of database file for pPager */
  61401. #endif
  61402. } cj;
  61403. struct OP_IncrVacuum_stack_vars {
  61404. Btree *pBt;
  61405. } ck;
  61406. struct OP_VBegin_stack_vars {
  61407. VTable *pVTab;
  61408. } cl;
  61409. struct OP_VOpen_stack_vars {
  61410. VdbeCursor *pCur;
  61411. sqlite3_vtab_cursor *pVtabCursor;
  61412. sqlite3_vtab *pVtab;
  61413. sqlite3_module *pModule;
  61414. } cm;
  61415. struct OP_VFilter_stack_vars {
  61416. int nArg;
  61417. int iQuery;
  61418. const sqlite3_module *pModule;
  61419. Mem *pQuery;
  61420. Mem *pArgc;
  61421. sqlite3_vtab_cursor *pVtabCursor;
  61422. sqlite3_vtab *pVtab;
  61423. VdbeCursor *pCur;
  61424. int res;
  61425. int i;
  61426. Mem **apArg;
  61427. } cn;
  61428. struct OP_VColumn_stack_vars {
  61429. sqlite3_vtab *pVtab;
  61430. const sqlite3_module *pModule;
  61431. Mem *pDest;
  61432. sqlite3_context sContext;
  61433. } co;
  61434. struct OP_VNext_stack_vars {
  61435. sqlite3_vtab *pVtab;
  61436. const sqlite3_module *pModule;
  61437. int res;
  61438. VdbeCursor *pCur;
  61439. } cp;
  61440. struct OP_VRename_stack_vars {
  61441. sqlite3_vtab *pVtab;
  61442. Mem *pName;
  61443. } cq;
  61444. struct OP_VUpdate_stack_vars {
  61445. sqlite3_vtab *pVtab;
  61446. sqlite3_module *pModule;
  61447. int nArg;
  61448. int i;
  61449. sqlite_int64 rowid;
  61450. Mem **apArg;
  61451. Mem *pX;
  61452. } cr;
  61453. struct OP_Trace_stack_vars {
  61454. char *zTrace;
  61455. char *z;
  61456. } cs;
  61457. } u;
  61458. /* End automatically generated code
  61459. ********************************************************************/
  61460. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  61461. sqlite3VdbeEnter(p);
  61462. if( p->rc==SQLITE_NOMEM ){
  61463. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  61464. ** sqlite3_column_text16() failed. */
  61465. goto no_mem;
  61466. }
  61467. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  61468. p->rc = SQLITE_OK;
  61469. assert( p->explain==0 );
  61470. p->pResultSet = 0;
  61471. db->busyHandler.nBusy = 0;
  61472. CHECK_FOR_INTERRUPT;
  61473. sqlite3VdbeIOTraceSql(p);
  61474. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  61475. checkProgress = db->xProgress!=0;
  61476. #endif
  61477. #ifdef SQLITE_DEBUG
  61478. sqlite3BeginBenignMalloc();
  61479. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  61480. int i;
  61481. printf("VDBE Program Listing:\n");
  61482. sqlite3VdbePrintSql(p);
  61483. for(i=0; i<p->nOp; i++){
  61484. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  61485. }
  61486. }
  61487. sqlite3EndBenignMalloc();
  61488. #endif
  61489. for(pc=p->pc; rc==SQLITE_OK; pc++){
  61490. assert( pc>=0 && pc<p->nOp );
  61491. if( db->mallocFailed ) goto no_mem;
  61492. #ifdef VDBE_PROFILE
  61493. origPc = pc;
  61494. start = sqlite3Hwtime();
  61495. #endif
  61496. pOp = &aOp[pc];
  61497. /* Only allow tracing if SQLITE_DEBUG is defined.
  61498. */
  61499. #ifdef SQLITE_DEBUG
  61500. if( p->trace ){
  61501. if( pc==0 ){
  61502. printf("VDBE Execution Trace:\n");
  61503. sqlite3VdbePrintSql(p);
  61504. }
  61505. sqlite3VdbePrintOp(p->trace, pc, pOp);
  61506. }
  61507. #endif
  61508. /* Check to see if we need to simulate an interrupt. This only happens
  61509. ** if we have a special test build.
  61510. */
  61511. #ifdef SQLITE_TEST
  61512. if( sqlite3_interrupt_count>0 ){
  61513. sqlite3_interrupt_count--;
  61514. if( sqlite3_interrupt_count==0 ){
  61515. sqlite3_interrupt(db);
  61516. }
  61517. }
  61518. #endif
  61519. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  61520. /* Call the progress callback if it is configured and the required number
  61521. ** of VDBE ops have been executed (either since this invocation of
  61522. ** sqlite3VdbeExec() or since last time the progress callback was called).
  61523. ** If the progress callback returns non-zero, exit the virtual machine with
  61524. ** a return code SQLITE_ABORT.
  61525. */
  61526. if( checkProgress ){
  61527. if( db->nProgressOps==nProgressOps ){
  61528. int prc;
  61529. prc = db->xProgress(db->pProgressArg);
  61530. if( prc!=0 ){
  61531. rc = SQLITE_INTERRUPT;
  61532. goto vdbe_error_halt;
  61533. }
  61534. nProgressOps = 0;
  61535. }
  61536. nProgressOps++;
  61537. }
  61538. #endif
  61539. /* On any opcode with the "out2-prerelease" tag, free any
  61540. ** external allocations out of mem[p2] and set mem[p2] to be
  61541. ** an undefined integer. Opcodes will either fill in the integer
  61542. ** value or convert mem[p2] to a different type.
  61543. */
  61544. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  61545. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  61546. assert( pOp->p2>0 );
  61547. assert( pOp->p2<=p->nMem );
  61548. pOut = &aMem[pOp->p2];
  61549. memAboutToChange(p, pOut);
  61550. VdbeMemRelease(pOut);
  61551. pOut->flags = MEM_Int;
  61552. }
  61553. /* Sanity checking on other operands */
  61554. #ifdef SQLITE_DEBUG
  61555. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  61556. assert( pOp->p1>0 );
  61557. assert( pOp->p1<=p->nMem );
  61558. assert( memIsValid(&aMem[pOp->p1]) );
  61559. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  61560. }
  61561. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  61562. assert( pOp->p2>0 );
  61563. assert( pOp->p2<=p->nMem );
  61564. assert( memIsValid(&aMem[pOp->p2]) );
  61565. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  61566. }
  61567. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  61568. assert( pOp->p3>0 );
  61569. assert( pOp->p3<=p->nMem );
  61570. assert( memIsValid(&aMem[pOp->p3]) );
  61571. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  61572. }
  61573. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  61574. assert( pOp->p2>0 );
  61575. assert( pOp->p2<=p->nMem );
  61576. memAboutToChange(p, &aMem[pOp->p2]);
  61577. }
  61578. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  61579. assert( pOp->p3>0 );
  61580. assert( pOp->p3<=p->nMem );
  61581. memAboutToChange(p, &aMem[pOp->p3]);
  61582. }
  61583. #endif
  61584. switch( pOp->opcode ){
  61585. /*****************************************************************************
  61586. ** What follows is a massive switch statement where each case implements a
  61587. ** separate instruction in the virtual machine. If we follow the usual
  61588. ** indentation conventions, each case should be indented by 6 spaces. But
  61589. ** that is a lot of wasted space on the left margin. So the code within
  61590. ** the switch statement will break with convention and be flush-left. Another
  61591. ** big comment (similar to this one) will mark the point in the code where
  61592. ** we transition back to normal indentation.
  61593. **
  61594. ** The formatting of each case is important. The makefile for SQLite
  61595. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  61596. ** file looking for lines that begin with "case OP_". The opcodes.h files
  61597. ** will be filled with #defines that give unique integer values to each
  61598. ** opcode and the opcodes.c file is filled with an array of strings where
  61599. ** each string is the symbolic name for the corresponding opcode. If the
  61600. ** case statement is followed by a comment of the form "/# same as ... #/"
  61601. ** that comment is used to determine the particular value of the opcode.
  61602. **
  61603. ** Other keywords in the comment that follows each case are used to
  61604. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  61605. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  61606. ** the mkopcodeh.awk script for additional information.
  61607. **
  61608. ** Documentation about VDBE opcodes is generated by scanning this file
  61609. ** for lines of that contain "Opcode:". That line and all subsequent
  61610. ** comment lines are used in the generation of the opcode.html documentation
  61611. ** file.
  61612. **
  61613. ** SUMMARY:
  61614. **
  61615. ** Formatting is important to scripts that scan this file.
  61616. ** Do not deviate from the formatting style currently in use.
  61617. **
  61618. *****************************************************************************/
  61619. /* Opcode: Goto * P2 * * *
  61620. **
  61621. ** An unconditional jump to address P2.
  61622. ** The next instruction executed will be
  61623. ** the one at index P2 from the beginning of
  61624. ** the program.
  61625. */
  61626. case OP_Goto: { /* jump */
  61627. CHECK_FOR_INTERRUPT;
  61628. pc = pOp->p2 - 1;
  61629. break;
  61630. }
  61631. /* Opcode: Gosub P1 P2 * * *
  61632. **
  61633. ** Write the current address onto register P1
  61634. ** and then jump to address P2.
  61635. */
  61636. case OP_Gosub: { /* jump */
  61637. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  61638. pIn1 = &aMem[pOp->p1];
  61639. assert( (pIn1->flags & MEM_Dyn)==0 );
  61640. memAboutToChange(p, pIn1);
  61641. pIn1->flags = MEM_Int;
  61642. pIn1->u.i = pc;
  61643. REGISTER_TRACE(pOp->p1, pIn1);
  61644. pc = pOp->p2 - 1;
  61645. break;
  61646. }
  61647. /* Opcode: Return P1 * * * *
  61648. **
  61649. ** Jump to the next instruction after the address in register P1.
  61650. */
  61651. case OP_Return: { /* in1 */
  61652. pIn1 = &aMem[pOp->p1];
  61653. assert( pIn1->flags & MEM_Int );
  61654. pc = (int)pIn1->u.i;
  61655. break;
  61656. }
  61657. /* Opcode: Yield P1 * * * *
  61658. **
  61659. ** Swap the program counter with the value in register P1.
  61660. */
  61661. case OP_Yield: { /* in1 */
  61662. #if 0 /* local variables moved into u.aa */
  61663. int pcDest;
  61664. #endif /* local variables moved into u.aa */
  61665. pIn1 = &aMem[pOp->p1];
  61666. assert( (pIn1->flags & MEM_Dyn)==0 );
  61667. pIn1->flags = MEM_Int;
  61668. u.aa.pcDest = (int)pIn1->u.i;
  61669. pIn1->u.i = pc;
  61670. REGISTER_TRACE(pOp->p1, pIn1);
  61671. pc = u.aa.pcDest;
  61672. break;
  61673. }
  61674. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  61675. **
  61676. ** Check the value in register P3. If it is NULL then Halt using
  61677. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  61678. ** value in register P3 is not NULL, then this routine is a no-op.
  61679. */
  61680. case OP_HaltIfNull: { /* in3 */
  61681. pIn3 = &aMem[pOp->p3];
  61682. if( (pIn3->flags & MEM_Null)==0 ) break;
  61683. /* Fall through into OP_Halt */
  61684. }
  61685. /* Opcode: Halt P1 P2 * P4 *
  61686. **
  61687. ** Exit immediately. All open cursors, etc are closed
  61688. ** automatically.
  61689. **
  61690. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  61691. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  61692. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  61693. ** whether or not to rollback the current transaction. Do not rollback
  61694. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  61695. ** then back out all changes that have occurred during this execution of the
  61696. ** VDBE, but do not rollback the transaction.
  61697. **
  61698. ** If P4 is not null then it is an error message string.
  61699. **
  61700. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  61701. ** every program. So a jump past the last instruction of the program
  61702. ** is the same as executing Halt.
  61703. */
  61704. case OP_Halt: {
  61705. if( pOp->p1==SQLITE_OK && p->pFrame ){
  61706. /* Halt the sub-program. Return control to the parent frame. */
  61707. VdbeFrame *pFrame = p->pFrame;
  61708. p->pFrame = pFrame->pParent;
  61709. p->nFrame--;
  61710. sqlite3VdbeSetChanges(db, p->nChange);
  61711. pc = sqlite3VdbeFrameRestore(pFrame);
  61712. lastRowid = db->lastRowid;
  61713. if( pOp->p2==OE_Ignore ){
  61714. /* Instruction pc is the OP_Program that invoked the sub-program
  61715. ** currently being halted. If the p2 instruction of this OP_Halt
  61716. ** instruction is set to OE_Ignore, then the sub-program is throwing
  61717. ** an IGNORE exception. In this case jump to the address specified
  61718. ** as the p2 of the calling OP_Program. */
  61719. pc = p->aOp[pc].p2-1;
  61720. }
  61721. aOp = p->aOp;
  61722. aMem = p->aMem;
  61723. break;
  61724. }
  61725. p->rc = pOp->p1;
  61726. p->errorAction = (u8)pOp->p2;
  61727. p->pc = pc;
  61728. if( pOp->p4.z ){
  61729. assert( p->rc!=SQLITE_OK );
  61730. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  61731. testcase( sqlite3GlobalConfig.xLog!=0 );
  61732. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  61733. }else if( p->rc ){
  61734. testcase( sqlite3GlobalConfig.xLog!=0 );
  61735. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  61736. }
  61737. rc = sqlite3VdbeHalt(p);
  61738. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  61739. if( rc==SQLITE_BUSY ){
  61740. p->rc = rc = SQLITE_BUSY;
  61741. }else{
  61742. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  61743. assert( rc==SQLITE_OK || db->nDeferredCons>0 );
  61744. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  61745. }
  61746. goto vdbe_return;
  61747. }
  61748. /* Opcode: Integer P1 P2 * * *
  61749. **
  61750. ** The 32-bit integer value P1 is written into register P2.
  61751. */
  61752. case OP_Integer: { /* out2-prerelease */
  61753. pOut->u.i = pOp->p1;
  61754. break;
  61755. }
  61756. /* Opcode: Int64 * P2 * P4 *
  61757. **
  61758. ** P4 is a pointer to a 64-bit integer value.
  61759. ** Write that value into register P2.
  61760. */
  61761. case OP_Int64: { /* out2-prerelease */
  61762. assert( pOp->p4.pI64!=0 );
  61763. pOut->u.i = *pOp->p4.pI64;
  61764. break;
  61765. }
  61766. #ifndef SQLITE_OMIT_FLOATING_POINT
  61767. /* Opcode: Real * P2 * P4 *
  61768. **
  61769. ** P4 is a pointer to a 64-bit floating point value.
  61770. ** Write that value into register P2.
  61771. */
  61772. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  61773. pOut->flags = MEM_Real;
  61774. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  61775. pOut->r = *pOp->p4.pReal;
  61776. break;
  61777. }
  61778. #endif
  61779. /* Opcode: String8 * P2 * P4 *
  61780. **
  61781. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  61782. ** into an OP_String before it is executed for the first time.
  61783. */
  61784. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  61785. assert( pOp->p4.z!=0 );
  61786. pOp->opcode = OP_String;
  61787. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  61788. #ifndef SQLITE_OMIT_UTF16
  61789. if( encoding!=SQLITE_UTF8 ){
  61790. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  61791. if( rc==SQLITE_TOOBIG ) goto too_big;
  61792. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  61793. assert( pOut->zMalloc==pOut->z );
  61794. assert( pOut->flags & MEM_Dyn );
  61795. pOut->zMalloc = 0;
  61796. pOut->flags |= MEM_Static;
  61797. pOut->flags &= ~MEM_Dyn;
  61798. if( pOp->p4type==P4_DYNAMIC ){
  61799. sqlite3DbFree(db, pOp->p4.z);
  61800. }
  61801. pOp->p4type = P4_DYNAMIC;
  61802. pOp->p4.z = pOut->z;
  61803. pOp->p1 = pOut->n;
  61804. }
  61805. #endif
  61806. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  61807. goto too_big;
  61808. }
  61809. /* Fall through to the next case, OP_String */
  61810. }
  61811. /* Opcode: String P1 P2 * P4 *
  61812. **
  61813. ** The string value P4 of length P1 (bytes) is stored in register P2.
  61814. */
  61815. case OP_String: { /* out2-prerelease */
  61816. assert( pOp->p4.z!=0 );
  61817. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  61818. pOut->z = pOp->p4.z;
  61819. pOut->n = pOp->p1;
  61820. pOut->enc = encoding;
  61821. UPDATE_MAX_BLOBSIZE(pOut);
  61822. break;
  61823. }
  61824. /* Opcode: Null P1 P2 P3 * *
  61825. **
  61826. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  61827. ** NULL into register P3 and every register in between P2 and P3. If P3
  61828. ** is less than P2 (typically P3 is zero) then only register P2 is
  61829. ** set to NULL.
  61830. **
  61831. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  61832. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  61833. ** OP_Ne or OP_Eq.
  61834. */
  61835. case OP_Null: { /* out2-prerelease */
  61836. #if 0 /* local variables moved into u.ab */
  61837. int cnt;
  61838. u16 nullFlag;
  61839. #endif /* local variables moved into u.ab */
  61840. u.ab.cnt = pOp->p3-pOp->p2;
  61841. assert( pOp->p3<=p->nMem );
  61842. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  61843. while( u.ab.cnt>0 ){
  61844. pOut++;
  61845. memAboutToChange(p, pOut);
  61846. VdbeMemRelease(pOut);
  61847. pOut->flags = u.ab.nullFlag;
  61848. u.ab.cnt--;
  61849. }
  61850. break;
  61851. }
  61852. /* Opcode: Blob P1 P2 * P4
  61853. **
  61854. ** P4 points to a blob of data P1 bytes long. Store this
  61855. ** blob in register P2.
  61856. */
  61857. case OP_Blob: { /* out2-prerelease */
  61858. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  61859. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  61860. pOut->enc = encoding;
  61861. UPDATE_MAX_BLOBSIZE(pOut);
  61862. break;
  61863. }
  61864. /* Opcode: Variable P1 P2 * P4 *
  61865. **
  61866. ** Transfer the values of bound parameter P1 into register P2
  61867. **
  61868. ** If the parameter is named, then its name appears in P4 and P3==1.
  61869. ** The P4 value is used by sqlite3_bind_parameter_name().
  61870. */
  61871. case OP_Variable: { /* out2-prerelease */
  61872. #if 0 /* local variables moved into u.ac */
  61873. Mem *pVar; /* Value being transferred */
  61874. #endif /* local variables moved into u.ac */
  61875. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  61876. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  61877. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  61878. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  61879. goto too_big;
  61880. }
  61881. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  61882. UPDATE_MAX_BLOBSIZE(pOut);
  61883. break;
  61884. }
  61885. /* Opcode: Move P1 P2 P3 * *
  61886. **
  61887. ** Move the values in register P1..P1+P3 over into
  61888. ** registers P2..P2+P3. Registers P1..P1+P3 are
  61889. ** left holding a NULL. It is an error for register ranges
  61890. ** P1..P1+P3 and P2..P2+P3 to overlap.
  61891. */
  61892. case OP_Move: {
  61893. #if 0 /* local variables moved into u.ad */
  61894. char *zMalloc; /* Holding variable for allocated memory */
  61895. int n; /* Number of registers left to copy */
  61896. int p1; /* Register to copy from */
  61897. int p2; /* Register to copy to */
  61898. #endif /* local variables moved into u.ad */
  61899. u.ad.n = pOp->p3 + 1;
  61900. u.ad.p1 = pOp->p1;
  61901. u.ad.p2 = pOp->p2;
  61902. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  61903. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  61904. pIn1 = &aMem[u.ad.p1];
  61905. pOut = &aMem[u.ad.p2];
  61906. while( u.ad.n-- ){
  61907. assert( pOut<=&aMem[p->nMem] );
  61908. assert( pIn1<=&aMem[p->nMem] );
  61909. assert( memIsValid(pIn1) );
  61910. memAboutToChange(p, pOut);
  61911. u.ad.zMalloc = pOut->zMalloc;
  61912. pOut->zMalloc = 0;
  61913. sqlite3VdbeMemMove(pOut, pIn1);
  61914. #ifdef SQLITE_DEBUG
  61915. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  61916. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  61917. }
  61918. #endif
  61919. pIn1->zMalloc = u.ad.zMalloc;
  61920. REGISTER_TRACE(u.ad.p2++, pOut);
  61921. pIn1++;
  61922. pOut++;
  61923. }
  61924. break;
  61925. }
  61926. /* Opcode: Copy P1 P2 P3 * *
  61927. **
  61928. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  61929. **
  61930. ** This instruction makes a deep copy of the value. A duplicate
  61931. ** is made of any string or blob constant. See also OP_SCopy.
  61932. */
  61933. case OP_Copy: {
  61934. #if 0 /* local variables moved into u.ae */
  61935. int n;
  61936. #endif /* local variables moved into u.ae */
  61937. u.ae.n = pOp->p3;
  61938. pIn1 = &aMem[pOp->p1];
  61939. pOut = &aMem[pOp->p2];
  61940. assert( pOut!=pIn1 );
  61941. while( 1 ){
  61942. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  61943. Deephemeralize(pOut);
  61944. #ifdef SQLITE_DEBUG
  61945. pOut->pScopyFrom = 0;
  61946. #endif
  61947. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  61948. if( (u.ae.n--)==0 ) break;
  61949. pOut++;
  61950. pIn1++;
  61951. }
  61952. break;
  61953. }
  61954. /* Opcode: SCopy P1 P2 * * *
  61955. **
  61956. ** Make a shallow copy of register P1 into register P2.
  61957. **
  61958. ** This instruction makes a shallow copy of the value. If the value
  61959. ** is a string or blob, then the copy is only a pointer to the
  61960. ** original and hence if the original changes so will the copy.
  61961. ** Worse, if the original is deallocated, the copy becomes invalid.
  61962. ** Thus the program must guarantee that the original will not change
  61963. ** during the lifetime of the copy. Use OP_Copy to make a complete
  61964. ** copy.
  61965. */
  61966. case OP_SCopy: { /* in1, out2 */
  61967. pIn1 = &aMem[pOp->p1];
  61968. pOut = &aMem[pOp->p2];
  61969. assert( pOut!=pIn1 );
  61970. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  61971. #ifdef SQLITE_DEBUG
  61972. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  61973. #endif
  61974. REGISTER_TRACE(pOp->p2, pOut);
  61975. break;
  61976. }
  61977. /* Opcode: ResultRow P1 P2 * * *
  61978. **
  61979. ** The registers P1 through P1+P2-1 contain a single row of
  61980. ** results. This opcode causes the sqlite3_step() call to terminate
  61981. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  61982. ** structure to provide access to the top P1 values as the result
  61983. ** row.
  61984. */
  61985. case OP_ResultRow: {
  61986. #if 0 /* local variables moved into u.af */
  61987. Mem *pMem;
  61988. int i;
  61989. #endif /* local variables moved into u.af */
  61990. assert( p->nResColumn==pOp->p2 );
  61991. assert( pOp->p1>0 );
  61992. assert( pOp->p1+pOp->p2<=p->nMem+1 );
  61993. /* If this statement has violated immediate foreign key constraints, do
  61994. ** not return the number of rows modified. And do not RELEASE the statement
  61995. ** transaction. It needs to be rolled back. */
  61996. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  61997. assert( db->flags&SQLITE_CountRows );
  61998. assert( p->usesStmtJournal );
  61999. break;
  62000. }
  62001. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  62002. ** DML statements invoke this opcode to return the number of rows
  62003. ** modified to the user. This is the only way that a VM that
  62004. ** opens a statement transaction may invoke this opcode.
  62005. **
  62006. ** In case this is such a statement, close any statement transaction
  62007. ** opened by this VM before returning control to the user. This is to
  62008. ** ensure that statement-transactions are always nested, not overlapping.
  62009. ** If the open statement-transaction is not closed here, then the user
  62010. ** may step another VM that opens its own statement transaction. This
  62011. ** may lead to overlapping statement transactions.
  62012. **
  62013. ** The statement transaction is never a top-level transaction. Hence
  62014. ** the RELEASE call below can never fail.
  62015. */
  62016. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  62017. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  62018. if( NEVER(rc!=SQLITE_OK) ){
  62019. break;
  62020. }
  62021. /* Invalidate all ephemeral cursor row caches */
  62022. p->cacheCtr = (p->cacheCtr + 2)|1;
  62023. /* Make sure the results of the current row are \000 terminated
  62024. ** and have an assigned type. The results are de-ephemeralized as
  62025. ** a side effect.
  62026. */
  62027. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  62028. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  62029. assert( memIsValid(&u.af.pMem[u.af.i]) );
  62030. Deephemeralize(&u.af.pMem[u.af.i]);
  62031. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  62032. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  62033. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  62034. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  62035. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  62036. }
  62037. if( db->mallocFailed ) goto no_mem;
  62038. /* Return SQLITE_ROW
  62039. */
  62040. p->pc = pc + 1;
  62041. rc = SQLITE_ROW;
  62042. goto vdbe_return;
  62043. }
  62044. /* Opcode: Concat P1 P2 P3 * *
  62045. **
  62046. ** Add the text in register P1 onto the end of the text in
  62047. ** register P2 and store the result in register P3.
  62048. ** If either the P1 or P2 text are NULL then store NULL in P3.
  62049. **
  62050. ** P3 = P2 || P1
  62051. **
  62052. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  62053. ** if P3 is the same register as P2, the implementation is able
  62054. ** to avoid a memcpy().
  62055. */
  62056. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  62057. #if 0 /* local variables moved into u.ag */
  62058. i64 nByte;
  62059. #endif /* local variables moved into u.ag */
  62060. pIn1 = &aMem[pOp->p1];
  62061. pIn2 = &aMem[pOp->p2];
  62062. pOut = &aMem[pOp->p3];
  62063. assert( pIn1!=pOut );
  62064. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  62065. sqlite3VdbeMemSetNull(pOut);
  62066. break;
  62067. }
  62068. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  62069. Stringify(pIn1, encoding);
  62070. Stringify(pIn2, encoding);
  62071. u.ag.nByte = pIn1->n + pIn2->n;
  62072. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  62073. goto too_big;
  62074. }
  62075. MemSetTypeFlag(pOut, MEM_Str);
  62076. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  62077. goto no_mem;
  62078. }
  62079. if( pOut!=pIn2 ){
  62080. memcpy(pOut->z, pIn2->z, pIn2->n);
  62081. }
  62082. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  62083. pOut->z[u.ag.nByte] = 0;
  62084. pOut->z[u.ag.nByte+1] = 0;
  62085. pOut->flags |= MEM_Term;
  62086. pOut->n = (int)u.ag.nByte;
  62087. pOut->enc = encoding;
  62088. UPDATE_MAX_BLOBSIZE(pOut);
  62089. break;
  62090. }
  62091. /* Opcode: Add P1 P2 P3 * *
  62092. **
  62093. ** Add the value in register P1 to the value in register P2
  62094. ** and store the result in register P3.
  62095. ** If either input is NULL, the result is NULL.
  62096. */
  62097. /* Opcode: Multiply P1 P2 P3 * *
  62098. **
  62099. **
  62100. ** Multiply the value in register P1 by the value in register P2
  62101. ** and store the result in register P3.
  62102. ** If either input is NULL, the result is NULL.
  62103. */
  62104. /* Opcode: Subtract P1 P2 P3 * *
  62105. **
  62106. ** Subtract the value in register P1 from the value in register P2
  62107. ** and store the result in register P3.
  62108. ** If either input is NULL, the result is NULL.
  62109. */
  62110. /* Opcode: Divide P1 P2 P3 * *
  62111. **
  62112. ** Divide the value in register P1 by the value in register P2
  62113. ** and store the result in register P3 (P3=P2/P1). If the value in
  62114. ** register P1 is zero, then the result is NULL. If either input is
  62115. ** NULL, the result is NULL.
  62116. */
  62117. /* Opcode: Remainder P1 P2 P3 * *
  62118. **
  62119. ** Compute the remainder after integer division of the value in
  62120. ** register P1 by the value in register P2 and store the result in P3.
  62121. ** If the value in register P2 is zero the result is NULL.
  62122. ** If either operand is NULL, the result is NULL.
  62123. */
  62124. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  62125. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  62126. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  62127. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  62128. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  62129. #if 0 /* local variables moved into u.ah */
  62130. char bIntint; /* Started out as two integer operands */
  62131. int flags; /* Combined MEM_* flags from both inputs */
  62132. i64 iA; /* Integer value of left operand */
  62133. i64 iB; /* Integer value of right operand */
  62134. double rA; /* Real value of left operand */
  62135. double rB; /* Real value of right operand */
  62136. #endif /* local variables moved into u.ah */
  62137. pIn1 = &aMem[pOp->p1];
  62138. applyNumericAffinity(pIn1);
  62139. pIn2 = &aMem[pOp->p2];
  62140. applyNumericAffinity(pIn2);
  62141. pOut = &aMem[pOp->p3];
  62142. u.ah.flags = pIn1->flags | pIn2->flags;
  62143. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  62144. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  62145. u.ah.iA = pIn1->u.i;
  62146. u.ah.iB = pIn2->u.i;
  62147. u.ah.bIntint = 1;
  62148. switch( pOp->opcode ){
  62149. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62150. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62151. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  62152. case OP_Divide: {
  62153. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62154. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  62155. u.ah.iB /= u.ah.iA;
  62156. break;
  62157. }
  62158. default: {
  62159. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62160. if( u.ah.iA==-1 ) u.ah.iA = 1;
  62161. u.ah.iB %= u.ah.iA;
  62162. break;
  62163. }
  62164. }
  62165. pOut->u.i = u.ah.iB;
  62166. MemSetTypeFlag(pOut, MEM_Int);
  62167. }else{
  62168. u.ah.bIntint = 0;
  62169. fp_math:
  62170. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  62171. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  62172. switch( pOp->opcode ){
  62173. case OP_Add: u.ah.rB += u.ah.rA; break;
  62174. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  62175. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  62176. case OP_Divide: {
  62177. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  62178. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  62179. u.ah.rB /= u.ah.rA;
  62180. break;
  62181. }
  62182. default: {
  62183. u.ah.iA = (i64)u.ah.rA;
  62184. u.ah.iB = (i64)u.ah.rB;
  62185. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  62186. if( u.ah.iA==-1 ) u.ah.iA = 1;
  62187. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  62188. break;
  62189. }
  62190. }
  62191. #ifdef SQLITE_OMIT_FLOATING_POINT
  62192. pOut->u.i = u.ah.rB;
  62193. MemSetTypeFlag(pOut, MEM_Int);
  62194. #else
  62195. if( sqlite3IsNaN(u.ah.rB) ){
  62196. goto arithmetic_result_is_null;
  62197. }
  62198. pOut->r = u.ah.rB;
  62199. MemSetTypeFlag(pOut, MEM_Real);
  62200. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  62201. sqlite3VdbeIntegerAffinity(pOut);
  62202. }
  62203. #endif
  62204. }
  62205. break;
  62206. arithmetic_result_is_null:
  62207. sqlite3VdbeMemSetNull(pOut);
  62208. break;
  62209. }
  62210. /* Opcode: CollSeq P1 * * P4
  62211. **
  62212. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  62213. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  62214. ** be returned. This is used by the built-in min(), max() and nullif()
  62215. ** functions.
  62216. **
  62217. ** If P1 is not zero, then it is a register that a subsequent min() or
  62218. ** max() aggregate will set to 1 if the current row is not the minimum or
  62219. ** maximum. The P1 register is initialized to 0 by this instruction.
  62220. **
  62221. ** The interface used by the implementation of the aforementioned functions
  62222. ** to retrieve the collation sequence set by this opcode is not available
  62223. ** publicly, only to user functions defined in func.c.
  62224. */
  62225. case OP_CollSeq: {
  62226. assert( pOp->p4type==P4_COLLSEQ );
  62227. if( pOp->p1 ){
  62228. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  62229. }
  62230. break;
  62231. }
  62232. /* Opcode: Function P1 P2 P3 P4 P5
  62233. **
  62234. ** Invoke a user function (P4 is a pointer to a Function structure that
  62235. ** defines the function) with P5 arguments taken from register P2 and
  62236. ** successors. The result of the function is stored in register P3.
  62237. ** Register P3 must not be one of the function inputs.
  62238. **
  62239. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  62240. ** function was determined to be constant at compile time. If the first
  62241. ** argument was constant then bit 0 of P1 is set. This is used to determine
  62242. ** whether meta data associated with a user function argument using the
  62243. ** sqlite3_set_auxdata() API may be safely retained until the next
  62244. ** invocation of this opcode.
  62245. **
  62246. ** See also: AggStep and AggFinal
  62247. */
  62248. case OP_Function: {
  62249. #if 0 /* local variables moved into u.ai */
  62250. int i;
  62251. Mem *pArg;
  62252. sqlite3_context ctx;
  62253. sqlite3_value **apVal;
  62254. int n;
  62255. #endif /* local variables moved into u.ai */
  62256. u.ai.n = pOp->p5;
  62257. u.ai.apVal = p->apArg;
  62258. assert( u.ai.apVal || u.ai.n==0 );
  62259. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  62260. pOut = &aMem[pOp->p3];
  62261. memAboutToChange(p, pOut);
  62262. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
  62263. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  62264. u.ai.pArg = &aMem[pOp->p2];
  62265. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  62266. assert( memIsValid(u.ai.pArg) );
  62267. u.ai.apVal[u.ai.i] = u.ai.pArg;
  62268. Deephemeralize(u.ai.pArg);
  62269. sqlite3VdbeMemStoreType(u.ai.pArg);
  62270. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  62271. }
  62272. assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  62273. if( pOp->p4type==P4_FUNCDEF ){
  62274. u.ai.ctx.pFunc = pOp->p4.pFunc;
  62275. u.ai.ctx.pVdbeFunc = 0;
  62276. }else{
  62277. u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
  62278. u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
  62279. }
  62280. u.ai.ctx.s.flags = MEM_Null;
  62281. u.ai.ctx.s.db = db;
  62282. u.ai.ctx.s.xDel = 0;
  62283. u.ai.ctx.s.zMalloc = 0;
  62284. /* The output cell may already have a buffer allocated. Move
  62285. ** the pointer to u.ai.ctx.s so in case the user-function can use
  62286. ** the already allocated buffer instead of allocating a new one.
  62287. */
  62288. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  62289. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  62290. u.ai.ctx.isError = 0;
  62291. if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  62292. assert( pOp>aOp );
  62293. assert( pOp[-1].p4type==P4_COLLSEQ );
  62294. assert( pOp[-1].opcode==OP_CollSeq );
  62295. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  62296. }
  62297. db->lastRowid = lastRowid;
  62298. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  62299. lastRowid = db->lastRowid;
  62300. /* If any auxiliary data functions have been called by this user function,
  62301. ** immediately call the destructor for any non-static values.
  62302. */
  62303. if( u.ai.ctx.pVdbeFunc ){
  62304. sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
  62305. pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
  62306. pOp->p4type = P4_VDBEFUNC;
  62307. }
  62308. if( db->mallocFailed ){
  62309. /* Even though a malloc() has failed, the implementation of the
  62310. ** user function may have called an sqlite3_result_XXX() function
  62311. ** to return a value. The following call releases any resources
  62312. ** associated with such a value.
  62313. */
  62314. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  62315. goto no_mem;
  62316. }
  62317. /* If the function returned an error, throw an exception */
  62318. if( u.ai.ctx.isError ){
  62319. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  62320. rc = u.ai.ctx.isError;
  62321. }
  62322. /* Copy the result of the function into register P3 */
  62323. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  62324. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  62325. if( sqlite3VdbeMemTooBig(pOut) ){
  62326. goto too_big;
  62327. }
  62328. #if 0
  62329. /* The app-defined function has done something that as caused this
  62330. ** statement to expire. (Perhaps the function called sqlite3_exec()
  62331. ** with a CREATE TABLE statement.)
  62332. */
  62333. if( p->expired ) rc = SQLITE_ABORT;
  62334. #endif
  62335. REGISTER_TRACE(pOp->p3, pOut);
  62336. UPDATE_MAX_BLOBSIZE(pOut);
  62337. break;
  62338. }
  62339. /* Opcode: BitAnd P1 P2 P3 * *
  62340. **
  62341. ** Take the bit-wise AND of the values in register P1 and P2 and
  62342. ** store the result in register P3.
  62343. ** If either input is NULL, the result is NULL.
  62344. */
  62345. /* Opcode: BitOr P1 P2 P3 * *
  62346. **
  62347. ** Take the bit-wise OR of the values in register P1 and P2 and
  62348. ** store the result in register P3.
  62349. ** If either input is NULL, the result is NULL.
  62350. */
  62351. /* Opcode: ShiftLeft P1 P2 P3 * *
  62352. **
  62353. ** Shift the integer value in register P2 to the left by the
  62354. ** number of bits specified by the integer in register P1.
  62355. ** Store the result in register P3.
  62356. ** If either input is NULL, the result is NULL.
  62357. */
  62358. /* Opcode: ShiftRight P1 P2 P3 * *
  62359. **
  62360. ** Shift the integer value in register P2 to the right by the
  62361. ** number of bits specified by the integer in register P1.
  62362. ** Store the result in register P3.
  62363. ** If either input is NULL, the result is NULL.
  62364. */
  62365. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  62366. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  62367. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  62368. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  62369. #if 0 /* local variables moved into u.aj */
  62370. i64 iA;
  62371. u64 uA;
  62372. i64 iB;
  62373. u8 op;
  62374. #endif /* local variables moved into u.aj */
  62375. pIn1 = &aMem[pOp->p1];
  62376. pIn2 = &aMem[pOp->p2];
  62377. pOut = &aMem[pOp->p3];
  62378. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  62379. sqlite3VdbeMemSetNull(pOut);
  62380. break;
  62381. }
  62382. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  62383. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  62384. u.aj.op = pOp->opcode;
  62385. if( u.aj.op==OP_BitAnd ){
  62386. u.aj.iA &= u.aj.iB;
  62387. }else if( u.aj.op==OP_BitOr ){
  62388. u.aj.iA |= u.aj.iB;
  62389. }else if( u.aj.iB!=0 ){
  62390. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  62391. /* If shifting by a negative amount, shift in the other direction */
  62392. if( u.aj.iB<0 ){
  62393. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  62394. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  62395. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  62396. }
  62397. if( u.aj.iB>=64 ){
  62398. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  62399. }else{
  62400. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  62401. if( u.aj.op==OP_ShiftLeft ){
  62402. u.aj.uA <<= u.aj.iB;
  62403. }else{
  62404. u.aj.uA >>= u.aj.iB;
  62405. /* Sign-extend on a right shift of a negative number */
  62406. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  62407. }
  62408. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  62409. }
  62410. }
  62411. pOut->u.i = u.aj.iA;
  62412. MemSetTypeFlag(pOut, MEM_Int);
  62413. break;
  62414. }
  62415. /* Opcode: AddImm P1 P2 * * *
  62416. **
  62417. ** Add the constant P2 to the value in register P1.
  62418. ** The result is always an integer.
  62419. **
  62420. ** To force any register to be an integer, just add 0.
  62421. */
  62422. case OP_AddImm: { /* in1 */
  62423. pIn1 = &aMem[pOp->p1];
  62424. memAboutToChange(p, pIn1);
  62425. sqlite3VdbeMemIntegerify(pIn1);
  62426. pIn1->u.i += pOp->p2;
  62427. break;
  62428. }
  62429. /* Opcode: MustBeInt P1 P2 * * *
  62430. **
  62431. ** Force the value in register P1 to be an integer. If the value
  62432. ** in P1 is not an integer and cannot be converted into an integer
  62433. ** without data loss, then jump immediately to P2, or if P2==0
  62434. ** raise an SQLITE_MISMATCH exception.
  62435. */
  62436. case OP_MustBeInt: { /* jump, in1 */
  62437. pIn1 = &aMem[pOp->p1];
  62438. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  62439. if( (pIn1->flags & MEM_Int)==0 ){
  62440. if( pOp->p2==0 ){
  62441. rc = SQLITE_MISMATCH;
  62442. goto abort_due_to_error;
  62443. }else{
  62444. pc = pOp->p2 - 1;
  62445. }
  62446. }else{
  62447. MemSetTypeFlag(pIn1, MEM_Int);
  62448. }
  62449. break;
  62450. }
  62451. #ifndef SQLITE_OMIT_FLOATING_POINT
  62452. /* Opcode: RealAffinity P1 * * * *
  62453. **
  62454. ** If register P1 holds an integer convert it to a real value.
  62455. **
  62456. ** This opcode is used when extracting information from a column that
  62457. ** has REAL affinity. Such column values may still be stored as
  62458. ** integers, for space efficiency, but after extraction we want them
  62459. ** to have only a real value.
  62460. */
  62461. case OP_RealAffinity: { /* in1 */
  62462. pIn1 = &aMem[pOp->p1];
  62463. if( pIn1->flags & MEM_Int ){
  62464. sqlite3VdbeMemRealify(pIn1);
  62465. }
  62466. break;
  62467. }
  62468. #endif
  62469. #ifndef SQLITE_OMIT_CAST
  62470. /* Opcode: ToText P1 * * * *
  62471. **
  62472. ** Force the value in register P1 to be text.
  62473. ** If the value is numeric, convert it to a string using the
  62474. ** equivalent of printf(). Blob values are unchanged and
  62475. ** are afterwards simply interpreted as text.
  62476. **
  62477. ** A NULL value is not changed by this routine. It remains NULL.
  62478. */
  62479. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  62480. pIn1 = &aMem[pOp->p1];
  62481. memAboutToChange(p, pIn1);
  62482. if( pIn1->flags & MEM_Null ) break;
  62483. assert( MEM_Str==(MEM_Blob>>3) );
  62484. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  62485. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  62486. rc = ExpandBlob(pIn1);
  62487. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  62488. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  62489. UPDATE_MAX_BLOBSIZE(pIn1);
  62490. break;
  62491. }
  62492. /* Opcode: ToBlob P1 * * * *
  62493. **
  62494. ** Force the value in register P1 to be a BLOB.
  62495. ** If the value is numeric, convert it to a string first.
  62496. ** Strings are simply reinterpreted as blobs with no change
  62497. ** to the underlying data.
  62498. **
  62499. ** A NULL value is not changed by this routine. It remains NULL.
  62500. */
  62501. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  62502. pIn1 = &aMem[pOp->p1];
  62503. if( pIn1->flags & MEM_Null ) break;
  62504. if( (pIn1->flags & MEM_Blob)==0 ){
  62505. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  62506. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  62507. MemSetTypeFlag(pIn1, MEM_Blob);
  62508. }else{
  62509. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  62510. }
  62511. UPDATE_MAX_BLOBSIZE(pIn1);
  62512. break;
  62513. }
  62514. /* Opcode: ToNumeric P1 * * * *
  62515. **
  62516. ** Force the value in register P1 to be numeric (either an
  62517. ** integer or a floating-point number.)
  62518. ** If the value is text or blob, try to convert it to an using the
  62519. ** equivalent of atoi() or atof() and store 0 if no such conversion
  62520. ** is possible.
  62521. **
  62522. ** A NULL value is not changed by this routine. It remains NULL.
  62523. */
  62524. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  62525. pIn1 = &aMem[pOp->p1];
  62526. sqlite3VdbeMemNumerify(pIn1);
  62527. break;
  62528. }
  62529. #endif /* SQLITE_OMIT_CAST */
  62530. /* Opcode: ToInt P1 * * * *
  62531. **
  62532. ** Force the value in register P1 to be an integer. If
  62533. ** The value is currently a real number, drop its fractional part.
  62534. ** If the value is text or blob, try to convert it to an integer using the
  62535. ** equivalent of atoi() and store 0 if no such conversion is possible.
  62536. **
  62537. ** A NULL value is not changed by this routine. It remains NULL.
  62538. */
  62539. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  62540. pIn1 = &aMem[pOp->p1];
  62541. if( (pIn1->flags & MEM_Null)==0 ){
  62542. sqlite3VdbeMemIntegerify(pIn1);
  62543. }
  62544. break;
  62545. }
  62546. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  62547. /* Opcode: ToReal P1 * * * *
  62548. **
  62549. ** Force the value in register P1 to be a floating point number.
  62550. ** If The value is currently an integer, convert it.
  62551. ** If the value is text or blob, try to convert it to an integer using the
  62552. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  62553. **
  62554. ** A NULL value is not changed by this routine. It remains NULL.
  62555. */
  62556. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  62557. pIn1 = &aMem[pOp->p1];
  62558. memAboutToChange(p, pIn1);
  62559. if( (pIn1->flags & MEM_Null)==0 ){
  62560. sqlite3VdbeMemRealify(pIn1);
  62561. }
  62562. break;
  62563. }
  62564. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  62565. /* Opcode: Lt P1 P2 P3 P4 P5
  62566. **
  62567. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  62568. ** jump to address P2.
  62569. **
  62570. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  62571. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  62572. ** bit is clear then fall through if either operand is NULL.
  62573. **
  62574. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  62575. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  62576. ** to coerce both inputs according to this affinity before the
  62577. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  62578. ** affinity is used. Note that the affinity conversions are stored
  62579. ** back into the input registers P1 and P3. So this opcode can cause
  62580. ** persistent changes to registers P1 and P3.
  62581. **
  62582. ** Once any conversions have taken place, and neither value is NULL,
  62583. ** the values are compared. If both values are blobs then memcmp() is
  62584. ** used to determine the results of the comparison. If both values
  62585. ** are text, then the appropriate collating function specified in
  62586. ** P4 is used to do the comparison. If P4 is not specified then
  62587. ** memcmp() is used to compare text string. If both values are
  62588. ** numeric, then a numeric comparison is used. If the two values
  62589. ** are of different types, then numbers are considered less than
  62590. ** strings and strings are considered less than blobs.
  62591. **
  62592. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  62593. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  62594. **
  62595. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  62596. ** equal to one another, provided that they do not have their MEM_Cleared
  62597. ** bit set.
  62598. */
  62599. /* Opcode: Ne P1 P2 P3 P4 P5
  62600. **
  62601. ** This works just like the Lt opcode except that the jump is taken if
  62602. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  62603. ** additional information.
  62604. **
  62605. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  62606. ** true or false and is never NULL. If both operands are NULL then the result
  62607. ** of comparison is false. If either operand is NULL then the result is true.
  62608. ** If neither operand is NULL the result is the same as it would be if
  62609. ** the SQLITE_NULLEQ flag were omitted from P5.
  62610. */
  62611. /* Opcode: Eq P1 P2 P3 P4 P5
  62612. **
  62613. ** This works just like the Lt opcode except that the jump is taken if
  62614. ** the operands in registers P1 and P3 are equal.
  62615. ** See the Lt opcode for additional information.
  62616. **
  62617. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  62618. ** true or false and is never NULL. If both operands are NULL then the result
  62619. ** of comparison is true. If either operand is NULL then the result is false.
  62620. ** If neither operand is NULL the result is the same as it would be if
  62621. ** the SQLITE_NULLEQ flag were omitted from P5.
  62622. */
  62623. /* Opcode: Le P1 P2 P3 P4 P5
  62624. **
  62625. ** This works just like the Lt opcode except that the jump is taken if
  62626. ** the content of register P3 is less than or equal to the content of
  62627. ** register P1. See the Lt opcode for additional information.
  62628. */
  62629. /* Opcode: Gt P1 P2 P3 P4 P5
  62630. **
  62631. ** This works just like the Lt opcode except that the jump is taken if
  62632. ** the content of register P3 is greater than the content of
  62633. ** register P1. See the Lt opcode for additional information.
  62634. */
  62635. /* Opcode: Ge P1 P2 P3 P4 P5
  62636. **
  62637. ** This works just like the Lt opcode except that the jump is taken if
  62638. ** the content of register P3 is greater than or equal to the content of
  62639. ** register P1. See the Lt opcode for additional information.
  62640. */
  62641. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  62642. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  62643. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  62644. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  62645. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  62646. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  62647. #if 0 /* local variables moved into u.ak */
  62648. int res; /* Result of the comparison of pIn1 against pIn3 */
  62649. char affinity; /* Affinity to use for comparison */
  62650. u16 flags1; /* Copy of initial value of pIn1->flags */
  62651. u16 flags3; /* Copy of initial value of pIn3->flags */
  62652. #endif /* local variables moved into u.ak */
  62653. pIn1 = &aMem[pOp->p1];
  62654. pIn3 = &aMem[pOp->p3];
  62655. u.ak.flags1 = pIn1->flags;
  62656. u.ak.flags3 = pIn3->flags;
  62657. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  62658. /* One or both operands are NULL */
  62659. if( pOp->p5 & SQLITE_NULLEQ ){
  62660. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  62661. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  62662. ** or not both operands are null.
  62663. */
  62664. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  62665. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  62666. if( (u.ak.flags1&MEM_Null)!=0
  62667. && (u.ak.flags3&MEM_Null)!=0
  62668. && (u.ak.flags3&MEM_Cleared)==0
  62669. ){
  62670. u.ak.res = 0; /* Results are equal */
  62671. }else{
  62672. u.ak.res = 1; /* Results are not equal */
  62673. }
  62674. }else{
  62675. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  62676. ** then the result is always NULL.
  62677. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  62678. */
  62679. if( pOp->p5 & SQLITE_STOREP2 ){
  62680. pOut = &aMem[pOp->p2];
  62681. MemSetTypeFlag(pOut, MEM_Null);
  62682. REGISTER_TRACE(pOp->p2, pOut);
  62683. }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
  62684. pc = pOp->p2-1;
  62685. }
  62686. break;
  62687. }
  62688. }else{
  62689. /* Neither operand is NULL. Do a comparison. */
  62690. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  62691. if( u.ak.affinity ){
  62692. applyAffinity(pIn1, u.ak.affinity, encoding);
  62693. applyAffinity(pIn3, u.ak.affinity, encoding);
  62694. if( db->mallocFailed ) goto no_mem;
  62695. }
  62696. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  62697. ExpandBlob(pIn1);
  62698. ExpandBlob(pIn3);
  62699. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  62700. }
  62701. switch( pOp->opcode ){
  62702. case OP_Eq: u.ak.res = u.ak.res==0; break;
  62703. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  62704. case OP_Lt: u.ak.res = u.ak.res<0; break;
  62705. case OP_Le: u.ak.res = u.ak.res<=0; break;
  62706. case OP_Gt: u.ak.res = u.ak.res>0; break;
  62707. default: u.ak.res = u.ak.res>=0; break;
  62708. }
  62709. if( pOp->p5 & SQLITE_STOREP2 ){
  62710. pOut = &aMem[pOp->p2];
  62711. memAboutToChange(p, pOut);
  62712. MemSetTypeFlag(pOut, MEM_Int);
  62713. pOut->u.i = u.ak.res;
  62714. REGISTER_TRACE(pOp->p2, pOut);
  62715. }else if( u.ak.res ){
  62716. pc = pOp->p2-1;
  62717. }
  62718. /* Undo any changes made by applyAffinity() to the input registers. */
  62719. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  62720. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  62721. break;
  62722. }
  62723. /* Opcode: Permutation * * * P4 *
  62724. **
  62725. ** Set the permutation used by the OP_Compare operator to be the array
  62726. ** of integers in P4.
  62727. **
  62728. ** The permutation is only valid until the next OP_Compare that has
  62729. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  62730. ** occur immediately prior to the OP_Compare.
  62731. */
  62732. case OP_Permutation: {
  62733. assert( pOp->p4type==P4_INTARRAY );
  62734. assert( pOp->p4.ai );
  62735. aPermute = pOp->p4.ai;
  62736. break;
  62737. }
  62738. /* Opcode: Compare P1 P2 P3 P4 P5
  62739. **
  62740. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  62741. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  62742. ** the comparison for use by the next OP_Jump instruct.
  62743. **
  62744. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  62745. ** determined by the most recent OP_Permutation operator. If the
  62746. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  62747. ** order.
  62748. **
  62749. ** P4 is a KeyInfo structure that defines collating sequences and sort
  62750. ** orders for the comparison. The permutation applies to registers
  62751. ** only. The KeyInfo elements are used sequentially.
  62752. **
  62753. ** The comparison is a sort comparison, so NULLs compare equal,
  62754. ** NULLs are less than numbers, numbers are less than strings,
  62755. ** and strings are less than blobs.
  62756. */
  62757. case OP_Compare: {
  62758. #if 0 /* local variables moved into u.al */
  62759. int n;
  62760. int i;
  62761. int p1;
  62762. int p2;
  62763. const KeyInfo *pKeyInfo;
  62764. int idx;
  62765. CollSeq *pColl; /* Collating sequence to use on this term */
  62766. int bRev; /* True for DESCENDING sort order */
  62767. #endif /* local variables moved into u.al */
  62768. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  62769. u.al.n = pOp->p3;
  62770. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  62771. assert( u.al.n>0 );
  62772. assert( u.al.pKeyInfo!=0 );
  62773. u.al.p1 = pOp->p1;
  62774. u.al.p2 = pOp->p2;
  62775. #if SQLITE_DEBUG
  62776. if( aPermute ){
  62777. int k, mx = 0;
  62778. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  62779. assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
  62780. assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
  62781. }else{
  62782. assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
  62783. assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
  62784. }
  62785. #endif /* SQLITE_DEBUG */
  62786. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  62787. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  62788. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  62789. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  62790. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  62791. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  62792. assert( u.al.i<u.al.pKeyInfo->nField );
  62793. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  62794. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  62795. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  62796. if( iCompare ){
  62797. if( u.al.bRev ) iCompare = -iCompare;
  62798. break;
  62799. }
  62800. }
  62801. aPermute = 0;
  62802. break;
  62803. }
  62804. /* Opcode: Jump P1 P2 P3 * *
  62805. **
  62806. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  62807. ** in the most recent OP_Compare instruction the P1 vector was less than
  62808. ** equal to, or greater than the P2 vector, respectively.
  62809. */
  62810. case OP_Jump: { /* jump */
  62811. if( iCompare<0 ){
  62812. pc = pOp->p1 - 1;
  62813. }else if( iCompare==0 ){
  62814. pc = pOp->p2 - 1;
  62815. }else{
  62816. pc = pOp->p3 - 1;
  62817. }
  62818. break;
  62819. }
  62820. /* Opcode: And P1 P2 P3 * *
  62821. **
  62822. ** Take the logical AND of the values in registers P1 and P2 and
  62823. ** write the result into register P3.
  62824. **
  62825. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  62826. ** the other input is NULL. A NULL and true or two NULLs give
  62827. ** a NULL output.
  62828. */
  62829. /* Opcode: Or P1 P2 P3 * *
  62830. **
  62831. ** Take the logical OR of the values in register P1 and P2 and
  62832. ** store the answer in register P3.
  62833. **
  62834. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  62835. ** even if the other input is NULL. A NULL and false or two NULLs
  62836. ** give a NULL output.
  62837. */
  62838. case OP_And: /* same as TK_AND, in1, in2, out3 */
  62839. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  62840. #if 0 /* local variables moved into u.am */
  62841. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  62842. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  62843. #endif /* local variables moved into u.am */
  62844. pIn1 = &aMem[pOp->p1];
  62845. if( pIn1->flags & MEM_Null ){
  62846. u.am.v1 = 2;
  62847. }else{
  62848. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  62849. }
  62850. pIn2 = &aMem[pOp->p2];
  62851. if( pIn2->flags & MEM_Null ){
  62852. u.am.v2 = 2;
  62853. }else{
  62854. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  62855. }
  62856. if( pOp->opcode==OP_And ){
  62857. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  62858. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  62859. }else{
  62860. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  62861. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  62862. }
  62863. pOut = &aMem[pOp->p3];
  62864. if( u.am.v1==2 ){
  62865. MemSetTypeFlag(pOut, MEM_Null);
  62866. }else{
  62867. pOut->u.i = u.am.v1;
  62868. MemSetTypeFlag(pOut, MEM_Int);
  62869. }
  62870. break;
  62871. }
  62872. /* Opcode: Not P1 P2 * * *
  62873. **
  62874. ** Interpret the value in register P1 as a boolean value. Store the
  62875. ** boolean complement in register P2. If the value in register P1 is
  62876. ** NULL, then a NULL is stored in P2.
  62877. */
  62878. case OP_Not: { /* same as TK_NOT, in1, out2 */
  62879. pIn1 = &aMem[pOp->p1];
  62880. pOut = &aMem[pOp->p2];
  62881. if( pIn1->flags & MEM_Null ){
  62882. sqlite3VdbeMemSetNull(pOut);
  62883. }else{
  62884. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  62885. }
  62886. break;
  62887. }
  62888. /* Opcode: BitNot P1 P2 * * *
  62889. **
  62890. ** Interpret the content of register P1 as an integer. Store the
  62891. ** ones-complement of the P1 value into register P2. If P1 holds
  62892. ** a NULL then store a NULL in P2.
  62893. */
  62894. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  62895. pIn1 = &aMem[pOp->p1];
  62896. pOut = &aMem[pOp->p2];
  62897. if( pIn1->flags & MEM_Null ){
  62898. sqlite3VdbeMemSetNull(pOut);
  62899. }else{
  62900. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  62901. }
  62902. break;
  62903. }
  62904. /* Opcode: Once P1 P2 * * *
  62905. **
  62906. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  62907. ** set the flag and fall through to the next instruction.
  62908. */
  62909. case OP_Once: { /* jump */
  62910. assert( pOp->p1<p->nOnceFlag );
  62911. if( p->aOnceFlag[pOp->p1] ){
  62912. pc = pOp->p2-1;
  62913. }else{
  62914. p->aOnceFlag[pOp->p1] = 1;
  62915. }
  62916. break;
  62917. }
  62918. /* Opcode: If P1 P2 P3 * *
  62919. **
  62920. ** Jump to P2 if the value in register P1 is true. The value
  62921. ** is considered true if it is numeric and non-zero. If the value
  62922. ** in P1 is NULL then take the jump if P3 is non-zero.
  62923. */
  62924. /* Opcode: IfNot P1 P2 P3 * *
  62925. **
  62926. ** Jump to P2 if the value in register P1 is False. The value
  62927. ** is considered false if it has a numeric value of zero. If the value
  62928. ** in P1 is NULL then take the jump if P3 is zero.
  62929. */
  62930. case OP_If: /* jump, in1 */
  62931. case OP_IfNot: { /* jump, in1 */
  62932. #if 0 /* local variables moved into u.an */
  62933. int c;
  62934. #endif /* local variables moved into u.an */
  62935. pIn1 = &aMem[pOp->p1];
  62936. if( pIn1->flags & MEM_Null ){
  62937. u.an.c = pOp->p3;
  62938. }else{
  62939. #ifdef SQLITE_OMIT_FLOATING_POINT
  62940. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  62941. #else
  62942. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  62943. #endif
  62944. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  62945. }
  62946. if( u.an.c ){
  62947. pc = pOp->p2-1;
  62948. }
  62949. break;
  62950. }
  62951. /* Opcode: IsNull P1 P2 * * *
  62952. **
  62953. ** Jump to P2 if the value in register P1 is NULL.
  62954. */
  62955. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  62956. pIn1 = &aMem[pOp->p1];
  62957. if( (pIn1->flags & MEM_Null)!=0 ){
  62958. pc = pOp->p2 - 1;
  62959. }
  62960. break;
  62961. }
  62962. /* Opcode: NotNull P1 P2 * * *
  62963. **
  62964. ** Jump to P2 if the value in register P1 is not NULL.
  62965. */
  62966. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  62967. pIn1 = &aMem[pOp->p1];
  62968. if( (pIn1->flags & MEM_Null)==0 ){
  62969. pc = pOp->p2 - 1;
  62970. }
  62971. break;
  62972. }
  62973. /* Opcode: Column P1 P2 P3 P4 P5
  62974. **
  62975. ** Interpret the data that cursor P1 points to as a structure built using
  62976. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  62977. ** information about the format of the data.) Extract the P2-th column
  62978. ** from this record. If there are less that (P2+1)
  62979. ** values in the record, extract a NULL.
  62980. **
  62981. ** The value extracted is stored in register P3.
  62982. **
  62983. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  62984. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  62985. ** the result.
  62986. **
  62987. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  62988. ** then the cache of the cursor is reset prior to extracting the column.
  62989. ** The first OP_Column against a pseudo-table after the value of the content
  62990. ** register has changed should have this bit set.
  62991. **
  62992. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  62993. ** the result is guaranteed to only be used as the argument of a length()
  62994. ** or typeof() function, respectively. The loading of large blobs can be
  62995. ** skipped for length() and all content loading can be skipped for typeof().
  62996. */
  62997. case OP_Column: {
  62998. #if 0 /* local variables moved into u.ao */
  62999. u32 payloadSize; /* Number of bytes in the record */
  63000. i64 payloadSize64; /* Number of bytes in the record */
  63001. int p1; /* P1 value of the opcode */
  63002. int p2; /* column number to retrieve */
  63003. VdbeCursor *pC; /* The VDBE cursor */
  63004. char *zRec; /* Pointer to complete record-data */
  63005. BtCursor *pCrsr; /* The BTree cursor */
  63006. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  63007. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  63008. int nField; /* number of fields in the record */
  63009. int len; /* The length of the serialized data for the column */
  63010. int i; /* Loop counter */
  63011. char *zData; /* Part of the record being decoded */
  63012. Mem *pDest; /* Where to write the extracted value */
  63013. Mem sMem; /* For storing the record being decoded */
  63014. u8 *zIdx; /* Index into header */
  63015. u8 *zEndHdr; /* Pointer to first byte after the header */
  63016. u32 offset; /* Offset into the data */
  63017. u32 szField; /* Number of bytes in the content of a field */
  63018. int szHdr; /* Size of the header size field at start of record */
  63019. int avail; /* Number of bytes of available data */
  63020. u32 t; /* A type code from the record header */
  63021. Mem *pReg; /* PseudoTable input register */
  63022. #endif /* local variables moved into u.ao */
  63023. u.ao.p1 = pOp->p1;
  63024. u.ao.p2 = pOp->p2;
  63025. u.ao.pC = 0;
  63026. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  63027. assert( u.ao.p1<p->nCursor );
  63028. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  63029. u.ao.pDest = &aMem[pOp->p3];
  63030. memAboutToChange(p, u.ao.pDest);
  63031. u.ao.zRec = 0;
  63032. /* This block sets the variable u.ao.payloadSize to be the total number of
  63033. ** bytes in the record.
  63034. **
  63035. ** u.ao.zRec is set to be the complete text of the record if it is available.
  63036. ** The complete record text is always available for pseudo-tables
  63037. ** If the record is stored in a cursor, the complete record text
  63038. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  63039. ** If the data is unavailable, u.ao.zRec is set to NULL.
  63040. **
  63041. ** We also compute the number of columns in the record. For cursors,
  63042. ** the number of columns is stored in the VdbeCursor.nField element.
  63043. */
  63044. u.ao.pC = p->apCsr[u.ao.p1];
  63045. assert( u.ao.pC!=0 );
  63046. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63047. assert( u.ao.pC->pVtabCursor==0 );
  63048. #endif
  63049. u.ao.pCrsr = u.ao.pC->pCursor;
  63050. if( u.ao.pCrsr!=0 ){
  63051. /* The record is stored in a B-Tree */
  63052. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  63053. if( rc ) goto abort_due_to_error;
  63054. if( u.ao.pC->nullRow ){
  63055. u.ao.payloadSize = 0;
  63056. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  63057. u.ao.payloadSize = u.ao.pC->payloadSize;
  63058. u.ao.zRec = (char*)u.ao.pC->aRow;
  63059. }else if( u.ao.pC->isIndex ){
  63060. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  63061. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  63062. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  63063. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  63064. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  63065. ** larger than 32 bits. */
  63066. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  63067. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  63068. }else{
  63069. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  63070. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  63071. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  63072. }
  63073. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  63074. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  63075. if( u.ao.pC->multiPseudo ){
  63076. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  63077. Deephemeralize(u.ao.pDest);
  63078. goto op_column_out;
  63079. }
  63080. assert( u.ao.pReg->flags & MEM_Blob );
  63081. assert( memIsValid(u.ao.pReg) );
  63082. u.ao.payloadSize = u.ao.pReg->n;
  63083. u.ao.zRec = u.ao.pReg->z;
  63084. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  63085. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  63086. }else{
  63087. /* Consider the row to be NULL */
  63088. u.ao.payloadSize = 0;
  63089. }
  63090. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  63091. ** nullRow or because of a corrupt database. */
  63092. if( u.ao.payloadSize==0 ){
  63093. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  63094. goto op_column_out;
  63095. }
  63096. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  63097. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63098. goto too_big;
  63099. }
  63100. u.ao.nField = u.ao.pC->nField;
  63101. assert( u.ao.p2<u.ao.nField );
  63102. /* Read and parse the table header. Store the results of the parse
  63103. ** into the record header cache fields of the cursor.
  63104. */
  63105. u.ao.aType = u.ao.pC->aType;
  63106. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  63107. u.ao.aOffset = u.ao.pC->aOffset;
  63108. }else{
  63109. assert(u.ao.aType);
  63110. u.ao.avail = 0;
  63111. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  63112. u.ao.pC->payloadSize = u.ao.payloadSize;
  63113. u.ao.pC->cacheStatus = p->cacheCtr;
  63114. /* Figure out how many bytes are in the header */
  63115. if( u.ao.zRec ){
  63116. u.ao.zData = u.ao.zRec;
  63117. }else{
  63118. if( u.ao.pC->isIndex ){
  63119. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  63120. }else{
  63121. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  63122. }
  63123. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  63124. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  63125. ** having to make additional calls to fetch the content portion of
  63126. ** the record.
  63127. */
  63128. assert( u.ao.avail>=0 );
  63129. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  63130. u.ao.zRec = u.ao.zData;
  63131. u.ao.pC->aRow = (u8*)u.ao.zData;
  63132. }else{
  63133. u.ao.pC->aRow = 0;
  63134. }
  63135. }
  63136. /* The following assert is true in all cases except when
  63137. ** the database file has been corrupted externally.
  63138. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  63139. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  63140. /* Make sure a corrupt database has not given us an oversize header.
  63141. ** Do this now to avoid an oversize memory allocation.
  63142. **
  63143. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  63144. ** types use so much data space that there can only be 4096 and 32 of
  63145. ** them, respectively. So the maximum header length results from a
  63146. ** 3-byte type for each of the maximum of 32768 columns plus three
  63147. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  63148. */
  63149. if( u.ao.offset > 98307 ){
  63150. rc = SQLITE_CORRUPT_BKPT;
  63151. goto op_column_out;
  63152. }
  63153. /* Compute in u.ao.len the number of bytes of data we need to read in order
  63154. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  63155. ** u.ao.nField might be significantly less than the true number of columns
  63156. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  63157. ** We want to minimize u.ao.len in order to limit the size of the memory
  63158. ** allocation, especially if a corrupt database file has caused u.ao.offset
  63159. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  63160. ** still exceed Robson memory allocation limits on some configurations.
  63161. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  63162. ** will likely be much smaller since u.ao.nField will likely be less than
  63163. ** 20 or so. This insures that Robson memory allocation limits are
  63164. ** not exceeded even for corrupt database files.
  63165. */
  63166. u.ao.len = u.ao.nField*5 + 3;
  63167. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  63168. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  63169. ** record header in most cases. But they will fail to get the complete
  63170. ** record header if the record header does not fit on a single page
  63171. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  63172. ** acquire the complete header text.
  63173. */
  63174. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  63175. u.ao.sMem.flags = 0;
  63176. u.ao.sMem.db = 0;
  63177. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  63178. if( rc!=SQLITE_OK ){
  63179. goto op_column_out;
  63180. }
  63181. u.ao.zData = u.ao.sMem.z;
  63182. }
  63183. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  63184. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  63185. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  63186. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  63187. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  63188. ** of the record to the start of the data for the u.ao.i-th column
  63189. */
  63190. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  63191. if( u.ao.zIdx<u.ao.zEndHdr ){
  63192. u.ao.aOffset[u.ao.i] = u.ao.offset;
  63193. if( u.ao.zIdx[0]<0x80 ){
  63194. u.ao.t = u.ao.zIdx[0];
  63195. u.ao.zIdx++;
  63196. }else{
  63197. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  63198. }
  63199. u.ao.aType[u.ao.i] = u.ao.t;
  63200. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  63201. u.ao.offset += u.ao.szField;
  63202. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  63203. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  63204. break;
  63205. }
  63206. }else{
  63207. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  63208. ** record than SetNumColumns indicated there are columns in the
  63209. ** table. Set the u.ao.offset for any extra columns not present in
  63210. ** the record to 0. This tells code below to store the default value
  63211. ** for the column instead of deserializing a value from the record.
  63212. */
  63213. u.ao.aOffset[u.ao.i] = 0;
  63214. }
  63215. }
  63216. sqlite3VdbeMemRelease(&u.ao.sMem);
  63217. u.ao.sMem.flags = MEM_Null;
  63218. /* If we have read more header data than was contained in the header,
  63219. ** or if the end of the last field appears to be past the end of the
  63220. ** record, or if the end of the last field appears to be before the end
  63221. ** of the record (when all fields present), then we must be dealing
  63222. ** with a corrupt database.
  63223. */
  63224. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  63225. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  63226. rc = SQLITE_CORRUPT_BKPT;
  63227. goto op_column_out;
  63228. }
  63229. }
  63230. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  63231. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  63232. ** then there are not enough fields in the record to satisfy the
  63233. ** request. In this case, set the value NULL or to P4 if P4 is
  63234. ** a pointer to a Mem object.
  63235. */
  63236. if( u.ao.aOffset[u.ao.p2] ){
  63237. assert( rc==SQLITE_OK );
  63238. if( u.ao.zRec ){
  63239. /* This is the common case where the whole row fits on a single page */
  63240. VdbeMemRelease(u.ao.pDest);
  63241. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  63242. }else{
  63243. /* This branch happens only when the row overflows onto multiple pages */
  63244. u.ao.t = u.ao.aType[u.ao.p2];
  63245. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  63246. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  63247. ){
  63248. /* Content is irrelevant for the typeof() function and for
  63249. ** the length(X) function if X is a blob. So we might as well use
  63250. ** bogus content rather than reading content from disk. NULL works
  63251. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  63252. ** will work for everything else. */
  63253. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  63254. }else{
  63255. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  63256. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  63257. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  63258. &u.ao.sMem);
  63259. if( rc!=SQLITE_OK ){
  63260. goto op_column_out;
  63261. }
  63262. u.ao.zData = u.ao.sMem.z;
  63263. }
  63264. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  63265. }
  63266. u.ao.pDest->enc = encoding;
  63267. }else{
  63268. if( pOp->p4type==P4_MEM ){
  63269. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  63270. }else{
  63271. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  63272. }
  63273. }
  63274. /* If we dynamically allocated space to hold the data (in the
  63275. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  63276. ** dynamically allocated space over to the u.ao.pDest structure.
  63277. ** This prevents a memory copy.
  63278. */
  63279. if( u.ao.sMem.zMalloc ){
  63280. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  63281. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  63282. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  63283. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  63284. u.ao.pDest->flags |= MEM_Term;
  63285. u.ao.pDest->z = u.ao.sMem.z;
  63286. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  63287. }
  63288. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  63289. op_column_out:
  63290. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  63291. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  63292. break;
  63293. }
  63294. /* Opcode: Affinity P1 P2 * P4 *
  63295. **
  63296. ** Apply affinities to a range of P2 registers starting with P1.
  63297. **
  63298. ** P4 is a string that is P2 characters long. The nth character of the
  63299. ** string indicates the column affinity that should be used for the nth
  63300. ** memory cell in the range.
  63301. */
  63302. case OP_Affinity: {
  63303. #if 0 /* local variables moved into u.ap */
  63304. const char *zAffinity; /* The affinity to be applied */
  63305. char cAff; /* A single character of affinity */
  63306. #endif /* local variables moved into u.ap */
  63307. u.ap.zAffinity = pOp->p4.z;
  63308. assert( u.ap.zAffinity!=0 );
  63309. assert( u.ap.zAffinity[pOp->p2]==0 );
  63310. pIn1 = &aMem[pOp->p1];
  63311. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  63312. assert( pIn1 <= &p->aMem[p->nMem] );
  63313. assert( memIsValid(pIn1) );
  63314. ExpandBlob(pIn1);
  63315. applyAffinity(pIn1, u.ap.cAff, encoding);
  63316. pIn1++;
  63317. }
  63318. break;
  63319. }
  63320. /* Opcode: MakeRecord P1 P2 P3 P4 *
  63321. **
  63322. ** Convert P2 registers beginning with P1 into the [record format]
  63323. ** use as a data record in a database table or as a key
  63324. ** in an index. The OP_Column opcode can decode the record later.
  63325. **
  63326. ** P4 may be a string that is P2 characters long. The nth character of the
  63327. ** string indicates the column affinity that should be used for the nth
  63328. ** field of the index key.
  63329. **
  63330. ** The mapping from character to affinity is given by the SQLITE_AFF_
  63331. ** macros defined in sqliteInt.h.
  63332. **
  63333. ** If P4 is NULL then all index fields have the affinity NONE.
  63334. */
  63335. case OP_MakeRecord: {
  63336. #if 0 /* local variables moved into u.aq */
  63337. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  63338. Mem *pRec; /* The new record */
  63339. u64 nData; /* Number of bytes of data space */
  63340. int nHdr; /* Number of bytes of header space */
  63341. i64 nByte; /* Data space required for this record */
  63342. int nZero; /* Number of zero bytes at the end of the record */
  63343. int nVarint; /* Number of bytes in a varint */
  63344. u32 serial_type; /* Type field */
  63345. Mem *pData0; /* First field to be combined into the record */
  63346. Mem *pLast; /* Last field of the record */
  63347. int nField; /* Number of fields in the record */
  63348. char *zAffinity; /* The affinity string for the record */
  63349. int file_format; /* File format to use for encoding */
  63350. int i; /* Space used in zNewRecord[] */
  63351. int len; /* Length of a field */
  63352. #endif /* local variables moved into u.aq */
  63353. /* Assuming the record contains N fields, the record format looks
  63354. ** like this:
  63355. **
  63356. ** ------------------------------------------------------------------------
  63357. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  63358. ** ------------------------------------------------------------------------
  63359. **
  63360. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  63361. ** and so froth.
  63362. **
  63363. ** Each type field is a varint representing the serial type of the
  63364. ** corresponding data element (see sqlite3VdbeSerialType()). The
  63365. ** hdr-size field is also a varint which is the offset from the beginning
  63366. ** of the record to data0.
  63367. */
  63368. u.aq.nData = 0; /* Number of bytes of data space */
  63369. u.aq.nHdr = 0; /* Number of bytes of header space */
  63370. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  63371. u.aq.nField = pOp->p1;
  63372. u.aq.zAffinity = pOp->p4.z;
  63373. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
  63374. u.aq.pData0 = &aMem[u.aq.nField];
  63375. u.aq.nField = pOp->p2;
  63376. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  63377. u.aq.file_format = p->minWriteFileFormat;
  63378. /* Identify the output register */
  63379. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  63380. pOut = &aMem[pOp->p3];
  63381. memAboutToChange(p, pOut);
  63382. /* Loop through the elements that will make up the record to figure
  63383. ** out how much space is required for the new record.
  63384. */
  63385. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  63386. assert( memIsValid(u.aq.pRec) );
  63387. if( u.aq.zAffinity ){
  63388. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  63389. }
  63390. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  63391. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  63392. }
  63393. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  63394. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  63395. u.aq.nData += u.aq.len;
  63396. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  63397. if( u.aq.pRec->flags & MEM_Zero ){
  63398. /* Only pure zero-filled BLOBs can be input to this Opcode.
  63399. ** We do not allow blobs with a prefix and a zero-filled tail. */
  63400. u.aq.nZero += u.aq.pRec->u.nZero;
  63401. }else if( u.aq.len ){
  63402. u.aq.nZero = 0;
  63403. }
  63404. }
  63405. /* Add the initial header varint and total the size */
  63406. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  63407. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  63408. u.aq.nHdr++;
  63409. }
  63410. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  63411. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63412. goto too_big;
  63413. }
  63414. /* Make sure the output register has a buffer large enough to store
  63415. ** the new record. The output register (pOp->p3) is not allowed to
  63416. ** be one of the input registers (because the following call to
  63417. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  63418. */
  63419. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  63420. goto no_mem;
  63421. }
  63422. u.aq.zNewRecord = (u8 *)pOut->z;
  63423. /* Write the record */
  63424. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  63425. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  63426. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  63427. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  63428. }
  63429. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  63430. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  63431. }
  63432. assert( u.aq.i==u.aq.nByte );
  63433. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  63434. pOut->n = (int)u.aq.nByte;
  63435. pOut->flags = MEM_Blob | MEM_Dyn;
  63436. pOut->xDel = 0;
  63437. if( u.aq.nZero ){
  63438. pOut->u.nZero = u.aq.nZero;
  63439. pOut->flags |= MEM_Zero;
  63440. }
  63441. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  63442. REGISTER_TRACE(pOp->p3, pOut);
  63443. UPDATE_MAX_BLOBSIZE(pOut);
  63444. break;
  63445. }
  63446. /* Opcode: Count P1 P2 * * *
  63447. **
  63448. ** Store the number of entries (an integer value) in the table or index
  63449. ** opened by cursor P1 in register P2
  63450. */
  63451. #ifndef SQLITE_OMIT_BTREECOUNT
  63452. case OP_Count: { /* out2-prerelease */
  63453. #if 0 /* local variables moved into u.ar */
  63454. i64 nEntry;
  63455. BtCursor *pCrsr;
  63456. #endif /* local variables moved into u.ar */
  63457. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  63458. if( ALWAYS(u.ar.pCrsr) ){
  63459. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  63460. }else{
  63461. u.ar.nEntry = 0;
  63462. }
  63463. pOut->u.i = u.ar.nEntry;
  63464. break;
  63465. }
  63466. #endif
  63467. /* Opcode: Savepoint P1 * * P4 *
  63468. **
  63469. ** Open, release or rollback the savepoint named by parameter P4, depending
  63470. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  63471. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  63472. */
  63473. case OP_Savepoint: {
  63474. #if 0 /* local variables moved into u.as */
  63475. int p1; /* Value of P1 operand */
  63476. char *zName; /* Name of savepoint */
  63477. int nName;
  63478. Savepoint *pNew;
  63479. Savepoint *pSavepoint;
  63480. Savepoint *pTmp;
  63481. int iSavepoint;
  63482. int ii;
  63483. #endif /* local variables moved into u.as */
  63484. u.as.p1 = pOp->p1;
  63485. u.as.zName = pOp->p4.z;
  63486. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  63487. ** transaction, then there cannot be any savepoints.
  63488. */
  63489. assert( db->pSavepoint==0 || db->autoCommit==0 );
  63490. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  63491. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  63492. assert( checkSavepointCount(db) );
  63493. if( u.as.p1==SAVEPOINT_BEGIN ){
  63494. if( db->writeVdbeCnt>0 ){
  63495. /* A new savepoint cannot be created if there are active write
  63496. ** statements (i.e. open read/write incremental blob handles).
  63497. */
  63498. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  63499. "SQL statements in progress");
  63500. rc = SQLITE_BUSY;
  63501. }else{
  63502. u.as.nName = sqlite3Strlen30(u.as.zName);
  63503. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63504. /* This call is Ok even if this savepoint is actually a transaction
  63505. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  63506. ** If this is a transaction savepoint being opened, it is guaranteed
  63507. ** that the db->aVTrans[] array is empty. */
  63508. assert( db->autoCommit==0 || db->nVTrans==0 );
  63509. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  63510. db->nStatement+db->nSavepoint);
  63511. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  63512. #endif
  63513. /* Create a new savepoint structure. */
  63514. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  63515. if( u.as.pNew ){
  63516. u.as.pNew->zName = (char *)&u.as.pNew[1];
  63517. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  63518. /* If there is no open transaction, then mark this as a special
  63519. ** "transaction savepoint". */
  63520. if( db->autoCommit ){
  63521. db->autoCommit = 0;
  63522. db->isTransactionSavepoint = 1;
  63523. }else{
  63524. db->nSavepoint++;
  63525. }
  63526. /* Link the new savepoint into the database handle's list. */
  63527. u.as.pNew->pNext = db->pSavepoint;
  63528. db->pSavepoint = u.as.pNew;
  63529. u.as.pNew->nDeferredCons = db->nDeferredCons;
  63530. }
  63531. }
  63532. }else{
  63533. u.as.iSavepoint = 0;
  63534. /* Find the named savepoint. If there is no such savepoint, then an
  63535. ** an error is returned to the user. */
  63536. for(
  63537. u.as.pSavepoint = db->pSavepoint;
  63538. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  63539. u.as.pSavepoint = u.as.pSavepoint->pNext
  63540. ){
  63541. u.as.iSavepoint++;
  63542. }
  63543. if( !u.as.pSavepoint ){
  63544. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  63545. rc = SQLITE_ERROR;
  63546. }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
  63547. /* It is not possible to release (commit) a savepoint if there are
  63548. ** active write statements.
  63549. */
  63550. sqlite3SetString(&p->zErrMsg, db,
  63551. "cannot release savepoint - SQL statements in progress"
  63552. );
  63553. rc = SQLITE_BUSY;
  63554. }else{
  63555. /* Determine whether or not this is a transaction savepoint. If so,
  63556. ** and this is a RELEASE command, then the current transaction
  63557. ** is committed.
  63558. */
  63559. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  63560. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  63561. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  63562. goto vdbe_return;
  63563. }
  63564. db->autoCommit = 1;
  63565. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  63566. p->pc = pc;
  63567. db->autoCommit = 0;
  63568. p->rc = rc = SQLITE_BUSY;
  63569. goto vdbe_return;
  63570. }
  63571. db->isTransactionSavepoint = 0;
  63572. rc = p->rc;
  63573. }else{
  63574. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  63575. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  63576. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  63577. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  63578. }
  63579. }
  63580. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  63581. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  63582. if( rc!=SQLITE_OK ){
  63583. goto abort_due_to_error;
  63584. }
  63585. }
  63586. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  63587. sqlite3ExpirePreparedStatements(db);
  63588. sqlite3ResetAllSchemasOfConnection(db);
  63589. db->flags = (db->flags | SQLITE_InternChanges);
  63590. }
  63591. }
  63592. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  63593. ** savepoints nested inside of the savepoint being operated on. */
  63594. while( db->pSavepoint!=u.as.pSavepoint ){
  63595. u.as.pTmp = db->pSavepoint;
  63596. db->pSavepoint = u.as.pTmp->pNext;
  63597. sqlite3DbFree(db, u.as.pTmp);
  63598. db->nSavepoint--;
  63599. }
  63600. /* If it is a RELEASE, then destroy the savepoint being operated on
  63601. ** too. If it is a ROLLBACK TO, then set the number of deferred
  63602. ** constraint violations present in the database to the value stored
  63603. ** when the savepoint was created. */
  63604. if( u.as.p1==SAVEPOINT_RELEASE ){
  63605. assert( u.as.pSavepoint==db->pSavepoint );
  63606. db->pSavepoint = u.as.pSavepoint->pNext;
  63607. sqlite3DbFree(db, u.as.pSavepoint);
  63608. if( !isTransaction ){
  63609. db->nSavepoint--;
  63610. }
  63611. }else{
  63612. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  63613. }
  63614. if( !isTransaction ){
  63615. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  63616. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  63617. }
  63618. }
  63619. }
  63620. break;
  63621. }
  63622. /* Opcode: AutoCommit P1 P2 * * *
  63623. **
  63624. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  63625. ** back any currently active btree transactions. If there are any active
  63626. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  63627. ** there are active writing VMs or active VMs that use shared cache.
  63628. **
  63629. ** This instruction causes the VM to halt.
  63630. */
  63631. case OP_AutoCommit: {
  63632. #if 0 /* local variables moved into u.at */
  63633. int desiredAutoCommit;
  63634. int iRollback;
  63635. int turnOnAC;
  63636. #endif /* local variables moved into u.at */
  63637. u.at.desiredAutoCommit = pOp->p1;
  63638. u.at.iRollback = pOp->p2;
  63639. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  63640. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  63641. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  63642. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  63643. #if 0
  63644. if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
  63645. /* If this instruction implements a ROLLBACK and other VMs are
  63646. ** still running, and a transaction is active, return an error indicating
  63647. ** that the other VMs must complete first.
  63648. */
  63649. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  63650. "SQL statements in progress");
  63651. rc = SQLITE_BUSY;
  63652. }else
  63653. #endif
  63654. if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
  63655. /* If this instruction implements a COMMIT and other VMs are writing
  63656. ** return an error indicating that the other VMs must complete first.
  63657. */
  63658. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  63659. "SQL statements in progress");
  63660. rc = SQLITE_BUSY;
  63661. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  63662. if( u.at.iRollback ){
  63663. assert( u.at.desiredAutoCommit==1 );
  63664. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  63665. db->autoCommit = 1;
  63666. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  63667. goto vdbe_return;
  63668. }else{
  63669. db->autoCommit = (u8)u.at.desiredAutoCommit;
  63670. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  63671. p->pc = pc;
  63672. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  63673. p->rc = rc = SQLITE_BUSY;
  63674. goto vdbe_return;
  63675. }
  63676. }
  63677. assert( db->nStatement==0 );
  63678. sqlite3CloseSavepoints(db);
  63679. if( p->rc==SQLITE_OK ){
  63680. rc = SQLITE_DONE;
  63681. }else{
  63682. rc = SQLITE_ERROR;
  63683. }
  63684. goto vdbe_return;
  63685. }else{
  63686. sqlite3SetString(&p->zErrMsg, db,
  63687. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  63688. (u.at.iRollback)?"cannot rollback - no transaction is active":
  63689. "cannot commit - no transaction is active"));
  63690. rc = SQLITE_ERROR;
  63691. }
  63692. break;
  63693. }
  63694. /* Opcode: Transaction P1 P2 * * *
  63695. **
  63696. ** Begin a transaction. The transaction ends when a Commit or Rollback
  63697. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  63698. ** transaction might also be rolled back if an error is encountered.
  63699. **
  63700. ** P1 is the index of the database file on which the transaction is
  63701. ** started. Index 0 is the main database file and index 1 is the
  63702. ** file used for temporary tables. Indices of 2 or more are used for
  63703. ** attached databases.
  63704. **
  63705. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  63706. ** obtained on the database file when a write-transaction is started. No
  63707. ** other process can start another write transaction while this transaction is
  63708. ** underway. Starting a write transaction also creates a rollback journal. A
  63709. ** write transaction must be started before any changes can be made to the
  63710. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  63711. ** on the file.
  63712. **
  63713. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  63714. ** true (this flag is set if the Vdbe may modify more than one row and may
  63715. ** throw an ABORT exception), a statement transaction may also be opened.
  63716. ** More specifically, a statement transaction is opened iff the database
  63717. ** connection is currently not in autocommit mode, or if there are other
  63718. ** active statements. A statement transaction allows the changes made by this
  63719. ** VDBE to be rolled back after an error without having to roll back the
  63720. ** entire transaction. If no error is encountered, the statement transaction
  63721. ** will automatically commit when the VDBE halts.
  63722. **
  63723. ** If P2 is zero, then a read-lock is obtained on the database file.
  63724. */
  63725. case OP_Transaction: {
  63726. #if 0 /* local variables moved into u.au */
  63727. Btree *pBt;
  63728. #endif /* local variables moved into u.au */
  63729. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  63730. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  63731. u.au.pBt = db->aDb[pOp->p1].pBt;
  63732. if( u.au.pBt ){
  63733. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  63734. if( rc==SQLITE_BUSY ){
  63735. p->pc = pc;
  63736. p->rc = rc = SQLITE_BUSY;
  63737. goto vdbe_return;
  63738. }
  63739. if( rc!=SQLITE_OK ){
  63740. goto abort_due_to_error;
  63741. }
  63742. if( pOp->p2 && p->usesStmtJournal
  63743. && (db->autoCommit==0 || db->activeVdbeCnt>1)
  63744. ){
  63745. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  63746. if( p->iStatement==0 ){
  63747. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  63748. db->nStatement++;
  63749. p->iStatement = db->nSavepoint + db->nStatement;
  63750. }
  63751. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  63752. if( rc==SQLITE_OK ){
  63753. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  63754. }
  63755. /* Store the current value of the database handles deferred constraint
  63756. ** counter. If the statement transaction needs to be rolled back,
  63757. ** the value of this counter needs to be restored too. */
  63758. p->nStmtDefCons = db->nDeferredCons;
  63759. }
  63760. }
  63761. break;
  63762. }
  63763. /* Opcode: ReadCookie P1 P2 P3 * *
  63764. **
  63765. ** Read cookie number P3 from database P1 and write it into register P2.
  63766. ** P3==1 is the schema version. P3==2 is the database format.
  63767. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  63768. ** the main database file and P1==1 is the database file used to store
  63769. ** temporary tables.
  63770. **
  63771. ** There must be a read-lock on the database (either a transaction
  63772. ** must be started or there must be an open cursor) before
  63773. ** executing this instruction.
  63774. */
  63775. case OP_ReadCookie: { /* out2-prerelease */
  63776. #if 0 /* local variables moved into u.av */
  63777. int iMeta;
  63778. int iDb;
  63779. int iCookie;
  63780. #endif /* local variables moved into u.av */
  63781. u.av.iDb = pOp->p1;
  63782. u.av.iCookie = pOp->p3;
  63783. assert( pOp->p3<SQLITE_N_BTREE_META );
  63784. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  63785. assert( db->aDb[u.av.iDb].pBt!=0 );
  63786. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  63787. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  63788. pOut->u.i = u.av.iMeta;
  63789. break;
  63790. }
  63791. /* Opcode: SetCookie P1 P2 P3 * *
  63792. **
  63793. ** Write the content of register P3 (interpreted as an integer)
  63794. ** into cookie number P2 of database P1. P2==1 is the schema version.
  63795. ** P2==2 is the database format. P2==3 is the recommended pager cache
  63796. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  63797. ** database file used to store temporary tables.
  63798. **
  63799. ** A transaction must be started before executing this opcode.
  63800. */
  63801. case OP_SetCookie: { /* in3 */
  63802. #if 0 /* local variables moved into u.aw */
  63803. Db *pDb;
  63804. #endif /* local variables moved into u.aw */
  63805. assert( pOp->p2<SQLITE_N_BTREE_META );
  63806. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  63807. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  63808. u.aw.pDb = &db->aDb[pOp->p1];
  63809. assert( u.aw.pDb->pBt!=0 );
  63810. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  63811. pIn3 = &aMem[pOp->p3];
  63812. sqlite3VdbeMemIntegerify(pIn3);
  63813. /* See note about index shifting on OP_ReadCookie */
  63814. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  63815. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  63816. /* When the schema cookie changes, record the new cookie internally */
  63817. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  63818. db->flags |= SQLITE_InternChanges;
  63819. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  63820. /* Record changes in the file format */
  63821. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  63822. }
  63823. if( pOp->p1==1 ){
  63824. /* Invalidate all prepared statements whenever the TEMP database
  63825. ** schema is changed. Ticket #1644 */
  63826. sqlite3ExpirePreparedStatements(db);
  63827. p->expired = 0;
  63828. }
  63829. break;
  63830. }
  63831. /* Opcode: VerifyCookie P1 P2 P3 * *
  63832. **
  63833. ** Check the value of global database parameter number 0 (the
  63834. ** schema version) and make sure it is equal to P2 and that the
  63835. ** generation counter on the local schema parse equals P3.
  63836. **
  63837. ** P1 is the database number which is 0 for the main database file
  63838. ** and 1 for the file holding temporary tables and some higher number
  63839. ** for auxiliary databases.
  63840. **
  63841. ** The cookie changes its value whenever the database schema changes.
  63842. ** This operation is used to detect when that the cookie has changed
  63843. ** and that the current process needs to reread the schema.
  63844. **
  63845. ** Either a transaction needs to have been started or an OP_Open needs
  63846. ** to be executed (to establish a read lock) before this opcode is
  63847. ** invoked.
  63848. */
  63849. case OP_VerifyCookie: {
  63850. #if 0 /* local variables moved into u.ax */
  63851. int iMeta;
  63852. int iGen;
  63853. Btree *pBt;
  63854. #endif /* local variables moved into u.ax */
  63855. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  63856. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  63857. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  63858. u.ax.pBt = db->aDb[pOp->p1].pBt;
  63859. if( u.ax.pBt ){
  63860. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  63861. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  63862. }else{
  63863. u.ax.iGen = u.ax.iMeta = 0;
  63864. }
  63865. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  63866. sqlite3DbFree(db, p->zErrMsg);
  63867. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  63868. /* If the schema-cookie from the database file matches the cookie
  63869. ** stored with the in-memory representation of the schema, do
  63870. ** not reload the schema from the database file.
  63871. **
  63872. ** If virtual-tables are in use, this is not just an optimization.
  63873. ** Often, v-tables store their data in other SQLite tables, which
  63874. ** are queried from within xNext() and other v-table methods using
  63875. ** prepared queries. If such a query is out-of-date, we do not want to
  63876. ** discard the database schema, as the user code implementing the
  63877. ** v-table would have to be ready for the sqlite3_vtab structure itself
  63878. ** to be invalidated whenever sqlite3_step() is called from within
  63879. ** a v-table method.
  63880. */
  63881. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  63882. sqlite3ResetOneSchema(db, pOp->p1);
  63883. }
  63884. p->expired = 1;
  63885. rc = SQLITE_SCHEMA;
  63886. }
  63887. break;
  63888. }
  63889. /* Opcode: OpenRead P1 P2 P3 P4 P5
  63890. **
  63891. ** Open a read-only cursor for the database table whose root page is
  63892. ** P2 in a database file. The database file is determined by P3.
  63893. ** P3==0 means the main database, P3==1 means the database used for
  63894. ** temporary tables, and P3>1 means used the corresponding attached
  63895. ** database. Give the new cursor an identifier of P1. The P1
  63896. ** values need not be contiguous but all P1 values should be small integers.
  63897. ** It is an error for P1 to be negative.
  63898. **
  63899. ** If P5!=0 then use the content of register P2 as the root page, not
  63900. ** the value of P2 itself.
  63901. **
  63902. ** There will be a read lock on the database whenever there is an
  63903. ** open cursor. If the database was unlocked prior to this instruction
  63904. ** then a read lock is acquired as part of this instruction. A read
  63905. ** lock allows other processes to read the database but prohibits
  63906. ** any other process from modifying the database. The read lock is
  63907. ** released when all cursors are closed. If this instruction attempts
  63908. ** to get a read lock but fails, the script terminates with an
  63909. ** SQLITE_BUSY error code.
  63910. **
  63911. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  63912. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  63913. ** structure, then said structure defines the content and collating
  63914. ** sequence of the index being opened. Otherwise, if P4 is an integer
  63915. ** value, it is set to the number of columns in the table.
  63916. **
  63917. ** See also OpenWrite.
  63918. */
  63919. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  63920. **
  63921. ** Open a read/write cursor named P1 on the table or index whose root
  63922. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  63923. ** root page.
  63924. **
  63925. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  63926. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  63927. ** structure, then said structure defines the content and collating
  63928. ** sequence of the index being opened. Otherwise, if P4 is an integer
  63929. ** value, it is set to the number of columns in the table, or to the
  63930. ** largest index of any column of the table that is actually used.
  63931. **
  63932. ** This instruction works just like OpenRead except that it opens the cursor
  63933. ** in read/write mode. For a given table, there can be one or more read-only
  63934. ** cursors or a single read/write cursor but not both.
  63935. **
  63936. ** See also OpenRead.
  63937. */
  63938. case OP_OpenRead:
  63939. case OP_OpenWrite: {
  63940. #if 0 /* local variables moved into u.ay */
  63941. int nField;
  63942. KeyInfo *pKeyInfo;
  63943. int p2;
  63944. int iDb;
  63945. int wrFlag;
  63946. Btree *pX;
  63947. VdbeCursor *pCur;
  63948. Db *pDb;
  63949. #endif /* local variables moved into u.ay */
  63950. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  63951. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  63952. if( p->expired ){
  63953. rc = SQLITE_ABORT;
  63954. break;
  63955. }
  63956. u.ay.nField = 0;
  63957. u.ay.pKeyInfo = 0;
  63958. u.ay.p2 = pOp->p2;
  63959. u.ay.iDb = pOp->p3;
  63960. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  63961. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  63962. u.ay.pDb = &db->aDb[u.ay.iDb];
  63963. u.ay.pX = u.ay.pDb->pBt;
  63964. assert( u.ay.pX!=0 );
  63965. if( pOp->opcode==OP_OpenWrite ){
  63966. u.ay.wrFlag = 1;
  63967. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  63968. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  63969. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  63970. }
  63971. }else{
  63972. u.ay.wrFlag = 0;
  63973. }
  63974. if( pOp->p5 & OPFLAG_P2ISREG ){
  63975. assert( u.ay.p2>0 );
  63976. assert( u.ay.p2<=p->nMem );
  63977. pIn2 = &aMem[u.ay.p2];
  63978. assert( memIsValid(pIn2) );
  63979. assert( (pIn2->flags & MEM_Int)!=0 );
  63980. sqlite3VdbeMemIntegerify(pIn2);
  63981. u.ay.p2 = (int)pIn2->u.i;
  63982. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  63983. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  63984. ** If there were a failure, the prepared statement would have halted
  63985. ** before reaching this instruction. */
  63986. if( NEVER(u.ay.p2<2) ) {
  63987. rc = SQLITE_CORRUPT_BKPT;
  63988. goto abort_due_to_error;
  63989. }
  63990. }
  63991. if( pOp->p4type==P4_KEYINFO ){
  63992. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  63993. u.ay.pKeyInfo->enc = ENC(p->db);
  63994. u.ay.nField = u.ay.pKeyInfo->nField+1;
  63995. }else if( pOp->p4type==P4_INT32 ){
  63996. u.ay.nField = pOp->p4.i;
  63997. }
  63998. assert( pOp->p1>=0 );
  63999. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  64000. if( u.ay.pCur==0 ) goto no_mem;
  64001. u.ay.pCur->nullRow = 1;
  64002. u.ay.pCur->isOrdered = 1;
  64003. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  64004. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  64005. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  64006. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  64007. /* Since it performs no memory allocation or IO, the only value that
  64008. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  64009. assert( rc==SQLITE_OK );
  64010. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  64011. ** SQLite used to check if the root-page flags were sane at this point
  64012. ** and report database corruption if they were not, but this check has
  64013. ** since moved into the btree layer. */
  64014. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  64015. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  64016. break;
  64017. }
  64018. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  64019. **
  64020. ** Open a new cursor P1 to a transient table.
  64021. ** The cursor is always opened read/write even if
  64022. ** the main database is read-only. The ephemeral
  64023. ** table is deleted automatically when the cursor is closed.
  64024. **
  64025. ** P2 is the number of columns in the ephemeral table.
  64026. ** The cursor points to a BTree table if P4==0 and to a BTree index
  64027. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  64028. ** that defines the format of keys in the index.
  64029. **
  64030. ** This opcode was once called OpenTemp. But that created
  64031. ** confusion because the term "temp table", might refer either
  64032. ** to a TEMP table at the SQL level, or to a table opened by
  64033. ** this opcode. Then this opcode was call OpenVirtual. But
  64034. ** that created confusion with the whole virtual-table idea.
  64035. **
  64036. ** The P5 parameter can be a mask of the BTREE_* flags defined
  64037. ** in btree.h. These flags control aspects of the operation of
  64038. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  64039. ** added automatically.
  64040. */
  64041. /* Opcode: OpenAutoindex P1 P2 * P4 *
  64042. **
  64043. ** This opcode works the same as OP_OpenEphemeral. It has a
  64044. ** different name to distinguish its use. Tables created using
  64045. ** by this opcode will be used for automatically created transient
  64046. ** indices in joins.
  64047. */
  64048. case OP_OpenAutoindex:
  64049. case OP_OpenEphemeral: {
  64050. #if 0 /* local variables moved into u.az */
  64051. VdbeCursor *pCx;
  64052. #endif /* local variables moved into u.az */
  64053. static const int vfsFlags =
  64054. SQLITE_OPEN_READWRITE |
  64055. SQLITE_OPEN_CREATE |
  64056. SQLITE_OPEN_EXCLUSIVE |
  64057. SQLITE_OPEN_DELETEONCLOSE |
  64058. SQLITE_OPEN_TRANSIENT_DB;
  64059. assert( pOp->p1>=0 );
  64060. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  64061. if( u.az.pCx==0 ) goto no_mem;
  64062. u.az.pCx->nullRow = 1;
  64063. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  64064. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  64065. if( rc==SQLITE_OK ){
  64066. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  64067. }
  64068. if( rc==SQLITE_OK ){
  64069. /* If a transient index is required, create it by calling
  64070. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  64071. ** opening it. If a transient table is required, just use the
  64072. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  64073. */
  64074. if( pOp->p4.pKeyInfo ){
  64075. int pgno;
  64076. assert( pOp->p4type==P4_KEYINFO );
  64077. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  64078. if( rc==SQLITE_OK ){
  64079. assert( pgno==MASTER_ROOT+1 );
  64080. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  64081. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  64082. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  64083. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  64084. }
  64085. u.az.pCx->isTable = 0;
  64086. }else{
  64087. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  64088. u.az.pCx->isTable = 1;
  64089. }
  64090. }
  64091. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  64092. u.az.pCx->isIndex = !u.az.pCx->isTable;
  64093. break;
  64094. }
  64095. /* Opcode: SorterOpen P1 P2 * P4 *
  64096. **
  64097. ** This opcode works like OP_OpenEphemeral except that it opens
  64098. ** a transient index that is specifically designed to sort large
  64099. ** tables using an external merge-sort algorithm.
  64100. */
  64101. case OP_SorterOpen: {
  64102. #if 0 /* local variables moved into u.ba */
  64103. VdbeCursor *pCx;
  64104. #endif /* local variables moved into u.ba */
  64105. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  64106. if( u.ba.pCx==0 ) goto no_mem;
  64107. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  64108. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  64109. u.ba.pCx->isSorter = 1;
  64110. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  64111. break;
  64112. }
  64113. /* Opcode: OpenPseudo P1 P2 P3 * P5
  64114. **
  64115. ** Open a new cursor that points to a fake table that contains a single
  64116. ** row of data. The content of that one row in the content of memory
  64117. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  64118. ** MEM_Blob content contained in register P2. When P5==1, then the
  64119. ** row is represented by P3 consecutive registers beginning with P2.
  64120. **
  64121. ** A pseudo-table created by this opcode is used to hold a single
  64122. ** row output from the sorter so that the row can be decomposed into
  64123. ** individual columns using the OP_Column opcode. The OP_Column opcode
  64124. ** is the only cursor opcode that works with a pseudo-table.
  64125. **
  64126. ** P3 is the number of fields in the records that will be stored by
  64127. ** the pseudo-table.
  64128. */
  64129. case OP_OpenPseudo: {
  64130. #if 0 /* local variables moved into u.bb */
  64131. VdbeCursor *pCx;
  64132. #endif /* local variables moved into u.bb */
  64133. assert( pOp->p1>=0 );
  64134. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  64135. if( u.bb.pCx==0 ) goto no_mem;
  64136. u.bb.pCx->nullRow = 1;
  64137. u.bb.pCx->pseudoTableReg = pOp->p2;
  64138. u.bb.pCx->isTable = 1;
  64139. u.bb.pCx->isIndex = 0;
  64140. u.bb.pCx->multiPseudo = pOp->p5;
  64141. break;
  64142. }
  64143. /* Opcode: Close P1 * * * *
  64144. **
  64145. ** Close a cursor previously opened as P1. If P1 is not
  64146. ** currently open, this instruction is a no-op.
  64147. */
  64148. case OP_Close: {
  64149. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64150. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  64151. p->apCsr[pOp->p1] = 0;
  64152. break;
  64153. }
  64154. /* Opcode: SeekGe P1 P2 P3 P4 *
  64155. **
  64156. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64157. ** use the value in register P3 as the key. If cursor P1 refers
  64158. ** to an SQL index, then P3 is the first in an array of P4 registers
  64159. ** that are used as an unpacked index key.
  64160. **
  64161. ** Reposition cursor P1 so that it points to the smallest entry that
  64162. ** is greater than or equal to the key value. If there are no records
  64163. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  64164. **
  64165. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  64166. */
  64167. /* Opcode: SeekGt P1 P2 P3 P4 *
  64168. **
  64169. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64170. ** use the value in register P3 as a key. If cursor P1 refers
  64171. ** to an SQL index, then P3 is the first in an array of P4 registers
  64172. ** that are used as an unpacked index key.
  64173. **
  64174. ** Reposition cursor P1 so that it points to the smallest entry that
  64175. ** is greater than the key value. If there are no records greater than
  64176. ** the key and P2 is not zero, then jump to P2.
  64177. **
  64178. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  64179. */
  64180. /* Opcode: SeekLt P1 P2 P3 P4 *
  64181. **
  64182. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64183. ** use the value in register P3 as a key. If cursor P1 refers
  64184. ** to an SQL index, then P3 is the first in an array of P4 registers
  64185. ** that are used as an unpacked index key.
  64186. **
  64187. ** Reposition cursor P1 so that it points to the largest entry that
  64188. ** is less than the key value. If there are no records less than
  64189. ** the key and P2 is not zero, then jump to P2.
  64190. **
  64191. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  64192. */
  64193. /* Opcode: SeekLe P1 P2 P3 P4 *
  64194. **
  64195. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  64196. ** use the value in register P3 as a key. If cursor P1 refers
  64197. ** to an SQL index, then P3 is the first in an array of P4 registers
  64198. ** that are used as an unpacked index key.
  64199. **
  64200. ** Reposition cursor P1 so that it points to the largest entry that
  64201. ** is less than or equal to the key value. If there are no records
  64202. ** less than or equal to the key and P2 is not zero, then jump to P2.
  64203. **
  64204. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  64205. */
  64206. case OP_SeekLt: /* jump, in3 */
  64207. case OP_SeekLe: /* jump, in3 */
  64208. case OP_SeekGe: /* jump, in3 */
  64209. case OP_SeekGt: { /* jump, in3 */
  64210. #if 0 /* local variables moved into u.bc */
  64211. int res;
  64212. int oc;
  64213. VdbeCursor *pC;
  64214. UnpackedRecord r;
  64215. int nField;
  64216. i64 iKey; /* The rowid we are to seek to */
  64217. #endif /* local variables moved into u.bc */
  64218. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64219. assert( pOp->p2!=0 );
  64220. u.bc.pC = p->apCsr[pOp->p1];
  64221. assert( u.bc.pC!=0 );
  64222. assert( u.bc.pC->pseudoTableReg==0 );
  64223. assert( OP_SeekLe == OP_SeekLt+1 );
  64224. assert( OP_SeekGe == OP_SeekLt+2 );
  64225. assert( OP_SeekGt == OP_SeekLt+3 );
  64226. assert( u.bc.pC->isOrdered );
  64227. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  64228. u.bc.oc = pOp->opcode;
  64229. u.bc.pC->nullRow = 0;
  64230. if( u.bc.pC->isTable ){
  64231. /* The input value in P3 might be of any type: integer, real, string,
  64232. ** blob, or NULL. But it needs to be an integer before we can do
  64233. ** the seek, so covert it. */
  64234. pIn3 = &aMem[pOp->p3];
  64235. applyNumericAffinity(pIn3);
  64236. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  64237. u.bc.pC->rowidIsValid = 0;
  64238. /* If the P3 value could not be converted into an integer without
  64239. ** loss of information, then special processing is required... */
  64240. if( (pIn3->flags & MEM_Int)==0 ){
  64241. if( (pIn3->flags & MEM_Real)==0 ){
  64242. /* If the P3 value cannot be converted into any kind of a number,
  64243. ** then the seek is not possible, so jump to P2 */
  64244. pc = pOp->p2 - 1;
  64245. break;
  64246. }
  64247. /* If we reach this point, then the P3 value must be a floating
  64248. ** point number. */
  64249. assert( (pIn3->flags & MEM_Real)!=0 );
  64250. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  64251. /* The P3 value is too large in magnitude to be expressed as an
  64252. ** integer. */
  64253. u.bc.res = 1;
  64254. if( pIn3->r<0 ){
  64255. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  64256. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  64257. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64258. }
  64259. }else{
  64260. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  64261. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  64262. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64263. }
  64264. }
  64265. if( u.bc.res ){
  64266. pc = pOp->p2 - 1;
  64267. }
  64268. break;
  64269. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  64270. /* Use the ceiling() function to convert real->int */
  64271. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  64272. }else{
  64273. /* Use the floor() function to convert real->int */
  64274. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  64275. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  64276. }
  64277. }
  64278. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  64279. if( rc!=SQLITE_OK ){
  64280. goto abort_due_to_error;
  64281. }
  64282. if( u.bc.res==0 ){
  64283. u.bc.pC->rowidIsValid = 1;
  64284. u.bc.pC->lastRowid = u.bc.iKey;
  64285. }
  64286. }else{
  64287. u.bc.nField = pOp->p4.i;
  64288. assert( pOp->p4type==P4_INT32 );
  64289. assert( u.bc.nField>0 );
  64290. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  64291. u.bc.r.nField = (u16)u.bc.nField;
  64292. /* The next line of code computes as follows, only faster:
  64293. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  64294. ** u.bc.r.flags = UNPACKED_INCRKEY;
  64295. ** }else{
  64296. ** u.bc.r.flags = 0;
  64297. ** }
  64298. */
  64299. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  64300. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  64301. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  64302. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  64303. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  64304. u.bc.r.aMem = &aMem[pOp->p3];
  64305. #ifdef SQLITE_DEBUG
  64306. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  64307. #endif
  64308. ExpandBlob(u.bc.r.aMem);
  64309. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  64310. if( rc!=SQLITE_OK ){
  64311. goto abort_due_to_error;
  64312. }
  64313. u.bc.pC->rowidIsValid = 0;
  64314. }
  64315. u.bc.pC->deferredMoveto = 0;
  64316. u.bc.pC->cacheStatus = CACHE_STALE;
  64317. #ifdef SQLITE_TEST
  64318. sqlite3_search_count++;
  64319. #endif
  64320. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  64321. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  64322. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  64323. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64324. u.bc.pC->rowidIsValid = 0;
  64325. }else{
  64326. u.bc.res = 0;
  64327. }
  64328. }else{
  64329. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  64330. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  64331. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  64332. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  64333. u.bc.pC->rowidIsValid = 0;
  64334. }else{
  64335. /* u.bc.res might be negative because the table is empty. Check to
  64336. ** see if this is the case.
  64337. */
  64338. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  64339. }
  64340. }
  64341. assert( pOp->p2>0 );
  64342. if( u.bc.res ){
  64343. pc = pOp->p2 - 1;
  64344. }
  64345. }else{
  64346. /* This happens when attempting to open the sqlite3_master table
  64347. ** for read access returns SQLITE_EMPTY. In this case always
  64348. ** take the jump (since there are no records in the table).
  64349. */
  64350. pc = pOp->p2 - 1;
  64351. }
  64352. break;
  64353. }
  64354. /* Opcode: Seek P1 P2 * * *
  64355. **
  64356. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  64357. ** for P1 to move so that it points to the rowid given by P2.
  64358. **
  64359. ** This is actually a deferred seek. Nothing actually happens until
  64360. ** the cursor is used to read a record. That way, if no reads
  64361. ** occur, no unnecessary I/O happens.
  64362. */
  64363. case OP_Seek: { /* in2 */
  64364. #if 0 /* local variables moved into u.bd */
  64365. VdbeCursor *pC;
  64366. #endif /* local variables moved into u.bd */
  64367. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64368. u.bd.pC = p->apCsr[pOp->p1];
  64369. assert( u.bd.pC!=0 );
  64370. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  64371. assert( u.bd.pC->isTable );
  64372. u.bd.pC->nullRow = 0;
  64373. pIn2 = &aMem[pOp->p2];
  64374. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  64375. u.bd.pC->rowidIsValid = 0;
  64376. u.bd.pC->deferredMoveto = 1;
  64377. }
  64378. break;
  64379. }
  64380. /* Opcode: Found P1 P2 P3 P4 *
  64381. **
  64382. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  64383. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  64384. ** record.
  64385. **
  64386. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  64387. ** is a prefix of any entry in P1 then a jump is made to P2 and
  64388. ** P1 is left pointing at the matching entry.
  64389. */
  64390. /* Opcode: NotFound P1 P2 P3 P4 *
  64391. **
  64392. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  64393. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  64394. ** record.
  64395. **
  64396. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  64397. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  64398. ** does contain an entry whose prefix matches the P3/P4 record then control
  64399. ** falls through to the next instruction and P1 is left pointing at the
  64400. ** matching entry.
  64401. **
  64402. ** See also: Found, NotExists, IsUnique
  64403. */
  64404. case OP_NotFound: /* jump, in3 */
  64405. case OP_Found: { /* jump, in3 */
  64406. #if 0 /* local variables moved into u.be */
  64407. int alreadyExists;
  64408. VdbeCursor *pC;
  64409. int res;
  64410. char *pFree;
  64411. UnpackedRecord *pIdxKey;
  64412. UnpackedRecord r;
  64413. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  64414. #endif /* local variables moved into u.be */
  64415. #ifdef SQLITE_TEST
  64416. sqlite3_found_count++;
  64417. #endif
  64418. u.be.alreadyExists = 0;
  64419. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64420. assert( pOp->p4type==P4_INT32 );
  64421. u.be.pC = p->apCsr[pOp->p1];
  64422. assert( u.be.pC!=0 );
  64423. pIn3 = &aMem[pOp->p3];
  64424. if( ALWAYS(u.be.pC->pCursor!=0) ){
  64425. assert( u.be.pC->isTable==0 );
  64426. if( pOp->p4.i>0 ){
  64427. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  64428. u.be.r.nField = (u16)pOp->p4.i;
  64429. u.be.r.aMem = pIn3;
  64430. #ifdef SQLITE_DEBUG
  64431. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  64432. #endif
  64433. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  64434. u.be.pIdxKey = &u.be.r;
  64435. }else{
  64436. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  64437. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  64438. );
  64439. if( u.be.pIdxKey==0 ) goto no_mem;
  64440. assert( pIn3->flags & MEM_Blob );
  64441. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  64442. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  64443. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  64444. }
  64445. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  64446. if( pOp->p4.i==0 ){
  64447. sqlite3DbFree(db, u.be.pFree);
  64448. }
  64449. if( rc!=SQLITE_OK ){
  64450. break;
  64451. }
  64452. u.be.alreadyExists = (u.be.res==0);
  64453. u.be.pC->deferredMoveto = 0;
  64454. u.be.pC->cacheStatus = CACHE_STALE;
  64455. }
  64456. if( pOp->opcode==OP_Found ){
  64457. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  64458. }else{
  64459. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  64460. }
  64461. break;
  64462. }
  64463. /* Opcode: IsUnique P1 P2 P3 P4 *
  64464. **
  64465. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  64466. ** no data and where the key are records generated by OP_MakeRecord with
  64467. ** the list field being the integer ROWID of the entry that the index
  64468. ** entry refers to.
  64469. **
  64470. ** The P3 register contains an integer record number. Call this record
  64471. ** number R. Register P4 is the first in a set of N contiguous registers
  64472. ** that make up an unpacked index key that can be used with cursor P1.
  64473. ** The value of N can be inferred from the cursor. N includes the rowid
  64474. ** value appended to the end of the index record. This rowid value may
  64475. ** or may not be the same as R.
  64476. **
  64477. ** If any of the N registers beginning with register P4 contains a NULL
  64478. ** value, jump immediately to P2.
  64479. **
  64480. ** Otherwise, this instruction checks if cursor P1 contains an entry
  64481. ** where the first (N-1) fields match but the rowid value at the end
  64482. ** of the index entry is not R. If there is no such entry, control jumps
  64483. ** to instruction P2. Otherwise, the rowid of the conflicting index
  64484. ** entry is copied to register P3 and control falls through to the next
  64485. ** instruction.
  64486. **
  64487. ** See also: NotFound, NotExists, Found
  64488. */
  64489. case OP_IsUnique: { /* jump, in3 */
  64490. #if 0 /* local variables moved into u.bf */
  64491. u16 ii;
  64492. VdbeCursor *pCx;
  64493. BtCursor *pCrsr;
  64494. u16 nField;
  64495. Mem *aMx;
  64496. UnpackedRecord r; /* B-Tree index search key */
  64497. i64 R; /* Rowid stored in register P3 */
  64498. #endif /* local variables moved into u.bf */
  64499. pIn3 = &aMem[pOp->p3];
  64500. u.bf.aMx = &aMem[pOp->p4.i];
  64501. /* Assert that the values of parameters P1 and P4 are in range. */
  64502. assert( pOp->p4type==P4_INT32 );
  64503. assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  64504. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64505. /* Find the index cursor. */
  64506. u.bf.pCx = p->apCsr[pOp->p1];
  64507. assert( u.bf.pCx->deferredMoveto==0 );
  64508. u.bf.pCx->seekResult = 0;
  64509. u.bf.pCx->cacheStatus = CACHE_STALE;
  64510. u.bf.pCrsr = u.bf.pCx->pCursor;
  64511. /* If any of the values are NULL, take the jump. */
  64512. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  64513. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  64514. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  64515. pc = pOp->p2 - 1;
  64516. u.bf.pCrsr = 0;
  64517. break;
  64518. }
  64519. }
  64520. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  64521. if( u.bf.pCrsr!=0 ){
  64522. /* Populate the index search key. */
  64523. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  64524. u.bf.r.nField = u.bf.nField + 1;
  64525. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  64526. u.bf.r.aMem = u.bf.aMx;
  64527. #ifdef SQLITE_DEBUG
  64528. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  64529. #endif
  64530. /* Extract the value of u.bf.R from register P3. */
  64531. sqlite3VdbeMemIntegerify(pIn3);
  64532. u.bf.R = pIn3->u.i;
  64533. /* Search the B-Tree index. If no conflicting record is found, jump
  64534. ** to P2. Otherwise, copy the rowid of the conflicting record to
  64535. ** register P3 and fall through to the next instruction. */
  64536. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  64537. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  64538. pc = pOp->p2 - 1;
  64539. }else{
  64540. pIn3->u.i = u.bf.r.rowid;
  64541. }
  64542. }
  64543. break;
  64544. }
  64545. /* Opcode: NotExists P1 P2 P3 * *
  64546. **
  64547. ** Use the content of register P3 as an integer key. If a record
  64548. ** with that key does not exist in table of P1, then jump to P2.
  64549. ** If the record does exist, then fall through. The cursor is left
  64550. ** pointing to the record if it exists.
  64551. **
  64552. ** The difference between this operation and NotFound is that this
  64553. ** operation assumes the key is an integer and that P1 is a table whereas
  64554. ** NotFound assumes key is a blob constructed from MakeRecord and
  64555. ** P1 is an index.
  64556. **
  64557. ** See also: Found, NotFound, IsUnique
  64558. */
  64559. case OP_NotExists: { /* jump, in3 */
  64560. #if 0 /* local variables moved into u.bg */
  64561. VdbeCursor *pC;
  64562. BtCursor *pCrsr;
  64563. int res;
  64564. u64 iKey;
  64565. #endif /* local variables moved into u.bg */
  64566. pIn3 = &aMem[pOp->p3];
  64567. assert( pIn3->flags & MEM_Int );
  64568. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64569. u.bg.pC = p->apCsr[pOp->p1];
  64570. assert( u.bg.pC!=0 );
  64571. assert( u.bg.pC->isTable );
  64572. assert( u.bg.pC->pseudoTableReg==0 );
  64573. u.bg.pCrsr = u.bg.pC->pCursor;
  64574. if( ALWAYS(u.bg.pCrsr!=0) ){
  64575. u.bg.res = 0;
  64576. u.bg.iKey = pIn3->u.i;
  64577. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  64578. u.bg.pC->lastRowid = pIn3->u.i;
  64579. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  64580. u.bg.pC->nullRow = 0;
  64581. u.bg.pC->cacheStatus = CACHE_STALE;
  64582. u.bg.pC->deferredMoveto = 0;
  64583. if( u.bg.res!=0 ){
  64584. pc = pOp->p2 - 1;
  64585. assert( u.bg.pC->rowidIsValid==0 );
  64586. }
  64587. u.bg.pC->seekResult = u.bg.res;
  64588. }else{
  64589. /* This happens when an attempt to open a read cursor on the
  64590. ** sqlite_master table returns SQLITE_EMPTY.
  64591. */
  64592. pc = pOp->p2 - 1;
  64593. assert( u.bg.pC->rowidIsValid==0 );
  64594. u.bg.pC->seekResult = 0;
  64595. }
  64596. break;
  64597. }
  64598. /* Opcode: Sequence P1 P2 * * *
  64599. **
  64600. ** Find the next available sequence number for cursor P1.
  64601. ** Write the sequence number into register P2.
  64602. ** The sequence number on the cursor is incremented after this
  64603. ** instruction.
  64604. */
  64605. case OP_Sequence: { /* out2-prerelease */
  64606. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64607. assert( p->apCsr[pOp->p1]!=0 );
  64608. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  64609. break;
  64610. }
  64611. /* Opcode: NewRowid P1 P2 P3 * *
  64612. **
  64613. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  64614. ** The record number is not previously used as a key in the database
  64615. ** table that cursor P1 points to. The new record number is written
  64616. ** written to register P2.
  64617. **
  64618. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  64619. ** the largest previously generated record number. No new record numbers are
  64620. ** allowed to be less than this value. When this value reaches its maximum,
  64621. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  64622. ** generated record number. This P3 mechanism is used to help implement the
  64623. ** AUTOINCREMENT feature.
  64624. */
  64625. case OP_NewRowid: { /* out2-prerelease */
  64626. #if 0 /* local variables moved into u.bh */
  64627. i64 v; /* The new rowid */
  64628. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  64629. int res; /* Result of an sqlite3BtreeLast() */
  64630. int cnt; /* Counter to limit the number of searches */
  64631. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  64632. VdbeFrame *pFrame; /* Root frame of VDBE */
  64633. #endif /* local variables moved into u.bh */
  64634. u.bh.v = 0;
  64635. u.bh.res = 0;
  64636. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64637. u.bh.pC = p->apCsr[pOp->p1];
  64638. assert( u.bh.pC!=0 );
  64639. if( NEVER(u.bh.pC->pCursor==0) ){
  64640. /* The zero initialization above is all that is needed */
  64641. }else{
  64642. /* The next rowid or record number (different terms for the same
  64643. ** thing) is obtained in a two-step algorithm.
  64644. **
  64645. ** First we attempt to find the largest existing rowid and add one
  64646. ** to that. But if the largest existing rowid is already the maximum
  64647. ** positive integer, we have to fall through to the second
  64648. ** probabilistic algorithm
  64649. **
  64650. ** The second algorithm is to select a rowid at random and see if
  64651. ** it already exists in the table. If it does not exist, we have
  64652. ** succeeded. If the random rowid does exist, we select a new one
  64653. ** and try again, up to 100 times.
  64654. */
  64655. assert( u.bh.pC->isTable );
  64656. #ifdef SQLITE_32BIT_ROWID
  64657. # define MAX_ROWID 0x7fffffff
  64658. #else
  64659. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  64660. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  64661. ** to provide the constant while making all compilers happy.
  64662. */
  64663. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  64664. #endif
  64665. if( !u.bh.pC->useRandomRowid ){
  64666. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  64667. if( u.bh.v==0 ){
  64668. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  64669. if( rc!=SQLITE_OK ){
  64670. goto abort_due_to_error;
  64671. }
  64672. if( u.bh.res ){
  64673. u.bh.v = 1; /* IMP: R-61914-48074 */
  64674. }else{
  64675. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  64676. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  64677. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  64678. if( u.bh.v>=MAX_ROWID ){
  64679. u.bh.pC->useRandomRowid = 1;
  64680. }else{
  64681. u.bh.v++; /* IMP: R-29538-34987 */
  64682. }
  64683. }
  64684. }
  64685. #ifndef SQLITE_OMIT_AUTOINCREMENT
  64686. if( pOp->p3 ){
  64687. /* Assert that P3 is a valid memory cell. */
  64688. assert( pOp->p3>0 );
  64689. if( p->pFrame ){
  64690. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  64691. /* Assert that P3 is a valid memory cell. */
  64692. assert( pOp->p3<=u.bh.pFrame->nMem );
  64693. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  64694. }else{
  64695. /* Assert that P3 is a valid memory cell. */
  64696. assert( pOp->p3<=p->nMem );
  64697. u.bh.pMem = &aMem[pOp->p3];
  64698. memAboutToChange(p, u.bh.pMem);
  64699. }
  64700. assert( memIsValid(u.bh.pMem) );
  64701. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  64702. sqlite3VdbeMemIntegerify(u.bh.pMem);
  64703. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  64704. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  64705. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  64706. goto abort_due_to_error;
  64707. }
  64708. if( u.bh.v<u.bh.pMem->u.i+1 ){
  64709. u.bh.v = u.bh.pMem->u.i + 1;
  64710. }
  64711. u.bh.pMem->u.i = u.bh.v;
  64712. }
  64713. #endif
  64714. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  64715. }
  64716. if( u.bh.pC->useRandomRowid ){
  64717. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  64718. ** largest possible integer (9223372036854775807) then the database
  64719. ** engine starts picking positive candidate ROWIDs at random until
  64720. ** it finds one that is not previously used. */
  64721. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  64722. ** an AUTOINCREMENT table. */
  64723. /* on the first attempt, simply do one more than previous */
  64724. u.bh.v = lastRowid;
  64725. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  64726. u.bh.v++; /* ensure non-zero */
  64727. u.bh.cnt = 0;
  64728. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  64729. 0, &u.bh.res))==SQLITE_OK)
  64730. && (u.bh.res==0)
  64731. && (++u.bh.cnt<100)){
  64732. /* collision - try another random rowid */
  64733. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  64734. if( u.bh.cnt<5 ){
  64735. /* try "small" random rowids for the initial attempts */
  64736. u.bh.v &= 0xffffff;
  64737. }else{
  64738. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  64739. }
  64740. u.bh.v++; /* ensure non-zero */
  64741. }
  64742. if( rc==SQLITE_OK && u.bh.res==0 ){
  64743. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  64744. goto abort_due_to_error;
  64745. }
  64746. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  64747. }
  64748. u.bh.pC->rowidIsValid = 0;
  64749. u.bh.pC->deferredMoveto = 0;
  64750. u.bh.pC->cacheStatus = CACHE_STALE;
  64751. }
  64752. pOut->u.i = u.bh.v;
  64753. break;
  64754. }
  64755. /* Opcode: Insert P1 P2 P3 P4 P5
  64756. **
  64757. ** Write an entry into the table of cursor P1. A new entry is
  64758. ** created if it doesn't already exist or the data for an existing
  64759. ** entry is overwritten. The data is the value MEM_Blob stored in register
  64760. ** number P2. The key is stored in register P3. The key must
  64761. ** be a MEM_Int.
  64762. **
  64763. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  64764. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  64765. ** then rowid is stored for subsequent return by the
  64766. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  64767. **
  64768. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  64769. ** the last seek operation (OP_NotExists) was a success, then this
  64770. ** operation will not attempt to find the appropriate row before doing
  64771. ** the insert but will instead overwrite the row that the cursor is
  64772. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  64773. ** has already positioned the cursor correctly. This is an optimization
  64774. ** that boosts performance by avoiding redundant seeks.
  64775. **
  64776. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  64777. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  64778. ** is part of an INSERT operation. The difference is only important to
  64779. ** the update hook.
  64780. **
  64781. ** Parameter P4 may point to a string containing the table-name, or
  64782. ** may be NULL. If it is not NULL, then the update-hook
  64783. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  64784. **
  64785. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  64786. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  64787. ** and register P2 becomes ephemeral. If the cursor is changed, the
  64788. ** value of register P2 will then change. Make sure this does not
  64789. ** cause any problems.)
  64790. **
  64791. ** This instruction only works on tables. The equivalent instruction
  64792. ** for indices is OP_IdxInsert.
  64793. */
  64794. /* Opcode: InsertInt P1 P2 P3 P4 P5
  64795. **
  64796. ** This works exactly like OP_Insert except that the key is the
  64797. ** integer value P3, not the value of the integer stored in register P3.
  64798. */
  64799. case OP_Insert:
  64800. case OP_InsertInt: {
  64801. #if 0 /* local variables moved into u.bi */
  64802. Mem *pData; /* MEM cell holding data for the record to be inserted */
  64803. Mem *pKey; /* MEM cell holding key for the record */
  64804. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  64805. VdbeCursor *pC; /* Cursor to table into which insert is written */
  64806. int nZero; /* Number of zero-bytes to append */
  64807. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  64808. const char *zDb; /* database name - used by the update hook */
  64809. const char *zTbl; /* Table name - used by the opdate hook */
  64810. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  64811. #endif /* local variables moved into u.bi */
  64812. u.bi.pData = &aMem[pOp->p2];
  64813. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64814. assert( memIsValid(u.bi.pData) );
  64815. u.bi.pC = p->apCsr[pOp->p1];
  64816. assert( u.bi.pC!=0 );
  64817. assert( u.bi.pC->pCursor!=0 );
  64818. assert( u.bi.pC->pseudoTableReg==0 );
  64819. assert( u.bi.pC->isTable );
  64820. REGISTER_TRACE(pOp->p2, u.bi.pData);
  64821. if( pOp->opcode==OP_Insert ){
  64822. u.bi.pKey = &aMem[pOp->p3];
  64823. assert( u.bi.pKey->flags & MEM_Int );
  64824. assert( memIsValid(u.bi.pKey) );
  64825. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  64826. u.bi.iKey = u.bi.pKey->u.i;
  64827. }else{
  64828. assert( pOp->opcode==OP_InsertInt );
  64829. u.bi.iKey = pOp->p3;
  64830. }
  64831. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  64832. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  64833. if( u.bi.pData->flags & MEM_Null ){
  64834. u.bi.pData->z = 0;
  64835. u.bi.pData->n = 0;
  64836. }else{
  64837. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  64838. }
  64839. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  64840. if( u.bi.pData->flags & MEM_Zero ){
  64841. u.bi.nZero = u.bi.pData->u.nZero;
  64842. }else{
  64843. u.bi.nZero = 0;
  64844. }
  64845. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  64846. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  64847. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  64848. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  64849. );
  64850. u.bi.pC->rowidIsValid = 0;
  64851. u.bi.pC->deferredMoveto = 0;
  64852. u.bi.pC->cacheStatus = CACHE_STALE;
  64853. /* Invoke the update-hook if required. */
  64854. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  64855. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  64856. u.bi.zTbl = pOp->p4.z;
  64857. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  64858. assert( u.bi.pC->isTable );
  64859. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  64860. assert( u.bi.pC->iDb>=0 );
  64861. }
  64862. break;
  64863. }
  64864. /* Opcode: Delete P1 P2 * P4 *
  64865. **
  64866. ** Delete the record at which the P1 cursor is currently pointing.
  64867. **
  64868. ** The cursor will be left pointing at either the next or the previous
  64869. ** record in the table. If it is left pointing at the next record, then
  64870. ** the next Next instruction will be a no-op. Hence it is OK to delete
  64871. ** a record from within an Next loop.
  64872. **
  64873. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  64874. ** incremented (otherwise not).
  64875. **
  64876. ** P1 must not be pseudo-table. It has to be a real table with
  64877. ** multiple rows.
  64878. **
  64879. ** If P4 is not NULL, then it is the name of the table that P1 is
  64880. ** pointing to. The update hook will be invoked, if it exists.
  64881. ** If P4 is not NULL then the P1 cursor must have been positioned
  64882. ** using OP_NotFound prior to invoking this opcode.
  64883. */
  64884. case OP_Delete: {
  64885. #if 0 /* local variables moved into u.bj */
  64886. i64 iKey;
  64887. VdbeCursor *pC;
  64888. #endif /* local variables moved into u.bj */
  64889. u.bj.iKey = 0;
  64890. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64891. u.bj.pC = p->apCsr[pOp->p1];
  64892. assert( u.bj.pC!=0 );
  64893. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  64894. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  64895. ** row being deleted.
  64896. */
  64897. if( db->xUpdateCallback && pOp->p4.z ){
  64898. assert( u.bj.pC->isTable );
  64899. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  64900. u.bj.iKey = u.bj.pC->lastRowid;
  64901. }
  64902. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  64903. ** OP_Column on the same table without any intervening operations that
  64904. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  64905. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  64906. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  64907. ** to guard against future changes to the code generator.
  64908. **/
  64909. assert( u.bj.pC->deferredMoveto==0 );
  64910. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  64911. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  64912. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  64913. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  64914. u.bj.pC->cacheStatus = CACHE_STALE;
  64915. /* Invoke the update-hook if required. */
  64916. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  64917. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  64918. const char *zTbl = pOp->p4.z;
  64919. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  64920. assert( u.bj.pC->iDb>=0 );
  64921. }
  64922. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  64923. break;
  64924. }
  64925. /* Opcode: ResetCount * * * * *
  64926. **
  64927. ** The value of the change counter is copied to the database handle
  64928. ** change counter (returned by subsequent calls to sqlite3_changes()).
  64929. ** Then the VMs internal change counter resets to 0.
  64930. ** This is used by trigger programs.
  64931. */
  64932. case OP_ResetCount: {
  64933. sqlite3VdbeSetChanges(db, p->nChange);
  64934. p->nChange = 0;
  64935. break;
  64936. }
  64937. /* Opcode: SorterCompare P1 P2 P3
  64938. **
  64939. ** P1 is a sorter cursor. This instruction compares the record blob in
  64940. ** register P3 with the entry that the sorter cursor currently points to.
  64941. ** If, excluding the rowid fields at the end, the two records are a match,
  64942. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  64943. */
  64944. case OP_SorterCompare: {
  64945. #if 0 /* local variables moved into u.bk */
  64946. VdbeCursor *pC;
  64947. int res;
  64948. #endif /* local variables moved into u.bk */
  64949. u.bk.pC = p->apCsr[pOp->p1];
  64950. assert( isSorter(u.bk.pC) );
  64951. pIn3 = &aMem[pOp->p3];
  64952. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  64953. if( u.bk.res ){
  64954. pc = pOp->p2-1;
  64955. }
  64956. break;
  64957. };
  64958. /* Opcode: SorterData P1 P2 * * *
  64959. **
  64960. ** Write into register P2 the current sorter data for sorter cursor P1.
  64961. */
  64962. case OP_SorterData: {
  64963. #if 0 /* local variables moved into u.bl */
  64964. VdbeCursor *pC;
  64965. #endif /* local variables moved into u.bl */
  64966. pOut = &aMem[pOp->p2];
  64967. u.bl.pC = p->apCsr[pOp->p1];
  64968. assert( u.bl.pC->isSorter );
  64969. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  64970. break;
  64971. }
  64972. /* Opcode: RowData P1 P2 * * *
  64973. **
  64974. ** Write into register P2 the complete row data for cursor P1.
  64975. ** There is no interpretation of the data.
  64976. ** It is just copied onto the P2 register exactly as
  64977. ** it is found in the database file.
  64978. **
  64979. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  64980. ** of a real table, not a pseudo-table.
  64981. */
  64982. /* Opcode: RowKey P1 P2 * * *
  64983. **
  64984. ** Write into register P2 the complete row key for cursor P1.
  64985. ** There is no interpretation of the data.
  64986. ** The key is copied onto the P3 register exactly as
  64987. ** it is found in the database file.
  64988. **
  64989. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  64990. ** of a real table, not a pseudo-table.
  64991. */
  64992. case OP_RowKey:
  64993. case OP_RowData: {
  64994. #if 0 /* local variables moved into u.bm */
  64995. VdbeCursor *pC;
  64996. BtCursor *pCrsr;
  64997. u32 n;
  64998. i64 n64;
  64999. #endif /* local variables moved into u.bm */
  65000. pOut = &aMem[pOp->p2];
  65001. memAboutToChange(p, pOut);
  65002. /* Note that RowKey and RowData are really exactly the same instruction */
  65003. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65004. u.bm.pC = p->apCsr[pOp->p1];
  65005. assert( u.bm.pC->isSorter==0 );
  65006. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  65007. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  65008. assert( u.bm.pC!=0 );
  65009. assert( u.bm.pC->nullRow==0 );
  65010. assert( u.bm.pC->pseudoTableReg==0 );
  65011. assert( u.bm.pC->pCursor!=0 );
  65012. u.bm.pCrsr = u.bm.pC->pCursor;
  65013. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  65014. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  65015. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  65016. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  65017. ** a no-op and can never fail. But we leave it in place as a safety.
  65018. */
  65019. assert( u.bm.pC->deferredMoveto==0 );
  65020. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  65021. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  65022. if( u.bm.pC->isIndex ){
  65023. assert( !u.bm.pC->isTable );
  65024. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  65025. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  65026. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65027. goto too_big;
  65028. }
  65029. u.bm.n = (u32)u.bm.n64;
  65030. }else{
  65031. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  65032. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  65033. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65034. goto too_big;
  65035. }
  65036. }
  65037. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  65038. goto no_mem;
  65039. }
  65040. pOut->n = u.bm.n;
  65041. MemSetTypeFlag(pOut, MEM_Blob);
  65042. if( u.bm.pC->isIndex ){
  65043. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  65044. }else{
  65045. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  65046. }
  65047. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  65048. UPDATE_MAX_BLOBSIZE(pOut);
  65049. break;
  65050. }
  65051. /* Opcode: Rowid P1 P2 * * *
  65052. **
  65053. ** Store in register P2 an integer which is the key of the table entry that
  65054. ** P1 is currently point to.
  65055. **
  65056. ** P1 can be either an ordinary table or a virtual table. There used to
  65057. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  65058. ** one opcode now works for both table types.
  65059. */
  65060. case OP_Rowid: { /* out2-prerelease */
  65061. #if 0 /* local variables moved into u.bn */
  65062. VdbeCursor *pC;
  65063. i64 v;
  65064. sqlite3_vtab *pVtab;
  65065. const sqlite3_module *pModule;
  65066. #endif /* local variables moved into u.bn */
  65067. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65068. u.bn.pC = p->apCsr[pOp->p1];
  65069. assert( u.bn.pC!=0 );
  65070. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  65071. if( u.bn.pC->nullRow ){
  65072. pOut->flags = MEM_Null;
  65073. break;
  65074. }else if( u.bn.pC->deferredMoveto ){
  65075. u.bn.v = u.bn.pC->movetoTarget;
  65076. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65077. }else if( u.bn.pC->pVtabCursor ){
  65078. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  65079. u.bn.pModule = u.bn.pVtab->pModule;
  65080. assert( u.bn.pModule->xRowid );
  65081. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  65082. importVtabErrMsg(p, u.bn.pVtab);
  65083. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65084. }else{
  65085. assert( u.bn.pC->pCursor!=0 );
  65086. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  65087. if( rc ) goto abort_due_to_error;
  65088. if( u.bn.pC->rowidIsValid ){
  65089. u.bn.v = u.bn.pC->lastRowid;
  65090. }else{
  65091. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  65092. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  65093. }
  65094. }
  65095. pOut->u.i = u.bn.v;
  65096. break;
  65097. }
  65098. /* Opcode: NullRow P1 * * * *
  65099. **
  65100. ** Move the cursor P1 to a null row. Any OP_Column operations
  65101. ** that occur while the cursor is on the null row will always
  65102. ** write a NULL.
  65103. */
  65104. case OP_NullRow: {
  65105. #if 0 /* local variables moved into u.bo */
  65106. VdbeCursor *pC;
  65107. #endif /* local variables moved into u.bo */
  65108. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65109. u.bo.pC = p->apCsr[pOp->p1];
  65110. assert( u.bo.pC!=0 );
  65111. u.bo.pC->nullRow = 1;
  65112. u.bo.pC->rowidIsValid = 0;
  65113. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  65114. if( u.bo.pC->pCursor ){
  65115. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  65116. }
  65117. break;
  65118. }
  65119. /* Opcode: Last P1 P2 * * *
  65120. **
  65121. ** The next use of the Rowid or Column or Next instruction for P1
  65122. ** will refer to the last entry in the database table or index.
  65123. ** If the table or index is empty and P2>0, then jump immediately to P2.
  65124. ** If P2 is 0 or if the table or index is not empty, fall through
  65125. ** to the following instruction.
  65126. */
  65127. case OP_Last: { /* jump */
  65128. #if 0 /* local variables moved into u.bp */
  65129. VdbeCursor *pC;
  65130. BtCursor *pCrsr;
  65131. int res;
  65132. #endif /* local variables moved into u.bp */
  65133. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65134. u.bp.pC = p->apCsr[pOp->p1];
  65135. assert( u.bp.pC!=0 );
  65136. u.bp.pCrsr = u.bp.pC->pCursor;
  65137. u.bp.res = 0;
  65138. if( ALWAYS(u.bp.pCrsr!=0) ){
  65139. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  65140. }
  65141. u.bp.pC->nullRow = (u8)u.bp.res;
  65142. u.bp.pC->deferredMoveto = 0;
  65143. u.bp.pC->rowidIsValid = 0;
  65144. u.bp.pC->cacheStatus = CACHE_STALE;
  65145. if( pOp->p2>0 && u.bp.res ){
  65146. pc = pOp->p2 - 1;
  65147. }
  65148. break;
  65149. }
  65150. /* Opcode: Sort P1 P2 * * *
  65151. **
  65152. ** This opcode does exactly the same thing as OP_Rewind except that
  65153. ** it increments an undocumented global variable used for testing.
  65154. **
  65155. ** Sorting is accomplished by writing records into a sorting index,
  65156. ** then rewinding that index and playing it back from beginning to
  65157. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  65158. ** rewinding so that the global variable will be incremented and
  65159. ** regression tests can determine whether or not the optimizer is
  65160. ** correctly optimizing out sorts.
  65161. */
  65162. case OP_SorterSort: /* jump */
  65163. case OP_Sort: { /* jump */
  65164. #ifdef SQLITE_TEST
  65165. sqlite3_sort_count++;
  65166. sqlite3_search_count--;
  65167. #endif
  65168. p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  65169. /* Fall through into OP_Rewind */
  65170. }
  65171. /* Opcode: Rewind P1 P2 * * *
  65172. **
  65173. ** The next use of the Rowid or Column or Next instruction for P1
  65174. ** will refer to the first entry in the database table or index.
  65175. ** If the table or index is empty and P2>0, then jump immediately to P2.
  65176. ** If P2 is 0 or if the table or index is not empty, fall through
  65177. ** to the following instruction.
  65178. */
  65179. case OP_Rewind: { /* jump */
  65180. #if 0 /* local variables moved into u.bq */
  65181. VdbeCursor *pC;
  65182. BtCursor *pCrsr;
  65183. int res;
  65184. #endif /* local variables moved into u.bq */
  65185. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65186. u.bq.pC = p->apCsr[pOp->p1];
  65187. assert( u.bq.pC!=0 );
  65188. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  65189. u.bq.res = 1;
  65190. if( isSorter(u.bq.pC) ){
  65191. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  65192. }else{
  65193. u.bq.pCrsr = u.bq.pC->pCursor;
  65194. assert( u.bq.pCrsr );
  65195. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  65196. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  65197. u.bq.pC->deferredMoveto = 0;
  65198. u.bq.pC->cacheStatus = CACHE_STALE;
  65199. u.bq.pC->rowidIsValid = 0;
  65200. }
  65201. u.bq.pC->nullRow = (u8)u.bq.res;
  65202. assert( pOp->p2>0 && pOp->p2<p->nOp );
  65203. if( u.bq.res ){
  65204. pc = pOp->p2 - 1;
  65205. }
  65206. break;
  65207. }
  65208. /* Opcode: Next P1 P2 * P4 P5
  65209. **
  65210. ** Advance cursor P1 so that it points to the next key/data pair in its
  65211. ** table or index. If there are no more key/value pairs then fall through
  65212. ** to the following instruction. But if the cursor advance was successful,
  65213. ** jump immediately to P2.
  65214. **
  65215. ** The P1 cursor must be for a real table, not a pseudo-table.
  65216. **
  65217. ** P4 is always of type P4_ADVANCE. The function pointer points to
  65218. ** sqlite3BtreeNext().
  65219. **
  65220. ** If P5 is positive and the jump is taken, then event counter
  65221. ** number P5-1 in the prepared statement is incremented.
  65222. **
  65223. ** See also: Prev
  65224. */
  65225. /* Opcode: Prev P1 P2 * * P5
  65226. **
  65227. ** Back up cursor P1 so that it points to the previous key/data pair in its
  65228. ** table or index. If there is no previous key/value pairs then fall through
  65229. ** to the following instruction. But if the cursor backup was successful,
  65230. ** jump immediately to P2.
  65231. **
  65232. ** The P1 cursor must be for a real table, not a pseudo-table.
  65233. **
  65234. ** P4 is always of type P4_ADVANCE. The function pointer points to
  65235. ** sqlite3BtreePrevious().
  65236. **
  65237. ** If P5 is positive and the jump is taken, then event counter
  65238. ** number P5-1 in the prepared statement is incremented.
  65239. */
  65240. case OP_SorterNext: /* jump */
  65241. case OP_Prev: /* jump */
  65242. case OP_Next: { /* jump */
  65243. #if 0 /* local variables moved into u.br */
  65244. VdbeCursor *pC;
  65245. int res;
  65246. #endif /* local variables moved into u.br */
  65247. CHECK_FOR_INTERRUPT;
  65248. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65249. assert( pOp->p5<=ArraySize(p->aCounter) );
  65250. u.br.pC = p->apCsr[pOp->p1];
  65251. if( u.br.pC==0 ){
  65252. break; /* See ticket #2273 */
  65253. }
  65254. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  65255. if( isSorter(u.br.pC) ){
  65256. assert( pOp->opcode==OP_SorterNext );
  65257. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  65258. }else{
  65259. u.br.res = 1;
  65260. assert( u.br.pC->deferredMoveto==0 );
  65261. assert( u.br.pC->pCursor );
  65262. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  65263. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  65264. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  65265. }
  65266. u.br.pC->nullRow = (u8)u.br.res;
  65267. u.br.pC->cacheStatus = CACHE_STALE;
  65268. if( u.br.res==0 ){
  65269. pc = pOp->p2 - 1;
  65270. if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
  65271. #ifdef SQLITE_TEST
  65272. sqlite3_search_count++;
  65273. #endif
  65274. }
  65275. u.br.pC->rowidIsValid = 0;
  65276. break;
  65277. }
  65278. /* Opcode: IdxInsert P1 P2 P3 * P5
  65279. **
  65280. ** Register P2 holds an SQL index key made using the
  65281. ** MakeRecord instructions. This opcode writes that key
  65282. ** into the index P1. Data for the entry is nil.
  65283. **
  65284. ** P3 is a flag that provides a hint to the b-tree layer that this
  65285. ** insert is likely to be an append.
  65286. **
  65287. ** This instruction only works for indices. The equivalent instruction
  65288. ** for tables is OP_Insert.
  65289. */
  65290. case OP_SorterInsert: /* in2 */
  65291. case OP_IdxInsert: { /* in2 */
  65292. #if 0 /* local variables moved into u.bs */
  65293. VdbeCursor *pC;
  65294. BtCursor *pCrsr;
  65295. int nKey;
  65296. const char *zKey;
  65297. #endif /* local variables moved into u.bs */
  65298. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65299. u.bs.pC = p->apCsr[pOp->p1];
  65300. assert( u.bs.pC!=0 );
  65301. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  65302. pIn2 = &aMem[pOp->p2];
  65303. assert( pIn2->flags & MEM_Blob );
  65304. u.bs.pCrsr = u.bs.pC->pCursor;
  65305. if( ALWAYS(u.bs.pCrsr!=0) ){
  65306. assert( u.bs.pC->isTable==0 );
  65307. rc = ExpandBlob(pIn2);
  65308. if( rc==SQLITE_OK ){
  65309. if( isSorter(u.bs.pC) ){
  65310. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  65311. }else{
  65312. u.bs.nKey = pIn2->n;
  65313. u.bs.zKey = pIn2->z;
  65314. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  65315. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  65316. );
  65317. assert( u.bs.pC->deferredMoveto==0 );
  65318. u.bs.pC->cacheStatus = CACHE_STALE;
  65319. }
  65320. }
  65321. }
  65322. break;
  65323. }
  65324. /* Opcode: IdxDelete P1 P2 P3 * *
  65325. **
  65326. ** The content of P3 registers starting at register P2 form
  65327. ** an unpacked index key. This opcode removes that entry from the
  65328. ** index opened by cursor P1.
  65329. */
  65330. case OP_IdxDelete: {
  65331. #if 0 /* local variables moved into u.bt */
  65332. VdbeCursor *pC;
  65333. BtCursor *pCrsr;
  65334. int res;
  65335. UnpackedRecord r;
  65336. #endif /* local variables moved into u.bt */
  65337. assert( pOp->p3>0 );
  65338. assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
  65339. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65340. u.bt.pC = p->apCsr[pOp->p1];
  65341. assert( u.bt.pC!=0 );
  65342. u.bt.pCrsr = u.bt.pC->pCursor;
  65343. if( ALWAYS(u.bt.pCrsr!=0) ){
  65344. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  65345. u.bt.r.nField = (u16)pOp->p3;
  65346. u.bt.r.flags = 0;
  65347. u.bt.r.aMem = &aMem[pOp->p2];
  65348. #ifdef SQLITE_DEBUG
  65349. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  65350. #endif
  65351. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  65352. if( rc==SQLITE_OK && u.bt.res==0 ){
  65353. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  65354. }
  65355. assert( u.bt.pC->deferredMoveto==0 );
  65356. u.bt.pC->cacheStatus = CACHE_STALE;
  65357. }
  65358. break;
  65359. }
  65360. /* Opcode: IdxRowid P1 P2 * * *
  65361. **
  65362. ** Write into register P2 an integer which is the last entry in the record at
  65363. ** the end of the index key pointed to by cursor P1. This integer should be
  65364. ** the rowid of the table entry to which this index entry points.
  65365. **
  65366. ** See also: Rowid, MakeRecord.
  65367. */
  65368. case OP_IdxRowid: { /* out2-prerelease */
  65369. #if 0 /* local variables moved into u.bu */
  65370. BtCursor *pCrsr;
  65371. VdbeCursor *pC;
  65372. i64 rowid;
  65373. #endif /* local variables moved into u.bu */
  65374. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65375. u.bu.pC = p->apCsr[pOp->p1];
  65376. assert( u.bu.pC!=0 );
  65377. u.bu.pCrsr = u.bu.pC->pCursor;
  65378. pOut->flags = MEM_Null;
  65379. if( ALWAYS(u.bu.pCrsr!=0) ){
  65380. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  65381. if( NEVER(rc) ) goto abort_due_to_error;
  65382. assert( u.bu.pC->deferredMoveto==0 );
  65383. assert( u.bu.pC->isTable==0 );
  65384. if( !u.bu.pC->nullRow ){
  65385. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  65386. if( rc!=SQLITE_OK ){
  65387. goto abort_due_to_error;
  65388. }
  65389. pOut->u.i = u.bu.rowid;
  65390. pOut->flags = MEM_Int;
  65391. }
  65392. }
  65393. break;
  65394. }
  65395. /* Opcode: IdxGE P1 P2 P3 P4 P5
  65396. **
  65397. ** The P4 register values beginning with P3 form an unpacked index
  65398. ** key that omits the ROWID. Compare this key value against the index
  65399. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  65400. **
  65401. ** If the P1 index entry is greater than or equal to the key value
  65402. ** then jump to P2. Otherwise fall through to the next instruction.
  65403. **
  65404. ** If P5 is non-zero then the key value is increased by an epsilon
  65405. ** prior to the comparison. This make the opcode work like IdxGT except
  65406. ** that if the key from register P3 is a prefix of the key in the cursor,
  65407. ** the result is false whereas it would be true with IdxGT.
  65408. */
  65409. /* Opcode: IdxLT P1 P2 P3 P4 P5
  65410. **
  65411. ** The P4 register values beginning with P3 form an unpacked index
  65412. ** key that omits the ROWID. Compare this key value against the index
  65413. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  65414. **
  65415. ** If the P1 index entry is less than the key value then jump to P2.
  65416. ** Otherwise fall through to the next instruction.
  65417. **
  65418. ** If P5 is non-zero then the key value is increased by an epsilon prior
  65419. ** to the comparison. This makes the opcode work like IdxLE.
  65420. */
  65421. case OP_IdxLT: /* jump */
  65422. case OP_IdxGE: { /* jump */
  65423. #if 0 /* local variables moved into u.bv */
  65424. VdbeCursor *pC;
  65425. int res;
  65426. UnpackedRecord r;
  65427. #endif /* local variables moved into u.bv */
  65428. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  65429. u.bv.pC = p->apCsr[pOp->p1];
  65430. assert( u.bv.pC!=0 );
  65431. assert( u.bv.pC->isOrdered );
  65432. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  65433. assert( u.bv.pC->deferredMoveto==0 );
  65434. assert( pOp->p5==0 || pOp->p5==1 );
  65435. assert( pOp->p4type==P4_INT32 );
  65436. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  65437. u.bv.r.nField = (u16)pOp->p4.i;
  65438. if( pOp->p5 ){
  65439. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  65440. }else{
  65441. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  65442. }
  65443. u.bv.r.aMem = &aMem[pOp->p3];
  65444. #ifdef SQLITE_DEBUG
  65445. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  65446. #endif
  65447. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  65448. if( pOp->opcode==OP_IdxLT ){
  65449. u.bv.res = -u.bv.res;
  65450. }else{
  65451. assert( pOp->opcode==OP_IdxGE );
  65452. u.bv.res++;
  65453. }
  65454. if( u.bv.res>0 ){
  65455. pc = pOp->p2 - 1 ;
  65456. }
  65457. }
  65458. break;
  65459. }
  65460. /* Opcode: Destroy P1 P2 P3 * *
  65461. **
  65462. ** Delete an entire database table or index whose root page in the database
  65463. ** file is given by P1.
  65464. **
  65465. ** The table being destroyed is in the main database file if P3==0. If
  65466. ** P3==1 then the table to be clear is in the auxiliary database file
  65467. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  65468. **
  65469. ** If AUTOVACUUM is enabled then it is possible that another root page
  65470. ** might be moved into the newly deleted root page in order to keep all
  65471. ** root pages contiguous at the beginning of the database. The former
  65472. ** value of the root page that moved - its value before the move occurred -
  65473. ** is stored in register P2. If no page
  65474. ** movement was required (because the table being dropped was already
  65475. ** the last one in the database) then a zero is stored in register P2.
  65476. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  65477. **
  65478. ** See also: Clear
  65479. */
  65480. case OP_Destroy: { /* out2-prerelease */
  65481. #if 0 /* local variables moved into u.bw */
  65482. int iMoved;
  65483. int iCnt;
  65484. Vdbe *pVdbe;
  65485. int iDb;
  65486. #endif /* local variables moved into u.bw */
  65487. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65488. u.bw.iCnt = 0;
  65489. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  65490. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
  65491. u.bw.iCnt++;
  65492. }
  65493. }
  65494. #else
  65495. u.bw.iCnt = db->activeVdbeCnt;
  65496. #endif
  65497. pOut->flags = MEM_Null;
  65498. if( u.bw.iCnt>1 ){
  65499. rc = SQLITE_LOCKED;
  65500. p->errorAction = OE_Abort;
  65501. }else{
  65502. u.bw.iDb = pOp->p3;
  65503. assert( u.bw.iCnt==1 );
  65504. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  65505. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  65506. pOut->flags = MEM_Int;
  65507. pOut->u.i = u.bw.iMoved;
  65508. #ifndef SQLITE_OMIT_AUTOVACUUM
  65509. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  65510. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  65511. /* All OP_Destroy operations occur on the same btree */
  65512. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  65513. resetSchemaOnFault = u.bw.iDb+1;
  65514. }
  65515. #endif
  65516. }
  65517. break;
  65518. }
  65519. /* Opcode: Clear P1 P2 P3
  65520. **
  65521. ** Delete all contents of the database table or index whose root page
  65522. ** in the database file is given by P1. But, unlike Destroy, do not
  65523. ** remove the table or index from the database file.
  65524. **
  65525. ** The table being clear is in the main database file if P2==0. If
  65526. ** P2==1 then the table to be clear is in the auxiliary database file
  65527. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  65528. **
  65529. ** If the P3 value is non-zero, then the table referred to must be an
  65530. ** intkey table (an SQL table, not an index). In this case the row change
  65531. ** count is incremented by the number of rows in the table being cleared.
  65532. ** If P3 is greater than zero, then the value stored in register P3 is
  65533. ** also incremented by the number of rows in the table being cleared.
  65534. **
  65535. ** See also: Destroy
  65536. */
  65537. case OP_Clear: {
  65538. #if 0 /* local variables moved into u.bx */
  65539. int nChange;
  65540. #endif /* local variables moved into u.bx */
  65541. u.bx.nChange = 0;
  65542. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  65543. rc = sqlite3BtreeClearTable(
  65544. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  65545. );
  65546. if( pOp->p3 ){
  65547. p->nChange += u.bx.nChange;
  65548. if( pOp->p3>0 ){
  65549. assert( memIsValid(&aMem[pOp->p3]) );
  65550. memAboutToChange(p, &aMem[pOp->p3]);
  65551. aMem[pOp->p3].u.i += u.bx.nChange;
  65552. }
  65553. }
  65554. break;
  65555. }
  65556. /* Opcode: CreateTable P1 P2 * * *
  65557. **
  65558. ** Allocate a new table in the main database file if P1==0 or in the
  65559. ** auxiliary database file if P1==1 or in an attached database if
  65560. ** P1>1. Write the root page number of the new table into
  65561. ** register P2
  65562. **
  65563. ** The difference between a table and an index is this: A table must
  65564. ** have a 4-byte integer key and can have arbitrary data. An index
  65565. ** has an arbitrary key but no data.
  65566. **
  65567. ** See also: CreateIndex
  65568. */
  65569. /* Opcode: CreateIndex P1 P2 * * *
  65570. **
  65571. ** Allocate a new index in the main database file if P1==0 or in the
  65572. ** auxiliary database file if P1==1 or in an attached database if
  65573. ** P1>1. Write the root page number of the new table into
  65574. ** register P2.
  65575. **
  65576. ** See documentation on OP_CreateTable for additional information.
  65577. */
  65578. case OP_CreateIndex: /* out2-prerelease */
  65579. case OP_CreateTable: { /* out2-prerelease */
  65580. #if 0 /* local variables moved into u.by */
  65581. int pgno;
  65582. int flags;
  65583. Db *pDb;
  65584. #endif /* local variables moved into u.by */
  65585. u.by.pgno = 0;
  65586. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  65587. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  65588. u.by.pDb = &db->aDb[pOp->p1];
  65589. assert( u.by.pDb->pBt!=0 );
  65590. if( pOp->opcode==OP_CreateTable ){
  65591. /* u.by.flags = BTREE_INTKEY; */
  65592. u.by.flags = BTREE_INTKEY;
  65593. }else{
  65594. u.by.flags = BTREE_BLOBKEY;
  65595. }
  65596. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  65597. pOut->u.i = u.by.pgno;
  65598. break;
  65599. }
  65600. /* Opcode: ParseSchema P1 * * P4 *
  65601. **
  65602. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  65603. ** that match the WHERE clause P4.
  65604. **
  65605. ** This opcode invokes the parser to create a new virtual machine,
  65606. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  65607. */
  65608. case OP_ParseSchema: {
  65609. #if 0 /* local variables moved into u.bz */
  65610. int iDb;
  65611. const char *zMaster;
  65612. char *zSql;
  65613. InitData initData;
  65614. #endif /* local variables moved into u.bz */
  65615. /* Any prepared statement that invokes this opcode will hold mutexes
  65616. ** on every btree. This is a prerequisite for invoking
  65617. ** sqlite3InitCallback().
  65618. */
  65619. #ifdef SQLITE_DEBUG
  65620. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  65621. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  65622. }
  65623. #endif
  65624. u.bz.iDb = pOp->p1;
  65625. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  65626. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  65627. /* Used to be a conditional */ {
  65628. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  65629. u.bz.initData.db = db;
  65630. u.bz.initData.iDb = pOp->p1;
  65631. u.bz.initData.pzErrMsg = &p->zErrMsg;
  65632. u.bz.zSql = sqlite3MPrintf(db,
  65633. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  65634. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  65635. if( u.bz.zSql==0 ){
  65636. rc = SQLITE_NOMEM;
  65637. }else{
  65638. assert( db->init.busy==0 );
  65639. db->init.busy = 1;
  65640. u.bz.initData.rc = SQLITE_OK;
  65641. assert( !db->mallocFailed );
  65642. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  65643. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  65644. sqlite3DbFree(db, u.bz.zSql);
  65645. db->init.busy = 0;
  65646. }
  65647. }
  65648. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  65649. if( rc==SQLITE_NOMEM ){
  65650. goto no_mem;
  65651. }
  65652. break;
  65653. }
  65654. #if !defined(SQLITE_OMIT_ANALYZE)
  65655. /* Opcode: LoadAnalysis P1 * * * *
  65656. **
  65657. ** Read the sqlite_stat1 table for database P1 and load the content
  65658. ** of that table into the internal index hash table. This will cause
  65659. ** the analysis to be used when preparing all subsequent queries.
  65660. */
  65661. case OP_LoadAnalysis: {
  65662. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  65663. rc = sqlite3AnalysisLoad(db, pOp->p1);
  65664. break;
  65665. }
  65666. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  65667. /* Opcode: DropTable P1 * * P4 *
  65668. **
  65669. ** Remove the internal (in-memory) data structures that describe
  65670. ** the table named P4 in database P1. This is called after a table
  65671. ** is dropped in order to keep the internal representation of the
  65672. ** schema consistent with what is on disk.
  65673. */
  65674. case OP_DropTable: {
  65675. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  65676. break;
  65677. }
  65678. /* Opcode: DropIndex P1 * * P4 *
  65679. **
  65680. ** Remove the internal (in-memory) data structures that describe
  65681. ** the index named P4 in database P1. This is called after an index
  65682. ** is dropped in order to keep the internal representation of the
  65683. ** schema consistent with what is on disk.
  65684. */
  65685. case OP_DropIndex: {
  65686. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  65687. break;
  65688. }
  65689. /* Opcode: DropTrigger P1 * * P4 *
  65690. **
  65691. ** Remove the internal (in-memory) data structures that describe
  65692. ** the trigger named P4 in database P1. This is called after a trigger
  65693. ** is dropped in order to keep the internal representation of the
  65694. ** schema consistent with what is on disk.
  65695. */
  65696. case OP_DropTrigger: {
  65697. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  65698. break;
  65699. }
  65700. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  65701. /* Opcode: IntegrityCk P1 P2 P3 * P5
  65702. **
  65703. ** Do an analysis of the currently open database. Store in
  65704. ** register P1 the text of an error message describing any problems.
  65705. ** If no problems are found, store a NULL in register P1.
  65706. **
  65707. ** The register P3 contains the maximum number of allowed errors.
  65708. ** At most reg(P3) errors will be reported.
  65709. ** In other words, the analysis stops as soon as reg(P1) errors are
  65710. ** seen. Reg(P1) is updated with the number of errors remaining.
  65711. **
  65712. ** The root page numbers of all tables in the database are integer
  65713. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  65714. ** total.
  65715. **
  65716. ** If P5 is not zero, the check is done on the auxiliary database
  65717. ** file, not the main database file.
  65718. **
  65719. ** This opcode is used to implement the integrity_check pragma.
  65720. */
  65721. case OP_IntegrityCk: {
  65722. #if 0 /* local variables moved into u.ca */
  65723. int nRoot; /* Number of tables to check. (Number of root pages.) */
  65724. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  65725. int j; /* Loop counter */
  65726. int nErr; /* Number of errors reported */
  65727. char *z; /* Text of the error report */
  65728. Mem *pnErr; /* Register keeping track of errors remaining */
  65729. #endif /* local variables moved into u.ca */
  65730. u.ca.nRoot = pOp->p2;
  65731. assert( u.ca.nRoot>0 );
  65732. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  65733. if( u.ca.aRoot==0 ) goto no_mem;
  65734. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  65735. u.ca.pnErr = &aMem[pOp->p3];
  65736. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  65737. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  65738. pIn1 = &aMem[pOp->p1];
  65739. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  65740. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  65741. }
  65742. u.ca.aRoot[u.ca.j] = 0;
  65743. assert( pOp->p5<db->nDb );
  65744. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  65745. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  65746. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  65747. sqlite3DbFree(db, u.ca.aRoot);
  65748. u.ca.pnErr->u.i -= u.ca.nErr;
  65749. sqlite3VdbeMemSetNull(pIn1);
  65750. if( u.ca.nErr==0 ){
  65751. assert( u.ca.z==0 );
  65752. }else if( u.ca.z==0 ){
  65753. goto no_mem;
  65754. }else{
  65755. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  65756. }
  65757. UPDATE_MAX_BLOBSIZE(pIn1);
  65758. sqlite3VdbeChangeEncoding(pIn1, encoding);
  65759. break;
  65760. }
  65761. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  65762. /* Opcode: RowSetAdd P1 P2 * * *
  65763. **
  65764. ** Insert the integer value held by register P2 into a boolean index
  65765. ** held in register P1.
  65766. **
  65767. ** An assertion fails if P2 is not an integer.
  65768. */
  65769. case OP_RowSetAdd: { /* in1, in2 */
  65770. pIn1 = &aMem[pOp->p1];
  65771. pIn2 = &aMem[pOp->p2];
  65772. assert( (pIn2->flags & MEM_Int)!=0 );
  65773. if( (pIn1->flags & MEM_RowSet)==0 ){
  65774. sqlite3VdbeMemSetRowSet(pIn1);
  65775. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  65776. }
  65777. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  65778. break;
  65779. }
  65780. /* Opcode: RowSetRead P1 P2 P3 * *
  65781. **
  65782. ** Extract the smallest value from boolean index P1 and put that value into
  65783. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  65784. ** unchanged and jump to instruction P2.
  65785. */
  65786. case OP_RowSetRead: { /* jump, in1, out3 */
  65787. #if 0 /* local variables moved into u.cb */
  65788. i64 val;
  65789. #endif /* local variables moved into u.cb */
  65790. CHECK_FOR_INTERRUPT;
  65791. pIn1 = &aMem[pOp->p1];
  65792. if( (pIn1->flags & MEM_RowSet)==0
  65793. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  65794. ){
  65795. /* The boolean index is empty */
  65796. sqlite3VdbeMemSetNull(pIn1);
  65797. pc = pOp->p2 - 1;
  65798. }else{
  65799. /* A value was pulled from the index */
  65800. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  65801. }
  65802. break;
  65803. }
  65804. /* Opcode: RowSetTest P1 P2 P3 P4
  65805. **
  65806. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  65807. ** contains a RowSet object and that RowSet object contains
  65808. ** the value held in P3, jump to register P2. Otherwise, insert the
  65809. ** integer in P3 into the RowSet and continue on to the
  65810. ** next opcode.
  65811. **
  65812. ** The RowSet object is optimized for the case where successive sets
  65813. ** of integers, where each set contains no duplicates. Each set
  65814. ** of values is identified by a unique P4 value. The first set
  65815. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  65816. ** non-negative. For non-negative values of P4 only the lower 4
  65817. ** bits are significant.
  65818. **
  65819. ** This allows optimizations: (a) when P4==0 there is no need to test
  65820. ** the rowset object for P3, as it is guaranteed not to contain it,
  65821. ** (b) when P4==-1 there is no need to insert the value, as it will
  65822. ** never be tested for, and (c) when a value that is part of set X is
  65823. ** inserted, there is no need to search to see if the same value was
  65824. ** previously inserted as part of set X (only if it was previously
  65825. ** inserted as part of some other set).
  65826. */
  65827. case OP_RowSetTest: { /* jump, in1, in3 */
  65828. #if 0 /* local variables moved into u.cc */
  65829. int iSet;
  65830. int exists;
  65831. #endif /* local variables moved into u.cc */
  65832. pIn1 = &aMem[pOp->p1];
  65833. pIn3 = &aMem[pOp->p3];
  65834. u.cc.iSet = pOp->p4.i;
  65835. assert( pIn3->flags&MEM_Int );
  65836. /* If there is anything other than a rowset object in memory cell P1,
  65837. ** delete it now and initialize P1 with an empty rowset
  65838. */
  65839. if( (pIn1->flags & MEM_RowSet)==0 ){
  65840. sqlite3VdbeMemSetRowSet(pIn1);
  65841. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  65842. }
  65843. assert( pOp->p4type==P4_INT32 );
  65844. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  65845. if( u.cc.iSet ){
  65846. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  65847. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  65848. pIn3->u.i);
  65849. if( u.cc.exists ){
  65850. pc = pOp->p2 - 1;
  65851. break;
  65852. }
  65853. }
  65854. if( u.cc.iSet>=0 ){
  65855. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  65856. }
  65857. break;
  65858. }
  65859. #ifndef SQLITE_OMIT_TRIGGER
  65860. /* Opcode: Program P1 P2 P3 P4 *
  65861. **
  65862. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  65863. **
  65864. ** P1 contains the address of the memory cell that contains the first memory
  65865. ** cell in an array of values used as arguments to the sub-program. P2
  65866. ** contains the address to jump to if the sub-program throws an IGNORE
  65867. ** exception using the RAISE() function. Register P3 contains the address
  65868. ** of a memory cell in this (the parent) VM that is used to allocate the
  65869. ** memory required by the sub-vdbe at runtime.
  65870. **
  65871. ** P4 is a pointer to the VM containing the trigger program.
  65872. */
  65873. case OP_Program: { /* jump */
  65874. #if 0 /* local variables moved into u.cd */
  65875. int nMem; /* Number of memory registers for sub-program */
  65876. int nByte; /* Bytes of runtime space required for sub-program */
  65877. Mem *pRt; /* Register to allocate runtime space */
  65878. Mem *pMem; /* Used to iterate through memory cells */
  65879. Mem *pEnd; /* Last memory cell in new array */
  65880. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  65881. SubProgram *pProgram; /* Sub-program to execute */
  65882. void *t; /* Token identifying trigger */
  65883. #endif /* local variables moved into u.cd */
  65884. u.cd.pProgram = pOp->p4.pProgram;
  65885. u.cd.pRt = &aMem[pOp->p3];
  65886. assert( u.cd.pProgram->nOp>0 );
  65887. /* If the p5 flag is clear, then recursive invocation of triggers is
  65888. ** disabled for backwards compatibility (p5 is set if this sub-program
  65889. ** is really a trigger, not a foreign key action, and the flag set
  65890. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  65891. **
  65892. ** It is recursive invocation of triggers, at the SQL level, that is
  65893. ** disabled. In some cases a single trigger may generate more than one
  65894. ** SubProgram (if the trigger may be executed with more than one different
  65895. ** ON CONFLICT algorithm). SubProgram structures associated with a
  65896. ** single trigger all have the same value for the SubProgram.token
  65897. ** variable. */
  65898. if( pOp->p5 ){
  65899. u.cd.t = u.cd.pProgram->token;
  65900. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  65901. if( u.cd.pFrame ) break;
  65902. }
  65903. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  65904. rc = SQLITE_ERROR;
  65905. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  65906. break;
  65907. }
  65908. /* Register u.cd.pRt is used to store the memory required to save the state
  65909. ** of the current program, and the memory required at runtime to execute
  65910. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  65911. ** is already allocated. Otherwise, it must be initialized. */
  65912. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  65913. /* SubProgram.nMem is set to the number of memory cells used by the
  65914. ** program stored in SubProgram.aOp. As well as these, one memory
  65915. ** cell is required for each cursor used by the program. Set local
  65916. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  65917. */
  65918. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  65919. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  65920. + u.cd.nMem * sizeof(Mem)
  65921. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  65922. + u.cd.pProgram->nOnce * sizeof(u8);
  65923. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  65924. if( !u.cd.pFrame ){
  65925. goto no_mem;
  65926. }
  65927. sqlite3VdbeMemRelease(u.cd.pRt);
  65928. u.cd.pRt->flags = MEM_Frame;
  65929. u.cd.pRt->u.pFrame = u.cd.pFrame;
  65930. u.cd.pFrame->v = p;
  65931. u.cd.pFrame->nChildMem = u.cd.nMem;
  65932. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  65933. u.cd.pFrame->pc = pc;
  65934. u.cd.pFrame->aMem = p->aMem;
  65935. u.cd.pFrame->nMem = p->nMem;
  65936. u.cd.pFrame->apCsr = p->apCsr;
  65937. u.cd.pFrame->nCursor = p->nCursor;
  65938. u.cd.pFrame->aOp = p->aOp;
  65939. u.cd.pFrame->nOp = p->nOp;
  65940. u.cd.pFrame->token = u.cd.pProgram->token;
  65941. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  65942. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  65943. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  65944. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  65945. u.cd.pMem->flags = MEM_Invalid;
  65946. u.cd.pMem->db = db;
  65947. }
  65948. }else{
  65949. u.cd.pFrame = u.cd.pRt->u.pFrame;
  65950. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  65951. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  65952. assert( pc==u.cd.pFrame->pc );
  65953. }
  65954. p->nFrame++;
  65955. u.cd.pFrame->pParent = p->pFrame;
  65956. u.cd.pFrame->lastRowid = lastRowid;
  65957. u.cd.pFrame->nChange = p->nChange;
  65958. p->nChange = 0;
  65959. p->pFrame = u.cd.pFrame;
  65960. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  65961. p->nMem = u.cd.pFrame->nChildMem;
  65962. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  65963. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  65964. p->aOp = aOp = u.cd.pProgram->aOp;
  65965. p->nOp = u.cd.pProgram->nOp;
  65966. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  65967. p->nOnceFlag = u.cd.pProgram->nOnce;
  65968. pc = -1;
  65969. memset(p->aOnceFlag, 0, p->nOnceFlag);
  65970. break;
  65971. }
  65972. /* Opcode: Param P1 P2 * * *
  65973. **
  65974. ** This opcode is only ever present in sub-programs called via the
  65975. ** OP_Program instruction. Copy a value currently stored in a memory
  65976. ** cell of the calling (parent) frame to cell P2 in the current frames
  65977. ** address space. This is used by trigger programs to access the new.*
  65978. ** and old.* values.
  65979. **
  65980. ** The address of the cell in the parent frame is determined by adding
  65981. ** the value of the P1 argument to the value of the P1 argument to the
  65982. ** calling OP_Program instruction.
  65983. */
  65984. case OP_Param: { /* out2-prerelease */
  65985. #if 0 /* local variables moved into u.ce */
  65986. VdbeFrame *pFrame;
  65987. Mem *pIn;
  65988. #endif /* local variables moved into u.ce */
  65989. u.ce.pFrame = p->pFrame;
  65990. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  65991. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  65992. break;
  65993. }
  65994. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  65995. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65996. /* Opcode: FkCounter P1 P2 * * *
  65997. **
  65998. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  65999. ** If P1 is non-zero, the database constraint counter is incremented
  66000. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  66001. ** statement counter is incremented (immediate foreign key constraints).
  66002. */
  66003. case OP_FkCounter: {
  66004. if( pOp->p1 ){
  66005. db->nDeferredCons += pOp->p2;
  66006. }else{
  66007. p->nFkConstraint += pOp->p2;
  66008. }
  66009. break;
  66010. }
  66011. /* Opcode: FkIfZero P1 P2 * * *
  66012. **
  66013. ** This opcode tests if a foreign key constraint-counter is currently zero.
  66014. ** If so, jump to instruction P2. Otherwise, fall through to the next
  66015. ** instruction.
  66016. **
  66017. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  66018. ** is zero (the one that counts deferred constraint violations). If P1 is
  66019. ** zero, the jump is taken if the statement constraint-counter is zero
  66020. ** (immediate foreign key constraint violations).
  66021. */
  66022. case OP_FkIfZero: { /* jump */
  66023. if( pOp->p1 ){
  66024. if( db->nDeferredCons==0 ) pc = pOp->p2-1;
  66025. }else{
  66026. if( p->nFkConstraint==0 ) pc = pOp->p2-1;
  66027. }
  66028. break;
  66029. }
  66030. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  66031. #ifndef SQLITE_OMIT_AUTOINCREMENT
  66032. /* Opcode: MemMax P1 P2 * * *
  66033. **
  66034. ** P1 is a register in the root frame of this VM (the root frame is
  66035. ** different from the current frame if this instruction is being executed
  66036. ** within a sub-program). Set the value of register P1 to the maximum of
  66037. ** its current value and the value in register P2.
  66038. **
  66039. ** This instruction throws an error if the memory cell is not initially
  66040. ** an integer.
  66041. */
  66042. case OP_MemMax: { /* in2 */
  66043. #if 0 /* local variables moved into u.cf */
  66044. Mem *pIn1;
  66045. VdbeFrame *pFrame;
  66046. #endif /* local variables moved into u.cf */
  66047. if( p->pFrame ){
  66048. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  66049. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  66050. }else{
  66051. u.cf.pIn1 = &aMem[pOp->p1];
  66052. }
  66053. assert( memIsValid(u.cf.pIn1) );
  66054. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  66055. pIn2 = &aMem[pOp->p2];
  66056. sqlite3VdbeMemIntegerify(pIn2);
  66057. if( u.cf.pIn1->u.i<pIn2->u.i){
  66058. u.cf.pIn1->u.i = pIn2->u.i;
  66059. }
  66060. break;
  66061. }
  66062. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  66063. /* Opcode: IfPos P1 P2 * * *
  66064. **
  66065. ** If the value of register P1 is 1 or greater, jump to P2.
  66066. **
  66067. ** It is illegal to use this instruction on a register that does
  66068. ** not contain an integer. An assertion fault will result if you try.
  66069. */
  66070. case OP_IfPos: { /* jump, in1 */
  66071. pIn1 = &aMem[pOp->p1];
  66072. assert( pIn1->flags&MEM_Int );
  66073. if( pIn1->u.i>0 ){
  66074. pc = pOp->p2 - 1;
  66075. }
  66076. break;
  66077. }
  66078. /* Opcode: IfNeg P1 P2 * * *
  66079. **
  66080. ** If the value of register P1 is less than zero, jump to P2.
  66081. **
  66082. ** It is illegal to use this instruction on a register that does
  66083. ** not contain an integer. An assertion fault will result if you try.
  66084. */
  66085. case OP_IfNeg: { /* jump, in1 */
  66086. pIn1 = &aMem[pOp->p1];
  66087. assert( pIn1->flags&MEM_Int );
  66088. if( pIn1->u.i<0 ){
  66089. pc = pOp->p2 - 1;
  66090. }
  66091. break;
  66092. }
  66093. /* Opcode: IfZero P1 P2 P3 * *
  66094. **
  66095. ** The register P1 must contain an integer. Add literal P3 to the
  66096. ** value in register P1. If the result is exactly 0, jump to P2.
  66097. **
  66098. ** It is illegal to use this instruction on a register that does
  66099. ** not contain an integer. An assertion fault will result if you try.
  66100. */
  66101. case OP_IfZero: { /* jump, in1 */
  66102. pIn1 = &aMem[pOp->p1];
  66103. assert( pIn1->flags&MEM_Int );
  66104. pIn1->u.i += pOp->p3;
  66105. if( pIn1->u.i==0 ){
  66106. pc = pOp->p2 - 1;
  66107. }
  66108. break;
  66109. }
  66110. /* Opcode: AggStep * P2 P3 P4 P5
  66111. **
  66112. ** Execute the step function for an aggregate. The
  66113. ** function has P5 arguments. P4 is a pointer to the FuncDef
  66114. ** structure that specifies the function. Use register
  66115. ** P3 as the accumulator.
  66116. **
  66117. ** The P5 arguments are taken from register P2 and its
  66118. ** successors.
  66119. */
  66120. case OP_AggStep: {
  66121. #if 0 /* local variables moved into u.cg */
  66122. int n;
  66123. int i;
  66124. Mem *pMem;
  66125. Mem *pRec;
  66126. sqlite3_context ctx;
  66127. sqlite3_value **apVal;
  66128. #endif /* local variables moved into u.cg */
  66129. u.cg.n = pOp->p5;
  66130. assert( u.cg.n>=0 );
  66131. u.cg.pRec = &aMem[pOp->p2];
  66132. u.cg.apVal = p->apArg;
  66133. assert( u.cg.apVal || u.cg.n==0 );
  66134. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  66135. assert( memIsValid(u.cg.pRec) );
  66136. u.cg.apVal[u.cg.i] = u.cg.pRec;
  66137. memAboutToChange(p, u.cg.pRec);
  66138. sqlite3VdbeMemStoreType(u.cg.pRec);
  66139. }
  66140. u.cg.ctx.pFunc = pOp->p4.pFunc;
  66141. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  66142. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  66143. u.cg.pMem->n++;
  66144. u.cg.ctx.s.flags = MEM_Null;
  66145. u.cg.ctx.s.z = 0;
  66146. u.cg.ctx.s.zMalloc = 0;
  66147. u.cg.ctx.s.xDel = 0;
  66148. u.cg.ctx.s.db = db;
  66149. u.cg.ctx.isError = 0;
  66150. u.cg.ctx.pColl = 0;
  66151. u.cg.ctx.skipFlag = 0;
  66152. if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  66153. assert( pOp>p->aOp );
  66154. assert( pOp[-1].p4type==P4_COLLSEQ );
  66155. assert( pOp[-1].opcode==OP_CollSeq );
  66156. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  66157. }
  66158. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  66159. if( u.cg.ctx.isError ){
  66160. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  66161. rc = u.cg.ctx.isError;
  66162. }
  66163. if( u.cg.ctx.skipFlag ){
  66164. assert( pOp[-1].opcode==OP_CollSeq );
  66165. u.cg.i = pOp[-1].p1;
  66166. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  66167. }
  66168. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  66169. break;
  66170. }
  66171. /* Opcode: AggFinal P1 P2 * P4 *
  66172. **
  66173. ** Execute the finalizer function for an aggregate. P1 is
  66174. ** the memory location that is the accumulator for the aggregate.
  66175. **
  66176. ** P2 is the number of arguments that the step function takes and
  66177. ** P4 is a pointer to the FuncDef for this function. The P2
  66178. ** argument is not used by this opcode. It is only there to disambiguate
  66179. ** functions that can take varying numbers of arguments. The
  66180. ** P4 argument is only needed for the degenerate case where
  66181. ** the step function was not previously called.
  66182. */
  66183. case OP_AggFinal: {
  66184. #if 0 /* local variables moved into u.ch */
  66185. Mem *pMem;
  66186. #endif /* local variables moved into u.ch */
  66187. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  66188. u.ch.pMem = &aMem[pOp->p1];
  66189. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  66190. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  66191. if( rc ){
  66192. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  66193. }
  66194. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  66195. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  66196. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  66197. goto too_big;
  66198. }
  66199. break;
  66200. }
  66201. #ifndef SQLITE_OMIT_WAL
  66202. /* Opcode: Checkpoint P1 P2 P3 * *
  66203. **
  66204. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  66205. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  66206. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  66207. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  66208. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  66209. ** in the WAL that have been checkpointed after the checkpoint
  66210. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  66211. ** mem[P3+2] are initialized to -1.
  66212. */
  66213. case OP_Checkpoint: {
  66214. #if 0 /* local variables moved into u.ci */
  66215. int i; /* Loop counter */
  66216. int aRes[3]; /* Results */
  66217. Mem *pMem; /* Write results here */
  66218. #endif /* local variables moved into u.ci */
  66219. u.ci.aRes[0] = 0;
  66220. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  66221. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  66222. || pOp->p2==SQLITE_CHECKPOINT_FULL
  66223. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  66224. );
  66225. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  66226. if( rc==SQLITE_BUSY ){
  66227. rc = SQLITE_OK;
  66228. u.ci.aRes[0] = 1;
  66229. }
  66230. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  66231. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  66232. }
  66233. break;
  66234. };
  66235. #endif
  66236. #ifndef SQLITE_OMIT_PRAGMA
  66237. /* Opcode: JournalMode P1 P2 P3 * P5
  66238. **
  66239. ** Change the journal mode of database P1 to P3. P3 must be one of the
  66240. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  66241. ** modes (delete, truncate, persist, off and memory), this is a simple
  66242. ** operation. No IO is required.
  66243. **
  66244. ** If changing into or out of WAL mode the procedure is more complicated.
  66245. **
  66246. ** Write a string containing the final journal-mode to register P2.
  66247. */
  66248. case OP_JournalMode: { /* out2-prerelease */
  66249. #if 0 /* local variables moved into u.cj */
  66250. Btree *pBt; /* Btree to change journal mode of */
  66251. Pager *pPager; /* Pager associated with pBt */
  66252. int eNew; /* New journal mode */
  66253. int eOld; /* The old journal mode */
  66254. #ifndef SQLITE_OMIT_WAL
  66255. const char *zFilename; /* Name of database file for pPager */
  66256. #endif
  66257. #endif /* local variables moved into u.cj */
  66258. u.cj.eNew = pOp->p3;
  66259. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  66260. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  66261. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  66262. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  66263. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  66264. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  66265. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  66266. );
  66267. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  66268. u.cj.pBt = db->aDb[pOp->p1].pBt;
  66269. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  66270. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  66271. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  66272. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  66273. #ifndef SQLITE_OMIT_WAL
  66274. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  66275. /* Do not allow a transition to journal_mode=WAL for a database
  66276. ** in temporary storage or if the VFS does not support shared memory
  66277. */
  66278. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  66279. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  66280. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  66281. ){
  66282. u.cj.eNew = u.cj.eOld;
  66283. }
  66284. if( (u.cj.eNew!=u.cj.eOld)
  66285. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  66286. ){
  66287. if( !db->autoCommit || db->activeVdbeCnt>1 ){
  66288. rc = SQLITE_ERROR;
  66289. sqlite3SetString(&p->zErrMsg, db,
  66290. "cannot change %s wal mode from within a transaction",
  66291. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  66292. );
  66293. break;
  66294. }else{
  66295. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  66296. /* If leaving WAL mode, close the log file. If successful, the call
  66297. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  66298. ** file. An EXCLUSIVE lock may still be held on the database file
  66299. ** after a successful return.
  66300. */
  66301. rc = sqlite3PagerCloseWal(u.cj.pPager);
  66302. if( rc==SQLITE_OK ){
  66303. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  66304. }
  66305. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  66306. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  66307. ** as an intermediate */
  66308. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  66309. }
  66310. /* Open a transaction on the database file. Regardless of the journal
  66311. ** mode, this transaction always uses a rollback journal.
  66312. */
  66313. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  66314. if( rc==SQLITE_OK ){
  66315. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  66316. }
  66317. }
  66318. }
  66319. #endif /* ifndef SQLITE_OMIT_WAL */
  66320. if( rc ){
  66321. u.cj.eNew = u.cj.eOld;
  66322. }
  66323. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  66324. pOut = &aMem[pOp->p2];
  66325. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  66326. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  66327. pOut->n = sqlite3Strlen30(pOut->z);
  66328. pOut->enc = SQLITE_UTF8;
  66329. sqlite3VdbeChangeEncoding(pOut, encoding);
  66330. break;
  66331. };
  66332. #endif /* SQLITE_OMIT_PRAGMA */
  66333. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  66334. /* Opcode: Vacuum * * * * *
  66335. **
  66336. ** Vacuum the entire database. This opcode will cause other virtual
  66337. ** machines to be created and run. It may not be called from within
  66338. ** a transaction.
  66339. */
  66340. case OP_Vacuum: {
  66341. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  66342. break;
  66343. }
  66344. #endif
  66345. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  66346. /* Opcode: IncrVacuum P1 P2 * * *
  66347. **
  66348. ** Perform a single step of the incremental vacuum procedure on
  66349. ** the P1 database. If the vacuum has finished, jump to instruction
  66350. ** P2. Otherwise, fall through to the next instruction.
  66351. */
  66352. case OP_IncrVacuum: { /* jump */
  66353. #if 0 /* local variables moved into u.ck */
  66354. Btree *pBt;
  66355. #endif /* local variables moved into u.ck */
  66356. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  66357. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  66358. u.ck.pBt = db->aDb[pOp->p1].pBt;
  66359. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  66360. if( rc==SQLITE_DONE ){
  66361. pc = pOp->p2 - 1;
  66362. rc = SQLITE_OK;
  66363. }
  66364. break;
  66365. }
  66366. #endif
  66367. /* Opcode: Expire P1 * * * *
  66368. **
  66369. ** Cause precompiled statements to become expired. An expired statement
  66370. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  66371. ** (via sqlite3_step()).
  66372. **
  66373. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  66374. ** then only the currently executing statement is affected.
  66375. */
  66376. case OP_Expire: {
  66377. if( !pOp->p1 ){
  66378. sqlite3ExpirePreparedStatements(db);
  66379. }else{
  66380. p->expired = 1;
  66381. }
  66382. break;
  66383. }
  66384. #ifndef SQLITE_OMIT_SHARED_CACHE
  66385. /* Opcode: TableLock P1 P2 P3 P4 *
  66386. **
  66387. ** Obtain a lock on a particular table. This instruction is only used when
  66388. ** the shared-cache feature is enabled.
  66389. **
  66390. ** P1 is the index of the database in sqlite3.aDb[] of the database
  66391. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  66392. ** a write lock if P3==1.
  66393. **
  66394. ** P2 contains the root-page of the table to lock.
  66395. **
  66396. ** P4 contains a pointer to the name of the table being locked. This is only
  66397. ** used to generate an error message if the lock cannot be obtained.
  66398. */
  66399. case OP_TableLock: {
  66400. u8 isWriteLock = (u8)pOp->p3;
  66401. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  66402. int p1 = pOp->p1;
  66403. assert( p1>=0 && p1<db->nDb );
  66404. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  66405. assert( isWriteLock==0 || isWriteLock==1 );
  66406. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  66407. if( (rc&0xFF)==SQLITE_LOCKED ){
  66408. const char *z = pOp->p4.z;
  66409. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  66410. }
  66411. }
  66412. break;
  66413. }
  66414. #endif /* SQLITE_OMIT_SHARED_CACHE */
  66415. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66416. /* Opcode: VBegin * * * P4 *
  66417. **
  66418. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  66419. ** xBegin method for that table.
  66420. **
  66421. ** Also, whether or not P4 is set, check that this is not being called from
  66422. ** within a callback to a virtual table xSync() method. If it is, the error
  66423. ** code will be set to SQLITE_LOCKED.
  66424. */
  66425. case OP_VBegin: {
  66426. #if 0 /* local variables moved into u.cl */
  66427. VTable *pVTab;
  66428. #endif /* local variables moved into u.cl */
  66429. u.cl.pVTab = pOp->p4.pVtab;
  66430. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  66431. if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
  66432. break;
  66433. }
  66434. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66435. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66436. /* Opcode: VCreate P1 * * P4 *
  66437. **
  66438. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  66439. ** for that table.
  66440. */
  66441. case OP_VCreate: {
  66442. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  66443. break;
  66444. }
  66445. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66446. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66447. /* Opcode: VDestroy P1 * * P4 *
  66448. **
  66449. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  66450. ** of that table.
  66451. */
  66452. case OP_VDestroy: {
  66453. p->inVtabMethod = 2;
  66454. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  66455. p->inVtabMethod = 0;
  66456. break;
  66457. }
  66458. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66459. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66460. /* Opcode: VOpen P1 * * P4 *
  66461. **
  66462. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  66463. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  66464. ** table and stores that cursor in P1.
  66465. */
  66466. case OP_VOpen: {
  66467. #if 0 /* local variables moved into u.cm */
  66468. VdbeCursor *pCur;
  66469. sqlite3_vtab_cursor *pVtabCursor;
  66470. sqlite3_vtab *pVtab;
  66471. sqlite3_module *pModule;
  66472. #endif /* local variables moved into u.cm */
  66473. u.cm.pCur = 0;
  66474. u.cm.pVtabCursor = 0;
  66475. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  66476. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  66477. assert(u.cm.pVtab && u.cm.pModule);
  66478. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  66479. importVtabErrMsg(p, u.cm.pVtab);
  66480. if( SQLITE_OK==rc ){
  66481. /* Initialize sqlite3_vtab_cursor base class */
  66482. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  66483. /* Initialize vdbe cursor object */
  66484. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  66485. if( u.cm.pCur ){
  66486. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  66487. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  66488. }else{
  66489. db->mallocFailed = 1;
  66490. u.cm.pModule->xClose(u.cm.pVtabCursor);
  66491. }
  66492. }
  66493. break;
  66494. }
  66495. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66496. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66497. /* Opcode: VFilter P1 P2 P3 P4 *
  66498. **
  66499. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  66500. ** the filtered result set is empty.
  66501. **
  66502. ** P4 is either NULL or a string that was generated by the xBestIndex
  66503. ** method of the module. The interpretation of the P4 string is left
  66504. ** to the module implementation.
  66505. **
  66506. ** This opcode invokes the xFilter method on the virtual table specified
  66507. ** by P1. The integer query plan parameter to xFilter is stored in register
  66508. ** P3. Register P3+1 stores the argc parameter to be passed to the
  66509. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  66510. ** additional parameters which are passed to
  66511. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  66512. **
  66513. ** A jump is made to P2 if the result set after filtering would be empty.
  66514. */
  66515. case OP_VFilter: { /* jump */
  66516. #if 0 /* local variables moved into u.cn */
  66517. int nArg;
  66518. int iQuery;
  66519. const sqlite3_module *pModule;
  66520. Mem *pQuery;
  66521. Mem *pArgc;
  66522. sqlite3_vtab_cursor *pVtabCursor;
  66523. sqlite3_vtab *pVtab;
  66524. VdbeCursor *pCur;
  66525. int res;
  66526. int i;
  66527. Mem **apArg;
  66528. #endif /* local variables moved into u.cn */
  66529. u.cn.pQuery = &aMem[pOp->p3];
  66530. u.cn.pArgc = &u.cn.pQuery[1];
  66531. u.cn.pCur = p->apCsr[pOp->p1];
  66532. assert( memIsValid(u.cn.pQuery) );
  66533. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  66534. assert( u.cn.pCur->pVtabCursor );
  66535. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  66536. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  66537. u.cn.pModule = u.cn.pVtab->pModule;
  66538. /* Grab the index number and argc parameters */
  66539. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  66540. u.cn.nArg = (int)u.cn.pArgc->u.i;
  66541. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  66542. /* Invoke the xFilter method */
  66543. {
  66544. u.cn.res = 0;
  66545. u.cn.apArg = p->apArg;
  66546. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  66547. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  66548. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  66549. }
  66550. p->inVtabMethod = 1;
  66551. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  66552. p->inVtabMethod = 0;
  66553. importVtabErrMsg(p, u.cn.pVtab);
  66554. if( rc==SQLITE_OK ){
  66555. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  66556. }
  66557. if( u.cn.res ){
  66558. pc = pOp->p2 - 1;
  66559. }
  66560. }
  66561. u.cn.pCur->nullRow = 0;
  66562. break;
  66563. }
  66564. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66565. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66566. /* Opcode: VColumn P1 P2 P3 * *
  66567. **
  66568. ** Store the value of the P2-th column of
  66569. ** the row of the virtual-table that the
  66570. ** P1 cursor is pointing to into register P3.
  66571. */
  66572. case OP_VColumn: {
  66573. #if 0 /* local variables moved into u.co */
  66574. sqlite3_vtab *pVtab;
  66575. const sqlite3_module *pModule;
  66576. Mem *pDest;
  66577. sqlite3_context sContext;
  66578. #endif /* local variables moved into u.co */
  66579. VdbeCursor *pCur = p->apCsr[pOp->p1];
  66580. assert( pCur->pVtabCursor );
  66581. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  66582. u.co.pDest = &aMem[pOp->p3];
  66583. memAboutToChange(p, u.co.pDest);
  66584. if( pCur->nullRow ){
  66585. sqlite3VdbeMemSetNull(u.co.pDest);
  66586. break;
  66587. }
  66588. u.co.pVtab = pCur->pVtabCursor->pVtab;
  66589. u.co.pModule = u.co.pVtab->pModule;
  66590. assert( u.co.pModule->xColumn );
  66591. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  66592. /* The output cell may already have a buffer allocated. Move
  66593. ** the current contents to u.co.sContext.s so in case the user-function
  66594. ** can use the already allocated buffer instead of allocating a
  66595. ** new one.
  66596. */
  66597. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  66598. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  66599. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  66600. importVtabErrMsg(p, u.co.pVtab);
  66601. if( u.co.sContext.isError ){
  66602. rc = u.co.sContext.isError;
  66603. }
  66604. /* Copy the result of the function to the P3 register. We
  66605. ** do this regardless of whether or not an error occurred to ensure any
  66606. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  66607. */
  66608. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  66609. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  66610. REGISTER_TRACE(pOp->p3, u.co.pDest);
  66611. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  66612. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  66613. goto too_big;
  66614. }
  66615. break;
  66616. }
  66617. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66618. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66619. /* Opcode: VNext P1 P2 * * *
  66620. **
  66621. ** Advance virtual table P1 to the next row in its result set and
  66622. ** jump to instruction P2. Or, if the virtual table has reached
  66623. ** the end of its result set, then fall through to the next instruction.
  66624. */
  66625. case OP_VNext: { /* jump */
  66626. #if 0 /* local variables moved into u.cp */
  66627. sqlite3_vtab *pVtab;
  66628. const sqlite3_module *pModule;
  66629. int res;
  66630. VdbeCursor *pCur;
  66631. #endif /* local variables moved into u.cp */
  66632. u.cp.res = 0;
  66633. u.cp.pCur = p->apCsr[pOp->p1];
  66634. assert( u.cp.pCur->pVtabCursor );
  66635. if( u.cp.pCur->nullRow ){
  66636. break;
  66637. }
  66638. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  66639. u.cp.pModule = u.cp.pVtab->pModule;
  66640. assert( u.cp.pModule->xNext );
  66641. /* Invoke the xNext() method of the module. There is no way for the
  66642. ** underlying implementation to return an error if one occurs during
  66643. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  66644. ** data is available) and the error code returned when xColumn or
  66645. ** some other method is next invoked on the save virtual table cursor.
  66646. */
  66647. p->inVtabMethod = 1;
  66648. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  66649. p->inVtabMethod = 0;
  66650. importVtabErrMsg(p, u.cp.pVtab);
  66651. if( rc==SQLITE_OK ){
  66652. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  66653. }
  66654. if( !u.cp.res ){
  66655. /* If there is data, jump to P2 */
  66656. pc = pOp->p2 - 1;
  66657. }
  66658. break;
  66659. }
  66660. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66661. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66662. /* Opcode: VRename P1 * * P4 *
  66663. **
  66664. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  66665. ** This opcode invokes the corresponding xRename method. The value
  66666. ** in register P1 is passed as the zName argument to the xRename method.
  66667. */
  66668. case OP_VRename: {
  66669. #if 0 /* local variables moved into u.cq */
  66670. sqlite3_vtab *pVtab;
  66671. Mem *pName;
  66672. #endif /* local variables moved into u.cq */
  66673. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  66674. u.cq.pName = &aMem[pOp->p1];
  66675. assert( u.cq.pVtab->pModule->xRename );
  66676. assert( memIsValid(u.cq.pName) );
  66677. REGISTER_TRACE(pOp->p1, u.cq.pName);
  66678. assert( u.cq.pName->flags & MEM_Str );
  66679. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  66680. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  66681. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  66682. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  66683. if( rc==SQLITE_OK ){
  66684. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  66685. importVtabErrMsg(p, u.cq.pVtab);
  66686. p->expired = 0;
  66687. }
  66688. break;
  66689. }
  66690. #endif
  66691. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66692. /* Opcode: VUpdate P1 P2 P3 P4 *
  66693. **
  66694. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  66695. ** This opcode invokes the corresponding xUpdate method. P2 values
  66696. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  66697. ** invocation. The value in register (P3+P2-1) corresponds to the
  66698. ** p2th element of the argv array passed to xUpdate.
  66699. **
  66700. ** The xUpdate method will do a DELETE or an INSERT or both.
  66701. ** The argv[0] element (which corresponds to memory cell P3)
  66702. ** is the rowid of a row to delete. If argv[0] is NULL then no
  66703. ** deletion occurs. The argv[1] element is the rowid of the new
  66704. ** row. This can be NULL to have the virtual table select the new
  66705. ** rowid for itself. The subsequent elements in the array are
  66706. ** the values of columns in the new row.
  66707. **
  66708. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  66709. ** a row to delete.
  66710. **
  66711. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  66712. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  66713. ** is set to the value of the rowid for the row just inserted.
  66714. */
  66715. case OP_VUpdate: {
  66716. #if 0 /* local variables moved into u.cr */
  66717. sqlite3_vtab *pVtab;
  66718. sqlite3_module *pModule;
  66719. int nArg;
  66720. int i;
  66721. sqlite_int64 rowid;
  66722. Mem **apArg;
  66723. Mem *pX;
  66724. #endif /* local variables moved into u.cr */
  66725. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  66726. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  66727. );
  66728. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  66729. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  66730. u.cr.nArg = pOp->p2;
  66731. assert( pOp->p4type==P4_VTAB );
  66732. if( ALWAYS(u.cr.pModule->xUpdate) ){
  66733. u8 vtabOnConflict = db->vtabOnConflict;
  66734. u.cr.apArg = p->apArg;
  66735. u.cr.pX = &aMem[pOp->p3];
  66736. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  66737. assert( memIsValid(u.cr.pX) );
  66738. memAboutToChange(p, u.cr.pX);
  66739. sqlite3VdbeMemStoreType(u.cr.pX);
  66740. u.cr.apArg[u.cr.i] = u.cr.pX;
  66741. u.cr.pX++;
  66742. }
  66743. db->vtabOnConflict = pOp->p5;
  66744. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  66745. db->vtabOnConflict = vtabOnConflict;
  66746. importVtabErrMsg(p, u.cr.pVtab);
  66747. if( rc==SQLITE_OK && pOp->p1 ){
  66748. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  66749. db->lastRowid = lastRowid = u.cr.rowid;
  66750. }
  66751. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  66752. if( pOp->p5==OE_Ignore ){
  66753. rc = SQLITE_OK;
  66754. }else{
  66755. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  66756. }
  66757. }else{
  66758. p->nChange++;
  66759. }
  66760. }
  66761. break;
  66762. }
  66763. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  66764. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  66765. /* Opcode: Pagecount P1 P2 * * *
  66766. **
  66767. ** Write the current number of pages in database P1 to memory cell P2.
  66768. */
  66769. case OP_Pagecount: { /* out2-prerelease */
  66770. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  66771. break;
  66772. }
  66773. #endif
  66774. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  66775. /* Opcode: MaxPgcnt P1 P2 P3 * *
  66776. **
  66777. ** Try to set the maximum page count for database P1 to the value in P3.
  66778. ** Do not let the maximum page count fall below the current page count and
  66779. ** do not change the maximum page count value if P3==0.
  66780. **
  66781. ** Store the maximum page count after the change in register P2.
  66782. */
  66783. case OP_MaxPgcnt: { /* out2-prerelease */
  66784. unsigned int newMax;
  66785. Btree *pBt;
  66786. pBt = db->aDb[pOp->p1].pBt;
  66787. newMax = 0;
  66788. if( pOp->p3 ){
  66789. newMax = sqlite3BtreeLastPage(pBt);
  66790. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  66791. }
  66792. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  66793. break;
  66794. }
  66795. #endif
  66796. #ifndef SQLITE_OMIT_TRACE
  66797. /* Opcode: Trace * * * P4 *
  66798. **
  66799. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  66800. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  66801. */
  66802. case OP_Trace: {
  66803. #if 0 /* local variables moved into u.cs */
  66804. char *zTrace;
  66805. char *z;
  66806. #endif /* local variables moved into u.cs */
  66807. if( db->xTrace
  66808. && !p->doingRerun
  66809. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  66810. ){
  66811. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  66812. db->xTrace(db->pTraceArg, u.cs.z);
  66813. sqlite3DbFree(db, u.cs.z);
  66814. }
  66815. #ifdef SQLITE_DEBUG
  66816. if( (db->flags & SQLITE_SqlTrace)!=0
  66817. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  66818. ){
  66819. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  66820. }
  66821. #endif /* SQLITE_DEBUG */
  66822. break;
  66823. }
  66824. #endif
  66825. /* Opcode: Noop * * * * *
  66826. **
  66827. ** Do nothing. This instruction is often useful as a jump
  66828. ** destination.
  66829. */
  66830. /*
  66831. ** The magic Explain opcode are only inserted when explain==2 (which
  66832. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  66833. ** This opcode records information from the optimizer. It is the
  66834. ** the same as a no-op. This opcodesnever appears in a real VM program.
  66835. */
  66836. default: { /* This is really OP_Noop and OP_Explain */
  66837. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  66838. break;
  66839. }
  66840. /*****************************************************************************
  66841. ** The cases of the switch statement above this line should all be indented
  66842. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  66843. ** readability. From this point on down, the normal indentation rules are
  66844. ** restored.
  66845. *****************************************************************************/
  66846. }
  66847. #ifdef VDBE_PROFILE
  66848. {
  66849. u64 elapsed = sqlite3Hwtime() - start;
  66850. pOp->cycles += elapsed;
  66851. pOp->cnt++;
  66852. #if 0
  66853. fprintf(stdout, "%10llu ", elapsed);
  66854. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  66855. #endif
  66856. }
  66857. #endif
  66858. /* The following code adds nothing to the actual functionality
  66859. ** of the program. It is only here for testing and debugging.
  66860. ** On the other hand, it does burn CPU cycles every time through
  66861. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  66862. */
  66863. #ifndef NDEBUG
  66864. assert( pc>=-1 && pc<p->nOp );
  66865. #ifdef SQLITE_DEBUG
  66866. if( p->trace ){
  66867. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  66868. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  66869. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  66870. }
  66871. if( pOp->opflags & OPFLG_OUT3 ){
  66872. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  66873. }
  66874. }
  66875. #endif /* SQLITE_DEBUG */
  66876. #endif /* NDEBUG */
  66877. } /* The end of the for(;;) loop the loops through opcodes */
  66878. /* If we reach this point, it means that execution is finished with
  66879. ** an error of some kind.
  66880. */
  66881. vdbe_error_halt:
  66882. assert( rc );
  66883. p->rc = rc;
  66884. testcase( sqlite3GlobalConfig.xLog!=0 );
  66885. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  66886. pc, p->zSql, p->zErrMsg);
  66887. sqlite3VdbeHalt(p);
  66888. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  66889. rc = SQLITE_ERROR;
  66890. if( resetSchemaOnFault>0 ){
  66891. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  66892. }
  66893. /* This is the only way out of this procedure. We have to
  66894. ** release the mutexes on btrees that were acquired at the
  66895. ** top. */
  66896. vdbe_return:
  66897. db->lastRowid = lastRowid;
  66898. sqlite3VdbeLeave(p);
  66899. return rc;
  66900. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  66901. ** is encountered.
  66902. */
  66903. too_big:
  66904. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  66905. rc = SQLITE_TOOBIG;
  66906. goto vdbe_error_halt;
  66907. /* Jump to here if a malloc() fails.
  66908. */
  66909. no_mem:
  66910. db->mallocFailed = 1;
  66911. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  66912. rc = SQLITE_NOMEM;
  66913. goto vdbe_error_halt;
  66914. /* Jump to here for any other kind of fatal error. The "rc" variable
  66915. ** should hold the error number.
  66916. */
  66917. abort_due_to_error:
  66918. assert( p->zErrMsg==0 );
  66919. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  66920. if( rc!=SQLITE_IOERR_NOMEM ){
  66921. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  66922. }
  66923. goto vdbe_error_halt;
  66924. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  66925. ** flag.
  66926. */
  66927. abort_due_to_interrupt:
  66928. assert( db->u1.isInterrupted );
  66929. rc = SQLITE_INTERRUPT;
  66930. p->rc = rc;
  66931. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  66932. goto vdbe_error_halt;
  66933. }
  66934. /************** End of vdbe.c ************************************************/
  66935. /************** Begin file vdbeblob.c ****************************************/
  66936. /*
  66937. ** 2007 May 1
  66938. **
  66939. ** The author disclaims copyright to this source code. In place of
  66940. ** a legal notice, here is a blessing:
  66941. **
  66942. ** May you do good and not evil.
  66943. ** May you find forgiveness for yourself and forgive others.
  66944. ** May you share freely, never taking more than you give.
  66945. **
  66946. *************************************************************************
  66947. **
  66948. ** This file contains code used to implement incremental BLOB I/O.
  66949. */
  66950. #ifndef SQLITE_OMIT_INCRBLOB
  66951. /*
  66952. ** Valid sqlite3_blob* handles point to Incrblob structures.
  66953. */
  66954. typedef struct Incrblob Incrblob;
  66955. struct Incrblob {
  66956. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  66957. int nByte; /* Size of open blob, in bytes */
  66958. int iOffset; /* Byte offset of blob in cursor data */
  66959. int iCol; /* Table column this handle is open on */
  66960. BtCursor *pCsr; /* Cursor pointing at blob row */
  66961. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  66962. sqlite3 *db; /* The associated database */
  66963. };
  66964. /*
  66965. ** This function is used by both blob_open() and blob_reopen(). It seeks
  66966. ** the b-tree cursor associated with blob handle p to point to row iRow.
  66967. ** If successful, SQLITE_OK is returned and subsequent calls to
  66968. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  66969. **
  66970. ** If an error occurs, or if the specified row does not exist or does not
  66971. ** contain a value of type TEXT or BLOB in the column nominated when the
  66972. ** blob handle was opened, then an error code is returned and *pzErr may
  66973. ** be set to point to a buffer containing an error message. It is the
  66974. ** responsibility of the caller to free the error message buffer using
  66975. ** sqlite3DbFree().
  66976. **
  66977. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  66978. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  66979. ** immediately return SQLITE_ABORT.
  66980. */
  66981. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  66982. int rc; /* Error code */
  66983. char *zErr = 0; /* Error message */
  66984. Vdbe *v = (Vdbe *)p->pStmt;
  66985. /* Set the value of the SQL statements only variable to integer iRow.
  66986. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  66987. ** triggering asserts related to mutexes.
  66988. */
  66989. assert( v->aVar[0].flags&MEM_Int );
  66990. v->aVar[0].u.i = iRow;
  66991. rc = sqlite3_step(p->pStmt);
  66992. if( rc==SQLITE_ROW ){
  66993. u32 type = v->apCsr[0]->aType[p->iCol];
  66994. if( type<12 ){
  66995. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  66996. type==0?"null": type==7?"real": "integer"
  66997. );
  66998. rc = SQLITE_ERROR;
  66999. sqlite3_finalize(p->pStmt);
  67000. p->pStmt = 0;
  67001. }else{
  67002. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  67003. p->nByte = sqlite3VdbeSerialTypeLen(type);
  67004. p->pCsr = v->apCsr[0]->pCursor;
  67005. sqlite3BtreeEnterCursor(p->pCsr);
  67006. sqlite3BtreeCacheOverflow(p->pCsr);
  67007. sqlite3BtreeLeaveCursor(p->pCsr);
  67008. }
  67009. }
  67010. if( rc==SQLITE_ROW ){
  67011. rc = SQLITE_OK;
  67012. }else if( p->pStmt ){
  67013. rc = sqlite3_finalize(p->pStmt);
  67014. p->pStmt = 0;
  67015. if( rc==SQLITE_OK ){
  67016. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  67017. rc = SQLITE_ERROR;
  67018. }else{
  67019. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  67020. }
  67021. }
  67022. assert( rc!=SQLITE_OK || zErr==0 );
  67023. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  67024. *pzErr = zErr;
  67025. return rc;
  67026. }
  67027. /*
  67028. ** Open a blob handle.
  67029. */
  67030. SQLITE_API int sqlite3_blob_open(
  67031. sqlite3* db, /* The database connection */
  67032. const char *zDb, /* The attached database containing the blob */
  67033. const char *zTable, /* The table containing the blob */
  67034. const char *zColumn, /* The column containing the blob */
  67035. sqlite_int64 iRow, /* The row containing the glob */
  67036. int flags, /* True -> read/write access, false -> read-only */
  67037. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  67038. ){
  67039. int nAttempt = 0;
  67040. int iCol; /* Index of zColumn in row-record */
  67041. /* This VDBE program seeks a btree cursor to the identified
  67042. ** db/table/row entry. The reason for using a vdbe program instead
  67043. ** of writing code to use the b-tree layer directly is that the
  67044. ** vdbe program will take advantage of the various transaction,
  67045. ** locking and error handling infrastructure built into the vdbe.
  67046. **
  67047. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  67048. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  67049. ** uses it to implement the blob_read(), blob_write() and
  67050. ** blob_bytes() functions.
  67051. **
  67052. ** The sqlite3_blob_close() function finalizes the vdbe program,
  67053. ** which closes the b-tree cursor and (possibly) commits the
  67054. ** transaction.
  67055. */
  67056. static const VdbeOpList openBlob[] = {
  67057. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  67058. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  67059. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  67060. /* One of the following two instructions is replaced by an OP_Noop. */
  67061. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  67062. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  67063. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  67064. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  67065. {OP_Column, 0, 0, 1}, /* 7 */
  67066. {OP_ResultRow, 1, 0, 0}, /* 8 */
  67067. {OP_Goto, 0, 5, 0}, /* 9 */
  67068. {OP_Close, 0, 0, 0}, /* 10 */
  67069. {OP_Halt, 0, 0, 0}, /* 11 */
  67070. };
  67071. int rc = SQLITE_OK;
  67072. char *zErr = 0;
  67073. Table *pTab;
  67074. Parse *pParse = 0;
  67075. Incrblob *pBlob = 0;
  67076. flags = !!flags; /* flags = (flags ? 1 : 0); */
  67077. *ppBlob = 0;
  67078. sqlite3_mutex_enter(db->mutex);
  67079. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  67080. if( !pBlob ) goto blob_open_out;
  67081. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  67082. if( !pParse ) goto blob_open_out;
  67083. do {
  67084. memset(pParse, 0, sizeof(Parse));
  67085. pParse->db = db;
  67086. sqlite3DbFree(db, zErr);
  67087. zErr = 0;
  67088. sqlite3BtreeEnterAll(db);
  67089. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  67090. if( pTab && IsVirtual(pTab) ){
  67091. pTab = 0;
  67092. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  67093. }
  67094. #ifndef SQLITE_OMIT_VIEW
  67095. if( pTab && pTab->pSelect ){
  67096. pTab = 0;
  67097. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  67098. }
  67099. #endif
  67100. if( !pTab ){
  67101. if( pParse->zErrMsg ){
  67102. sqlite3DbFree(db, zErr);
  67103. zErr = pParse->zErrMsg;
  67104. pParse->zErrMsg = 0;
  67105. }
  67106. rc = SQLITE_ERROR;
  67107. sqlite3BtreeLeaveAll(db);
  67108. goto blob_open_out;
  67109. }
  67110. /* Now search pTab for the exact column. */
  67111. for(iCol=0; iCol<pTab->nCol; iCol++) {
  67112. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  67113. break;
  67114. }
  67115. }
  67116. if( iCol==pTab->nCol ){
  67117. sqlite3DbFree(db, zErr);
  67118. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  67119. rc = SQLITE_ERROR;
  67120. sqlite3BtreeLeaveAll(db);
  67121. goto blob_open_out;
  67122. }
  67123. /* If the value is being opened for writing, check that the
  67124. ** column is not indexed, and that it is not part of a foreign key.
  67125. ** It is against the rules to open a column to which either of these
  67126. ** descriptions applies for writing. */
  67127. if( flags ){
  67128. const char *zFault = 0;
  67129. Index *pIdx;
  67130. #ifndef SQLITE_OMIT_FOREIGN_KEY
  67131. if( db->flags&SQLITE_ForeignKeys ){
  67132. /* Check that the column is not part of an FK child key definition. It
  67133. ** is not necessary to check if it is part of a parent key, as parent
  67134. ** key columns must be indexed. The check below will pick up this
  67135. ** case. */
  67136. FKey *pFKey;
  67137. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  67138. int j;
  67139. for(j=0; j<pFKey->nCol; j++){
  67140. if( pFKey->aCol[j].iFrom==iCol ){
  67141. zFault = "foreign key";
  67142. }
  67143. }
  67144. }
  67145. }
  67146. #endif
  67147. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  67148. int j;
  67149. for(j=0; j<pIdx->nColumn; j++){
  67150. if( pIdx->aiColumn[j]==iCol ){
  67151. zFault = "indexed";
  67152. }
  67153. }
  67154. }
  67155. if( zFault ){
  67156. sqlite3DbFree(db, zErr);
  67157. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  67158. rc = SQLITE_ERROR;
  67159. sqlite3BtreeLeaveAll(db);
  67160. goto blob_open_out;
  67161. }
  67162. }
  67163. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  67164. assert( pBlob->pStmt || db->mallocFailed );
  67165. if( pBlob->pStmt ){
  67166. Vdbe *v = (Vdbe *)pBlob->pStmt;
  67167. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67168. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  67169. /* Configure the OP_Transaction */
  67170. sqlite3VdbeChangeP1(v, 0, iDb);
  67171. sqlite3VdbeChangeP2(v, 0, flags);
  67172. /* Configure the OP_VerifyCookie */
  67173. sqlite3VdbeChangeP1(v, 1, iDb);
  67174. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  67175. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  67176. /* Make sure a mutex is held on the table to be accessed */
  67177. sqlite3VdbeUsesBtree(v, iDb);
  67178. /* Configure the OP_TableLock instruction */
  67179. #ifdef SQLITE_OMIT_SHARED_CACHE
  67180. sqlite3VdbeChangeToNoop(v, 2);
  67181. #else
  67182. sqlite3VdbeChangeP1(v, 2, iDb);
  67183. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  67184. sqlite3VdbeChangeP3(v, 2, flags);
  67185. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  67186. #endif
  67187. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  67188. ** parameter of the other to pTab->tnum. */
  67189. sqlite3VdbeChangeToNoop(v, 4 - flags);
  67190. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  67191. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  67192. /* Configure the number of columns. Configure the cursor to
  67193. ** think that the table has one more column than it really
  67194. ** does. An OP_Column to retrieve this imaginary column will
  67195. ** always return an SQL NULL. This is useful because it means
  67196. ** we can invoke OP_Column to fill in the vdbe cursors type
  67197. ** and offset cache without causing any IO.
  67198. */
  67199. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  67200. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  67201. if( !db->mallocFailed ){
  67202. pParse->nVar = 1;
  67203. pParse->nMem = 1;
  67204. pParse->nTab = 1;
  67205. sqlite3VdbeMakeReady(v, pParse);
  67206. }
  67207. }
  67208. pBlob->flags = flags;
  67209. pBlob->iCol = iCol;
  67210. pBlob->db = db;
  67211. sqlite3BtreeLeaveAll(db);
  67212. if( db->mallocFailed ){
  67213. goto blob_open_out;
  67214. }
  67215. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  67216. rc = blobSeekToRow(pBlob, iRow, &zErr);
  67217. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  67218. blob_open_out:
  67219. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  67220. *ppBlob = (sqlite3_blob *)pBlob;
  67221. }else{
  67222. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  67223. sqlite3DbFree(db, pBlob);
  67224. }
  67225. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  67226. sqlite3DbFree(db, zErr);
  67227. sqlite3StackFree(db, pParse);
  67228. rc = sqlite3ApiExit(db, rc);
  67229. sqlite3_mutex_leave(db->mutex);
  67230. return rc;
  67231. }
  67232. /*
  67233. ** Close a blob handle that was previously created using
  67234. ** sqlite3_blob_open().
  67235. */
  67236. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  67237. Incrblob *p = (Incrblob *)pBlob;
  67238. int rc;
  67239. sqlite3 *db;
  67240. if( p ){
  67241. db = p->db;
  67242. sqlite3_mutex_enter(db->mutex);
  67243. rc = sqlite3_finalize(p->pStmt);
  67244. sqlite3DbFree(db, p);
  67245. sqlite3_mutex_leave(db->mutex);
  67246. }else{
  67247. rc = SQLITE_OK;
  67248. }
  67249. return rc;
  67250. }
  67251. /*
  67252. ** Perform a read or write operation on a blob
  67253. */
  67254. static int blobReadWrite(
  67255. sqlite3_blob *pBlob,
  67256. void *z,
  67257. int n,
  67258. int iOffset,
  67259. int (*xCall)(BtCursor*, u32, u32, void*)
  67260. ){
  67261. int rc;
  67262. Incrblob *p = (Incrblob *)pBlob;
  67263. Vdbe *v;
  67264. sqlite3 *db;
  67265. if( p==0 ) return SQLITE_MISUSE_BKPT;
  67266. db = p->db;
  67267. sqlite3_mutex_enter(db->mutex);
  67268. v = (Vdbe*)p->pStmt;
  67269. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  67270. /* Request is out of range. Return a transient error. */
  67271. rc = SQLITE_ERROR;
  67272. sqlite3Error(db, SQLITE_ERROR, 0);
  67273. }else if( v==0 ){
  67274. /* If there is no statement handle, then the blob-handle has
  67275. ** already been invalidated. Return SQLITE_ABORT in this case.
  67276. */
  67277. rc = SQLITE_ABORT;
  67278. }else{
  67279. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  67280. ** returned, clean-up the statement handle.
  67281. */
  67282. assert( db == v->db );
  67283. sqlite3BtreeEnterCursor(p->pCsr);
  67284. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  67285. sqlite3BtreeLeaveCursor(p->pCsr);
  67286. if( rc==SQLITE_ABORT ){
  67287. sqlite3VdbeFinalize(v);
  67288. p->pStmt = 0;
  67289. }else{
  67290. db->errCode = rc;
  67291. v->rc = rc;
  67292. }
  67293. }
  67294. rc = sqlite3ApiExit(db, rc);
  67295. sqlite3_mutex_leave(db->mutex);
  67296. return rc;
  67297. }
  67298. /*
  67299. ** Read data from a blob handle.
  67300. */
  67301. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  67302. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  67303. }
  67304. /*
  67305. ** Write data to a blob handle.
  67306. */
  67307. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  67308. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  67309. }
  67310. /*
  67311. ** Query a blob handle for the size of the data.
  67312. **
  67313. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  67314. ** so no mutex is required for access.
  67315. */
  67316. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  67317. Incrblob *p = (Incrblob *)pBlob;
  67318. return (p && p->pStmt) ? p->nByte : 0;
  67319. }
  67320. /*
  67321. ** Move an existing blob handle to point to a different row of the same
  67322. ** database table.
  67323. **
  67324. ** If an error occurs, or if the specified row does not exist or does not
  67325. ** contain a blob or text value, then an error code is returned and the
  67326. ** database handle error code and message set. If this happens, then all
  67327. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  67328. ** immediately return SQLITE_ABORT.
  67329. */
  67330. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  67331. int rc;
  67332. Incrblob *p = (Incrblob *)pBlob;
  67333. sqlite3 *db;
  67334. if( p==0 ) return SQLITE_MISUSE_BKPT;
  67335. db = p->db;
  67336. sqlite3_mutex_enter(db->mutex);
  67337. if( p->pStmt==0 ){
  67338. /* If there is no statement handle, then the blob-handle has
  67339. ** already been invalidated. Return SQLITE_ABORT in this case.
  67340. */
  67341. rc = SQLITE_ABORT;
  67342. }else{
  67343. char *zErr;
  67344. rc = blobSeekToRow(p, iRow, &zErr);
  67345. if( rc!=SQLITE_OK ){
  67346. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  67347. sqlite3DbFree(db, zErr);
  67348. }
  67349. assert( rc!=SQLITE_SCHEMA );
  67350. }
  67351. rc = sqlite3ApiExit(db, rc);
  67352. assert( rc==SQLITE_OK || p->pStmt==0 );
  67353. sqlite3_mutex_leave(db->mutex);
  67354. return rc;
  67355. }
  67356. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  67357. /************** End of vdbeblob.c ********************************************/
  67358. /************** Begin file vdbesort.c ****************************************/
  67359. /*
  67360. ** 2011 July 9
  67361. **
  67362. ** The author disclaims copyright to this source code. In place of
  67363. ** a legal notice, here is a blessing:
  67364. **
  67365. ** May you do good and not evil.
  67366. ** May you find forgiveness for yourself and forgive others.
  67367. ** May you share freely, never taking more than you give.
  67368. **
  67369. *************************************************************************
  67370. ** This file contains code for the VdbeSorter object, used in concert with
  67371. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  67372. ** example, by CREATE INDEX statements on tables too large to fit in main
  67373. ** memory).
  67374. */
  67375. typedef struct VdbeSorterIter VdbeSorterIter;
  67376. typedef struct SorterRecord SorterRecord;
  67377. typedef struct FileWriter FileWriter;
  67378. /*
  67379. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  67380. **
  67381. ** As keys are added to the sorter, they are written to disk in a series
  67382. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  67383. ** the same as the cache-size allowed for temporary databases. In order
  67384. ** to allow the caller to extract keys from the sorter in sorted order,
  67385. ** all PMAs currently stored on disk must be merged together. This comment
  67386. ** describes the data structure used to do so. The structure supports
  67387. ** merging any number of arrays in a single pass with no redundant comparison
  67388. ** operations.
  67389. **
  67390. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  67391. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  67392. ** the purposes of the paragraphs below, we assume that the array is actually
  67393. ** N elements in size, where N is the smallest power of 2 greater to or equal
  67394. ** to the number of iterators being merged. The extra aIter[] elements are
  67395. ** treated as if they are empty (always at EOF).
  67396. **
  67397. ** The aTree[] array is also N elements in size. The value of N is stored in
  67398. ** the VdbeSorter.nTree variable.
  67399. **
  67400. ** The final (N/2) elements of aTree[] contain the results of comparing
  67401. ** pairs of iterator keys together. Element i contains the result of
  67402. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  67403. ** aTree element is set to the index of it.
  67404. **
  67405. ** For the purposes of this comparison, EOF is considered greater than any
  67406. ** other key value. If the keys are equal (only possible with two EOF
  67407. ** values), it doesn't matter which index is stored.
  67408. **
  67409. ** The (N/4) elements of aTree[] that preceed the final (N/2) described
  67410. ** above contains the index of the smallest of each block of 4 iterators.
  67411. ** And so on. So that aTree[1] contains the index of the iterator that
  67412. ** currently points to the smallest key value. aTree[0] is unused.
  67413. **
  67414. ** Example:
  67415. **
  67416. ** aIter[0] -> Banana
  67417. ** aIter[1] -> Feijoa
  67418. ** aIter[2] -> Elderberry
  67419. ** aIter[3] -> Currant
  67420. ** aIter[4] -> Grapefruit
  67421. ** aIter[5] -> Apple
  67422. ** aIter[6] -> Durian
  67423. ** aIter[7] -> EOF
  67424. **
  67425. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  67426. **
  67427. ** The current element is "Apple" (the value of the key indicated by
  67428. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  67429. ** be advanced to the next key in its segment. Say the next key is
  67430. ** "Eggplant":
  67431. **
  67432. ** aIter[5] -> Eggplant
  67433. **
  67434. ** The contents of aTree[] are updated first by comparing the new iterator
  67435. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  67436. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  67437. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  67438. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  67439. ** so the value written into element 1 of the array is 0. As follows:
  67440. **
  67441. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  67442. **
  67443. ** In other words, each time we advance to the next sorter element, log2(N)
  67444. ** key comparison operations are required, where N is the number of segments
  67445. ** being merged (rounded up to the next power of 2).
  67446. */
  67447. struct VdbeSorter {
  67448. i64 iWriteOff; /* Current write offset within file pTemp1 */
  67449. i64 iReadOff; /* Current read offset within file pTemp1 */
  67450. int nInMemory; /* Current size of pRecord list as PMA */
  67451. int nTree; /* Used size of aTree/aIter (power of 2) */
  67452. int nPMA; /* Number of PMAs stored in pTemp1 */
  67453. int mnPmaSize; /* Minimum PMA size, in bytes */
  67454. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  67455. VdbeSorterIter *aIter; /* Array of iterators to merge */
  67456. int *aTree; /* Current state of incremental merge */
  67457. sqlite3_file *pTemp1; /* PMA file 1 */
  67458. SorterRecord *pRecord; /* Head of in-memory record list */
  67459. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  67460. };
  67461. /*
  67462. ** The following type is an iterator for a PMA. It caches the current key in
  67463. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  67464. */
  67465. struct VdbeSorterIter {
  67466. i64 iReadOff; /* Current read offset */
  67467. i64 iEof; /* 1 byte past EOF for this iterator */
  67468. int nAlloc; /* Bytes of space at aAlloc */
  67469. int nKey; /* Number of bytes in key */
  67470. sqlite3_file *pFile; /* File iterator is reading from */
  67471. u8 *aAlloc; /* Allocated space */
  67472. u8 *aKey; /* Pointer to current key */
  67473. u8 *aBuffer; /* Current read buffer */
  67474. int nBuffer; /* Size of read buffer in bytes */
  67475. };
  67476. /*
  67477. ** An instance of this structure is used to organize the stream of records
  67478. ** being written to files by the merge-sort code into aligned, page-sized
  67479. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  67480. ** faster on many operating systems.
  67481. */
  67482. struct FileWriter {
  67483. int eFWErr; /* Non-zero if in an error state */
  67484. u8 *aBuffer; /* Pointer to write buffer */
  67485. int nBuffer; /* Size of write buffer in bytes */
  67486. int iBufStart; /* First byte of buffer to write */
  67487. int iBufEnd; /* Last byte of buffer to write */
  67488. i64 iWriteOff; /* Offset of start of buffer in file */
  67489. sqlite3_file *pFile; /* File to write to */
  67490. };
  67491. /*
  67492. ** A structure to store a single record. All in-memory records are connected
  67493. ** together into a linked list headed at VdbeSorter.pRecord using the
  67494. ** SorterRecord.pNext pointer.
  67495. */
  67496. struct SorterRecord {
  67497. void *pVal;
  67498. int nVal;
  67499. SorterRecord *pNext;
  67500. };
  67501. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  67502. #define SORTER_MIN_WORKING 10
  67503. /* Maximum number of segments to merge in a single pass. */
  67504. #define SORTER_MAX_MERGE_COUNT 16
  67505. /*
  67506. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  67507. ** argument. All structure fields are set to zero before returning.
  67508. */
  67509. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  67510. sqlite3DbFree(db, pIter->aAlloc);
  67511. sqlite3DbFree(db, pIter->aBuffer);
  67512. memset(pIter, 0, sizeof(VdbeSorterIter));
  67513. }
  67514. /*
  67515. ** Read nByte bytes of data from the stream of data iterated by object p.
  67516. ** If successful, set *ppOut to point to a buffer containing the data
  67517. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  67518. ** error code.
  67519. **
  67520. ** The buffer indicated by *ppOut may only be considered valid until the
  67521. ** next call to this function.
  67522. */
  67523. static int vdbeSorterIterRead(
  67524. sqlite3 *db, /* Database handle (for malloc) */
  67525. VdbeSorterIter *p, /* Iterator */
  67526. int nByte, /* Bytes of data to read */
  67527. u8 **ppOut /* OUT: Pointer to buffer containing data */
  67528. ){
  67529. int iBuf; /* Offset within buffer to read from */
  67530. int nAvail; /* Bytes of data available in buffer */
  67531. assert( p->aBuffer );
  67532. /* If there is no more data to be read from the buffer, read the next
  67533. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  67534. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  67535. iBuf = p->iReadOff % p->nBuffer;
  67536. if( iBuf==0 ){
  67537. int nRead; /* Bytes to read from disk */
  67538. int rc; /* sqlite3OsRead() return code */
  67539. /* Determine how many bytes of data to read. */
  67540. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  67541. nRead = p->nBuffer;
  67542. }else{
  67543. nRead = (int)(p->iEof - p->iReadOff);
  67544. }
  67545. assert( nRead>0 );
  67546. /* Read data from the file. Return early if an error occurs. */
  67547. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  67548. assert( rc!=SQLITE_IOERR_SHORT_READ );
  67549. if( rc!=SQLITE_OK ) return rc;
  67550. }
  67551. nAvail = p->nBuffer - iBuf;
  67552. if( nByte<=nAvail ){
  67553. /* The requested data is available in the in-memory buffer. In this
  67554. ** case there is no need to make a copy of the data, just return a
  67555. ** pointer into the buffer to the caller. */
  67556. *ppOut = &p->aBuffer[iBuf];
  67557. p->iReadOff += nByte;
  67558. }else{
  67559. /* The requested data is not all available in the in-memory buffer.
  67560. ** In this case, allocate space at p->aAlloc[] to copy the requested
  67561. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  67562. int nRem; /* Bytes remaining to copy */
  67563. /* Extend the p->aAlloc[] allocation if required. */
  67564. if( p->nAlloc<nByte ){
  67565. int nNew = p->nAlloc*2;
  67566. while( nByte>nNew ) nNew = nNew*2;
  67567. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  67568. if( !p->aAlloc ) return SQLITE_NOMEM;
  67569. p->nAlloc = nNew;
  67570. }
  67571. /* Copy as much data as is available in the buffer into the start of
  67572. ** p->aAlloc[]. */
  67573. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  67574. p->iReadOff += nAvail;
  67575. nRem = nByte - nAvail;
  67576. /* The following loop copies up to p->nBuffer bytes per iteration into
  67577. ** the p->aAlloc[] buffer. */
  67578. while( nRem>0 ){
  67579. int rc; /* vdbeSorterIterRead() return code */
  67580. int nCopy; /* Number of bytes to copy */
  67581. u8 *aNext; /* Pointer to buffer to copy data from */
  67582. nCopy = nRem;
  67583. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  67584. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  67585. if( rc!=SQLITE_OK ) return rc;
  67586. assert( aNext!=p->aAlloc );
  67587. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  67588. nRem -= nCopy;
  67589. }
  67590. *ppOut = p->aAlloc;
  67591. }
  67592. return SQLITE_OK;
  67593. }
  67594. /*
  67595. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  67596. ** the value read.
  67597. */
  67598. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  67599. int iBuf;
  67600. iBuf = p->iReadOff % p->nBuffer;
  67601. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  67602. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  67603. }else{
  67604. u8 aVarint[16], *a;
  67605. int i = 0, rc;
  67606. do{
  67607. rc = vdbeSorterIterRead(db, p, 1, &a);
  67608. if( rc ) return rc;
  67609. aVarint[(i++)&0xf] = a[0];
  67610. }while( (a[0]&0x80)!=0 );
  67611. sqlite3GetVarint(aVarint, pnOut);
  67612. }
  67613. return SQLITE_OK;
  67614. }
  67615. /*
  67616. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  67617. ** no error occurs, or an SQLite error code if one does.
  67618. */
  67619. static int vdbeSorterIterNext(
  67620. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  67621. VdbeSorterIter *pIter /* Iterator to advance */
  67622. ){
  67623. int rc; /* Return Code */
  67624. u64 nRec = 0; /* Size of record in bytes */
  67625. if( pIter->iReadOff>=pIter->iEof ){
  67626. /* This is an EOF condition */
  67627. vdbeSorterIterZero(db, pIter);
  67628. return SQLITE_OK;
  67629. }
  67630. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  67631. if( rc==SQLITE_OK ){
  67632. pIter->nKey = (int)nRec;
  67633. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  67634. }
  67635. return rc;
  67636. }
  67637. /*
  67638. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  67639. ** starting at offset iStart and ending at offset iEof-1. This function
  67640. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  67641. ** PMA is empty).
  67642. */
  67643. static int vdbeSorterIterInit(
  67644. sqlite3 *db, /* Database handle */
  67645. const VdbeSorter *pSorter, /* Sorter object */
  67646. i64 iStart, /* Start offset in pFile */
  67647. VdbeSorterIter *pIter, /* Iterator to populate */
  67648. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  67649. ){
  67650. int rc = SQLITE_OK;
  67651. int nBuf;
  67652. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  67653. assert( pSorter->iWriteOff>iStart );
  67654. assert( pIter->aAlloc==0 );
  67655. assert( pIter->aBuffer==0 );
  67656. pIter->pFile = pSorter->pTemp1;
  67657. pIter->iReadOff = iStart;
  67658. pIter->nAlloc = 128;
  67659. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  67660. pIter->nBuffer = nBuf;
  67661. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  67662. if( !pIter->aBuffer ){
  67663. rc = SQLITE_NOMEM;
  67664. }else{
  67665. int iBuf;
  67666. iBuf = iStart % nBuf;
  67667. if( iBuf ){
  67668. int nRead = nBuf - iBuf;
  67669. if( (iStart + nRead) > pSorter->iWriteOff ){
  67670. nRead = (int)(pSorter->iWriteOff - iStart);
  67671. }
  67672. rc = sqlite3OsRead(
  67673. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  67674. );
  67675. assert( rc!=SQLITE_IOERR_SHORT_READ );
  67676. }
  67677. if( rc==SQLITE_OK ){
  67678. u64 nByte; /* Size of PMA in bytes */
  67679. pIter->iEof = pSorter->iWriteOff;
  67680. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  67681. pIter->iEof = pIter->iReadOff + nByte;
  67682. *pnByte += nByte;
  67683. }
  67684. }
  67685. if( rc==SQLITE_OK ){
  67686. rc = vdbeSorterIterNext(db, pIter);
  67687. }
  67688. return rc;
  67689. }
  67690. /*
  67691. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  67692. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  67693. ** used by the comparison. If an error occurs, return an SQLite error code.
  67694. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  67695. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  67696. **
  67697. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  67698. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  67699. ** is true and key1 contains even a single NULL value, it is considered to
  67700. ** be less than key2. Even if key2 also contains NULL values.
  67701. **
  67702. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  67703. ** has been allocated and contains an unpacked record that is used as key2.
  67704. */
  67705. static void vdbeSorterCompare(
  67706. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  67707. int bOmitRowid, /* Ignore rowid field at end of keys */
  67708. const void *pKey1, int nKey1, /* Left side of comparison */
  67709. const void *pKey2, int nKey2, /* Right side of comparison */
  67710. int *pRes /* OUT: Result of comparison */
  67711. ){
  67712. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  67713. VdbeSorter *pSorter = pCsr->pSorter;
  67714. UnpackedRecord *r2 = pSorter->pUnpacked;
  67715. int i;
  67716. if( pKey2 ){
  67717. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  67718. }
  67719. if( bOmitRowid ){
  67720. r2->nField = pKeyInfo->nField;
  67721. assert( r2->nField>0 );
  67722. for(i=0; i<r2->nField; i++){
  67723. if( r2->aMem[i].flags & MEM_Null ){
  67724. *pRes = -1;
  67725. return;
  67726. }
  67727. }
  67728. r2->flags |= UNPACKED_PREFIX_MATCH;
  67729. }
  67730. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  67731. }
  67732. /*
  67733. ** This function is called to compare two iterator keys when merging
  67734. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  67735. ** value to recalculate.
  67736. */
  67737. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  67738. VdbeSorter *pSorter = pCsr->pSorter;
  67739. int i1;
  67740. int i2;
  67741. int iRes;
  67742. VdbeSorterIter *p1;
  67743. VdbeSorterIter *p2;
  67744. assert( iOut<pSorter->nTree && iOut>0 );
  67745. if( iOut>=(pSorter->nTree/2) ){
  67746. i1 = (iOut - pSorter->nTree/2) * 2;
  67747. i2 = i1 + 1;
  67748. }else{
  67749. i1 = pSorter->aTree[iOut*2];
  67750. i2 = pSorter->aTree[iOut*2+1];
  67751. }
  67752. p1 = &pSorter->aIter[i1];
  67753. p2 = &pSorter->aIter[i2];
  67754. if( p1->pFile==0 ){
  67755. iRes = i2;
  67756. }else if( p2->pFile==0 ){
  67757. iRes = i1;
  67758. }else{
  67759. int res;
  67760. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  67761. vdbeSorterCompare(
  67762. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  67763. );
  67764. if( res<=0 ){
  67765. iRes = i1;
  67766. }else{
  67767. iRes = i2;
  67768. }
  67769. }
  67770. pSorter->aTree[iOut] = iRes;
  67771. return SQLITE_OK;
  67772. }
  67773. /*
  67774. ** Initialize the temporary index cursor just opened as a sorter cursor.
  67775. */
  67776. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  67777. int pgsz; /* Page size of main database */
  67778. int mxCache; /* Cache size */
  67779. VdbeSorter *pSorter; /* The new sorter */
  67780. char *d; /* Dummy */
  67781. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  67782. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  67783. if( pSorter==0 ){
  67784. return SQLITE_NOMEM;
  67785. }
  67786. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  67787. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  67788. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  67789. if( !sqlite3TempInMemory(db) ){
  67790. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  67791. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  67792. mxCache = db->aDb[0].pSchema->cache_size;
  67793. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  67794. pSorter->mxPmaSize = mxCache * pgsz;
  67795. }
  67796. return SQLITE_OK;
  67797. }
  67798. /*
  67799. ** Free the list of sorted records starting at pRecord.
  67800. */
  67801. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  67802. SorterRecord *p;
  67803. SorterRecord *pNext;
  67804. for(p=pRecord; p; p=pNext){
  67805. pNext = p->pNext;
  67806. sqlite3DbFree(db, p);
  67807. }
  67808. }
  67809. /*
  67810. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  67811. */
  67812. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  67813. VdbeSorter *pSorter = pCsr->pSorter;
  67814. if( pSorter ){
  67815. if( pSorter->aIter ){
  67816. int i;
  67817. for(i=0; i<pSorter->nTree; i++){
  67818. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  67819. }
  67820. sqlite3DbFree(db, pSorter->aIter);
  67821. }
  67822. if( pSorter->pTemp1 ){
  67823. sqlite3OsCloseFree(pSorter->pTemp1);
  67824. }
  67825. vdbeSorterRecordFree(db, pSorter->pRecord);
  67826. sqlite3DbFree(db, pSorter->pUnpacked);
  67827. sqlite3DbFree(db, pSorter);
  67828. pCsr->pSorter = 0;
  67829. }
  67830. }
  67831. /*
  67832. ** Allocate space for a file-handle and open a temporary file. If successful,
  67833. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  67834. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  67835. */
  67836. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  67837. int dummy;
  67838. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  67839. SQLITE_OPEN_TEMP_JOURNAL |
  67840. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  67841. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  67842. );
  67843. }
  67844. /*
  67845. ** Merge the two sorted lists p1 and p2 into a single list.
  67846. ** Set *ppOut to the head of the new list.
  67847. */
  67848. static void vdbeSorterMerge(
  67849. const VdbeCursor *pCsr, /* For pKeyInfo */
  67850. SorterRecord *p1, /* First list to merge */
  67851. SorterRecord *p2, /* Second list to merge */
  67852. SorterRecord **ppOut /* OUT: Head of merged list */
  67853. ){
  67854. SorterRecord *pFinal = 0;
  67855. SorterRecord **pp = &pFinal;
  67856. void *pVal2 = p2 ? p2->pVal : 0;
  67857. while( p1 && p2 ){
  67858. int res;
  67859. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  67860. if( res<=0 ){
  67861. *pp = p1;
  67862. pp = &p1->pNext;
  67863. p1 = p1->pNext;
  67864. pVal2 = 0;
  67865. }else{
  67866. *pp = p2;
  67867. pp = &p2->pNext;
  67868. p2 = p2->pNext;
  67869. if( p2==0 ) break;
  67870. pVal2 = p2->pVal;
  67871. }
  67872. }
  67873. *pp = p1 ? p1 : p2;
  67874. *ppOut = pFinal;
  67875. }
  67876. /*
  67877. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  67878. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  67879. ** occurs.
  67880. */
  67881. static int vdbeSorterSort(const VdbeCursor *pCsr){
  67882. int i;
  67883. SorterRecord **aSlot;
  67884. SorterRecord *p;
  67885. VdbeSorter *pSorter = pCsr->pSorter;
  67886. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  67887. if( !aSlot ){
  67888. return SQLITE_NOMEM;
  67889. }
  67890. p = pSorter->pRecord;
  67891. while( p ){
  67892. SorterRecord *pNext = p->pNext;
  67893. p->pNext = 0;
  67894. for(i=0; aSlot[i]; i++){
  67895. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  67896. aSlot[i] = 0;
  67897. }
  67898. aSlot[i] = p;
  67899. p = pNext;
  67900. }
  67901. p = 0;
  67902. for(i=0; i<64; i++){
  67903. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  67904. }
  67905. pSorter->pRecord = p;
  67906. sqlite3_free(aSlot);
  67907. return SQLITE_OK;
  67908. }
  67909. /*
  67910. ** Initialize a file-writer object.
  67911. */
  67912. static void fileWriterInit(
  67913. sqlite3 *db, /* Database (for malloc) */
  67914. sqlite3_file *pFile, /* File to write to */
  67915. FileWriter *p, /* Object to populate */
  67916. i64 iStart /* Offset of pFile to begin writing at */
  67917. ){
  67918. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  67919. memset(p, 0, sizeof(FileWriter));
  67920. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  67921. if( !p->aBuffer ){
  67922. p->eFWErr = SQLITE_NOMEM;
  67923. }else{
  67924. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  67925. p->iWriteOff = iStart - p->iBufStart;
  67926. p->nBuffer = nBuf;
  67927. p->pFile = pFile;
  67928. }
  67929. }
  67930. /*
  67931. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  67932. ** if successful, or an SQLite error code if an error occurs.
  67933. */
  67934. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  67935. int nRem = nData;
  67936. while( nRem>0 && p->eFWErr==0 ){
  67937. int nCopy = nRem;
  67938. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  67939. nCopy = p->nBuffer - p->iBufEnd;
  67940. }
  67941. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  67942. p->iBufEnd += nCopy;
  67943. if( p->iBufEnd==p->nBuffer ){
  67944. p->eFWErr = sqlite3OsWrite(p->pFile,
  67945. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  67946. p->iWriteOff + p->iBufStart
  67947. );
  67948. p->iBufStart = p->iBufEnd = 0;
  67949. p->iWriteOff += p->nBuffer;
  67950. }
  67951. assert( p->iBufEnd<p->nBuffer );
  67952. nRem -= nCopy;
  67953. }
  67954. }
  67955. /*
  67956. ** Flush any buffered data to disk and clean up the file-writer object.
  67957. ** The results of using the file-writer after this call are undefined.
  67958. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  67959. ** required. Otherwise, return an SQLite error code.
  67960. **
  67961. ** Before returning, set *piEof to the offset immediately following the
  67962. ** last byte written to the file.
  67963. */
  67964. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  67965. int rc;
  67966. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  67967. p->eFWErr = sqlite3OsWrite(p->pFile,
  67968. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  67969. p->iWriteOff + p->iBufStart
  67970. );
  67971. }
  67972. *piEof = (p->iWriteOff + p->iBufEnd);
  67973. sqlite3DbFree(db, p->aBuffer);
  67974. rc = p->eFWErr;
  67975. memset(p, 0, sizeof(FileWriter));
  67976. return rc;
  67977. }
  67978. /*
  67979. ** Write value iVal encoded as a varint to the file-write object. Return
  67980. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  67981. */
  67982. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  67983. int nByte;
  67984. u8 aByte[10];
  67985. nByte = sqlite3PutVarint(aByte, iVal);
  67986. fileWriterWrite(p, aByte, nByte);
  67987. }
  67988. /*
  67989. ** Write the current contents of the in-memory linked-list to a PMA. Return
  67990. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  67991. **
  67992. ** The format of a PMA is:
  67993. **
  67994. ** * A varint. This varint contains the total number of bytes of content
  67995. ** in the PMA (not including the varint itself).
  67996. **
  67997. ** * One or more records packed end-to-end in order of ascending keys.
  67998. ** Each record consists of a varint followed by a blob of data (the
  67999. ** key). The varint is the number of bytes in the blob of data.
  68000. */
  68001. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  68002. int rc = SQLITE_OK; /* Return code */
  68003. VdbeSorter *pSorter = pCsr->pSorter;
  68004. FileWriter writer;
  68005. memset(&writer, 0, sizeof(FileWriter));
  68006. if( pSorter->nInMemory==0 ){
  68007. assert( pSorter->pRecord==0 );
  68008. return rc;
  68009. }
  68010. rc = vdbeSorterSort(pCsr);
  68011. /* If the first temporary PMA file has not been opened, open it now. */
  68012. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  68013. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  68014. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  68015. assert( pSorter->iWriteOff==0 );
  68016. assert( pSorter->nPMA==0 );
  68017. }
  68018. if( rc==SQLITE_OK ){
  68019. SorterRecord *p;
  68020. SorterRecord *pNext = 0;
  68021. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  68022. pSorter->nPMA++;
  68023. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  68024. for(p=pSorter->pRecord; p; p=pNext){
  68025. pNext = p->pNext;
  68026. fileWriterWriteVarint(&writer, p->nVal);
  68027. fileWriterWrite(&writer, p->pVal, p->nVal);
  68028. sqlite3DbFree(db, p);
  68029. }
  68030. pSorter->pRecord = p;
  68031. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  68032. }
  68033. return rc;
  68034. }
  68035. /*
  68036. ** Add a record to the sorter.
  68037. */
  68038. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  68039. sqlite3 *db, /* Database handle */
  68040. const VdbeCursor *pCsr, /* Sorter cursor */
  68041. Mem *pVal /* Memory cell containing record */
  68042. ){
  68043. VdbeSorter *pSorter = pCsr->pSorter;
  68044. int rc = SQLITE_OK; /* Return Code */
  68045. SorterRecord *pNew; /* New list element */
  68046. assert( pSorter );
  68047. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  68048. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  68049. if( pNew==0 ){
  68050. rc = SQLITE_NOMEM;
  68051. }else{
  68052. pNew->pVal = (void *)&pNew[1];
  68053. memcpy(pNew->pVal, pVal->z, pVal->n);
  68054. pNew->nVal = pVal->n;
  68055. pNew->pNext = pSorter->pRecord;
  68056. pSorter->pRecord = pNew;
  68057. }
  68058. /* See if the contents of the sorter should now be written out. They
  68059. ** are written out when either of the following are true:
  68060. **
  68061. ** * The total memory allocated for the in-memory list is greater
  68062. ** than (page-size * cache-size), or
  68063. **
  68064. ** * The total memory allocated for the in-memory list is greater
  68065. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  68066. */
  68067. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  68068. (pSorter->nInMemory>pSorter->mxPmaSize)
  68069. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  68070. )){
  68071. #ifdef SQLITE_DEBUG
  68072. i64 nExpect = pSorter->iWriteOff
  68073. + sqlite3VarintLen(pSorter->nInMemory)
  68074. + pSorter->nInMemory;
  68075. #endif
  68076. rc = vdbeSorterListToPMA(db, pCsr);
  68077. pSorter->nInMemory = 0;
  68078. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  68079. }
  68080. return rc;
  68081. }
  68082. /*
  68083. ** Helper function for sqlite3VdbeSorterRewind().
  68084. */
  68085. static int vdbeSorterInitMerge(
  68086. sqlite3 *db, /* Database handle */
  68087. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  68088. i64 *pnByte /* Sum of bytes in all opened PMAs */
  68089. ){
  68090. VdbeSorter *pSorter = pCsr->pSorter;
  68091. int rc = SQLITE_OK; /* Return code */
  68092. int i; /* Used to iterator through aIter[] */
  68093. i64 nByte = 0; /* Total bytes in all opened PMAs */
  68094. /* Initialize the iterators. */
  68095. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  68096. VdbeSorterIter *pIter = &pSorter->aIter[i];
  68097. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  68098. pSorter->iReadOff = pIter->iEof;
  68099. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  68100. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  68101. }
  68102. /* Initialize the aTree[] array. */
  68103. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  68104. rc = vdbeSorterDoCompare(pCsr, i);
  68105. }
  68106. *pnByte = nByte;
  68107. return rc;
  68108. }
  68109. /*
  68110. ** Once the sorter has been populated, this function is called to prepare
  68111. ** for iterating through its contents in sorted order.
  68112. */
  68113. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  68114. VdbeSorter *pSorter = pCsr->pSorter;
  68115. int rc; /* Return code */
  68116. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  68117. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  68118. int nIter; /* Number of iterators used */
  68119. int nByte; /* Bytes of space required for aIter/aTree */
  68120. int N = 2; /* Power of 2 >= nIter */
  68121. assert( pSorter );
  68122. /* If no data has been written to disk, then do not do so now. Instead,
  68123. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  68124. ** from the in-memory list. */
  68125. if( pSorter->nPMA==0 ){
  68126. *pbEof = !pSorter->pRecord;
  68127. assert( pSorter->aTree==0 );
  68128. return vdbeSorterSort(pCsr);
  68129. }
  68130. /* Write the current in-memory list to a PMA. */
  68131. rc = vdbeSorterListToPMA(db, pCsr);
  68132. if( rc!=SQLITE_OK ) return rc;
  68133. /* Allocate space for aIter[] and aTree[]. */
  68134. nIter = pSorter->nPMA;
  68135. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  68136. assert( nIter>0 );
  68137. while( N<nIter ) N += N;
  68138. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  68139. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  68140. if( !pSorter->aIter ) return SQLITE_NOMEM;
  68141. pSorter->aTree = (int *)&pSorter->aIter[N];
  68142. pSorter->nTree = N;
  68143. do {
  68144. int iNew; /* Index of new, merged, PMA */
  68145. for(iNew=0;
  68146. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  68147. iNew++
  68148. ){
  68149. int rc2; /* Return code from fileWriterFinish() */
  68150. FileWriter writer; /* Object used to write to disk */
  68151. i64 nWrite; /* Number of bytes in new PMA */
  68152. memset(&writer, 0, sizeof(FileWriter));
  68153. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  68154. ** initialize an iterator for each of them and break out of the loop.
  68155. ** These iterators will be incrementally merged as the VDBE layer calls
  68156. ** sqlite3VdbeSorterNext().
  68157. **
  68158. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  68159. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  68160. ** are merged into a single PMA that is written to file pTemp2.
  68161. */
  68162. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  68163. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  68164. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  68165. break;
  68166. }
  68167. /* Open the second temp file, if it is not already open. */
  68168. if( pTemp2==0 ){
  68169. assert( iWrite2==0 );
  68170. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  68171. }
  68172. if( rc==SQLITE_OK ){
  68173. int bEof = 0;
  68174. fileWriterInit(db, pTemp2, &writer, iWrite2);
  68175. fileWriterWriteVarint(&writer, nWrite);
  68176. while( rc==SQLITE_OK && bEof==0 ){
  68177. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  68178. assert( pIter->pFile );
  68179. fileWriterWriteVarint(&writer, pIter->nKey);
  68180. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  68181. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  68182. }
  68183. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  68184. if( rc==SQLITE_OK ) rc = rc2;
  68185. }
  68186. }
  68187. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  68188. break;
  68189. }else{
  68190. sqlite3_file *pTmp = pSorter->pTemp1;
  68191. pSorter->nPMA = iNew;
  68192. pSorter->pTemp1 = pTemp2;
  68193. pTemp2 = pTmp;
  68194. pSorter->iWriteOff = iWrite2;
  68195. pSorter->iReadOff = 0;
  68196. iWrite2 = 0;
  68197. }
  68198. }while( rc==SQLITE_OK );
  68199. if( pTemp2 ){
  68200. sqlite3OsCloseFree(pTemp2);
  68201. }
  68202. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  68203. return rc;
  68204. }
  68205. /*
  68206. ** Advance to the next element in the sorter.
  68207. */
  68208. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  68209. VdbeSorter *pSorter = pCsr->pSorter;
  68210. int rc; /* Return code */
  68211. if( pSorter->aTree ){
  68212. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  68213. int i; /* Index of aTree[] to recalculate */
  68214. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  68215. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  68216. rc = vdbeSorterDoCompare(pCsr, i);
  68217. }
  68218. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  68219. }else{
  68220. SorterRecord *pFree = pSorter->pRecord;
  68221. pSorter->pRecord = pFree->pNext;
  68222. pFree->pNext = 0;
  68223. vdbeSorterRecordFree(db, pFree);
  68224. *pbEof = !pSorter->pRecord;
  68225. rc = SQLITE_OK;
  68226. }
  68227. return rc;
  68228. }
  68229. /*
  68230. ** Return a pointer to a buffer owned by the sorter that contains the
  68231. ** current key.
  68232. */
  68233. static void *vdbeSorterRowkey(
  68234. const VdbeSorter *pSorter, /* Sorter object */
  68235. int *pnKey /* OUT: Size of current key in bytes */
  68236. ){
  68237. void *pKey;
  68238. if( pSorter->aTree ){
  68239. VdbeSorterIter *pIter;
  68240. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  68241. *pnKey = pIter->nKey;
  68242. pKey = pIter->aKey;
  68243. }else{
  68244. *pnKey = pSorter->pRecord->nVal;
  68245. pKey = pSorter->pRecord->pVal;
  68246. }
  68247. return pKey;
  68248. }
  68249. /*
  68250. ** Copy the current sorter key into the memory cell pOut.
  68251. */
  68252. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  68253. VdbeSorter *pSorter = pCsr->pSorter;
  68254. void *pKey; int nKey; /* Sorter key to copy into pOut */
  68255. pKey = vdbeSorterRowkey(pSorter, &nKey);
  68256. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  68257. return SQLITE_NOMEM;
  68258. }
  68259. pOut->n = nKey;
  68260. MemSetTypeFlag(pOut, MEM_Blob);
  68261. memcpy(pOut->z, pKey, nKey);
  68262. return SQLITE_OK;
  68263. }
  68264. /*
  68265. ** Compare the key in memory cell pVal with the key that the sorter cursor
  68266. ** passed as the first argument currently points to. For the purposes of
  68267. ** the comparison, ignore the rowid field at the end of each record.
  68268. **
  68269. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  68270. ** Otherwise, set *pRes to a negative, zero or positive value if the
  68271. ** key in pVal is smaller than, equal to or larger than the current sorter
  68272. ** key.
  68273. */
  68274. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  68275. const VdbeCursor *pCsr, /* Sorter cursor */
  68276. Mem *pVal, /* Value to compare to current sorter key */
  68277. int *pRes /* OUT: Result of comparison */
  68278. ){
  68279. VdbeSorter *pSorter = pCsr->pSorter;
  68280. void *pKey; int nKey; /* Sorter key to compare pVal with */
  68281. pKey = vdbeSorterRowkey(pSorter, &nKey);
  68282. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  68283. return SQLITE_OK;
  68284. }
  68285. /************** End of vdbesort.c ********************************************/
  68286. /************** Begin file journal.c *****************************************/
  68287. /*
  68288. ** 2007 August 22
  68289. **
  68290. ** The author disclaims copyright to this source code. In place of
  68291. ** a legal notice, here is a blessing:
  68292. **
  68293. ** May you do good and not evil.
  68294. ** May you find forgiveness for yourself and forgive others.
  68295. ** May you share freely, never taking more than you give.
  68296. **
  68297. *************************************************************************
  68298. **
  68299. ** This file implements a special kind of sqlite3_file object used
  68300. ** by SQLite to create journal files if the atomic-write optimization
  68301. ** is enabled.
  68302. **
  68303. ** The distinctive characteristic of this sqlite3_file is that the
  68304. ** actual on disk file is created lazily. When the file is created,
  68305. ** the caller specifies a buffer size for an in-memory buffer to
  68306. ** be used to service read() and write() requests. The actual file
  68307. ** on disk is not created or populated until either:
  68308. **
  68309. ** 1) The in-memory representation grows too large for the allocated
  68310. ** buffer, or
  68311. ** 2) The sqlite3JournalCreate() function is called.
  68312. */
  68313. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  68314. /*
  68315. ** A JournalFile object is a subclass of sqlite3_file used by
  68316. ** as an open file handle for journal files.
  68317. */
  68318. struct JournalFile {
  68319. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  68320. int nBuf; /* Size of zBuf[] in bytes */
  68321. char *zBuf; /* Space to buffer journal writes */
  68322. int iSize; /* Amount of zBuf[] currently used */
  68323. int flags; /* xOpen flags */
  68324. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  68325. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  68326. const char *zJournal; /* Name of the journal file */
  68327. };
  68328. typedef struct JournalFile JournalFile;
  68329. /*
  68330. ** If it does not already exists, create and populate the on-disk file
  68331. ** for JournalFile p.
  68332. */
  68333. static int createFile(JournalFile *p){
  68334. int rc = SQLITE_OK;
  68335. if( !p->pReal ){
  68336. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  68337. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  68338. if( rc==SQLITE_OK ){
  68339. p->pReal = pReal;
  68340. if( p->iSize>0 ){
  68341. assert(p->iSize<=p->nBuf);
  68342. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  68343. }
  68344. if( rc!=SQLITE_OK ){
  68345. /* If an error occurred while writing to the file, close it before
  68346. ** returning. This way, SQLite uses the in-memory journal data to
  68347. ** roll back changes made to the internal page-cache before this
  68348. ** function was called. */
  68349. sqlite3OsClose(pReal);
  68350. p->pReal = 0;
  68351. }
  68352. }
  68353. }
  68354. return rc;
  68355. }
  68356. /*
  68357. ** Close the file.
  68358. */
  68359. static int jrnlClose(sqlite3_file *pJfd){
  68360. JournalFile *p = (JournalFile *)pJfd;
  68361. if( p->pReal ){
  68362. sqlite3OsClose(p->pReal);
  68363. }
  68364. sqlite3_free(p->zBuf);
  68365. return SQLITE_OK;
  68366. }
  68367. /*
  68368. ** Read data from the file.
  68369. */
  68370. static int jrnlRead(
  68371. sqlite3_file *pJfd, /* The journal file from which to read */
  68372. void *zBuf, /* Put the results here */
  68373. int iAmt, /* Number of bytes to read */
  68374. sqlite_int64 iOfst /* Begin reading at this offset */
  68375. ){
  68376. int rc = SQLITE_OK;
  68377. JournalFile *p = (JournalFile *)pJfd;
  68378. if( p->pReal ){
  68379. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  68380. }else if( (iAmt+iOfst)>p->iSize ){
  68381. rc = SQLITE_IOERR_SHORT_READ;
  68382. }else{
  68383. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  68384. }
  68385. return rc;
  68386. }
  68387. /*
  68388. ** Write data to the file.
  68389. */
  68390. static int jrnlWrite(
  68391. sqlite3_file *pJfd, /* The journal file into which to write */
  68392. const void *zBuf, /* Take data to be written from here */
  68393. int iAmt, /* Number of bytes to write */
  68394. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  68395. ){
  68396. int rc = SQLITE_OK;
  68397. JournalFile *p = (JournalFile *)pJfd;
  68398. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  68399. rc = createFile(p);
  68400. }
  68401. if( rc==SQLITE_OK ){
  68402. if( p->pReal ){
  68403. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  68404. }else{
  68405. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  68406. if( p->iSize<(iOfst+iAmt) ){
  68407. p->iSize = (iOfst+iAmt);
  68408. }
  68409. }
  68410. }
  68411. return rc;
  68412. }
  68413. /*
  68414. ** Truncate the file.
  68415. */
  68416. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  68417. int rc = SQLITE_OK;
  68418. JournalFile *p = (JournalFile *)pJfd;
  68419. if( p->pReal ){
  68420. rc = sqlite3OsTruncate(p->pReal, size);
  68421. }else if( size<p->iSize ){
  68422. p->iSize = size;
  68423. }
  68424. return rc;
  68425. }
  68426. /*
  68427. ** Sync the file.
  68428. */
  68429. static int jrnlSync(sqlite3_file *pJfd, int flags){
  68430. int rc;
  68431. JournalFile *p = (JournalFile *)pJfd;
  68432. if( p->pReal ){
  68433. rc = sqlite3OsSync(p->pReal, flags);
  68434. }else{
  68435. rc = SQLITE_OK;
  68436. }
  68437. return rc;
  68438. }
  68439. /*
  68440. ** Query the size of the file in bytes.
  68441. */
  68442. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  68443. int rc = SQLITE_OK;
  68444. JournalFile *p = (JournalFile *)pJfd;
  68445. if( p->pReal ){
  68446. rc = sqlite3OsFileSize(p->pReal, pSize);
  68447. }else{
  68448. *pSize = (sqlite_int64) p->iSize;
  68449. }
  68450. return rc;
  68451. }
  68452. /*
  68453. ** Table of methods for JournalFile sqlite3_file object.
  68454. */
  68455. static struct sqlite3_io_methods JournalFileMethods = {
  68456. 1, /* iVersion */
  68457. jrnlClose, /* xClose */
  68458. jrnlRead, /* xRead */
  68459. jrnlWrite, /* xWrite */
  68460. jrnlTruncate, /* xTruncate */
  68461. jrnlSync, /* xSync */
  68462. jrnlFileSize, /* xFileSize */
  68463. 0, /* xLock */
  68464. 0, /* xUnlock */
  68465. 0, /* xCheckReservedLock */
  68466. 0, /* xFileControl */
  68467. 0, /* xSectorSize */
  68468. 0, /* xDeviceCharacteristics */
  68469. 0, /* xShmMap */
  68470. 0, /* xShmLock */
  68471. 0, /* xShmBarrier */
  68472. 0 /* xShmUnmap */
  68473. };
  68474. /*
  68475. ** Open a journal file.
  68476. */
  68477. SQLITE_PRIVATE int sqlite3JournalOpen(
  68478. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  68479. const char *zName, /* Name of the journal file */
  68480. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  68481. int flags, /* Opening flags */
  68482. int nBuf /* Bytes buffered before opening the file */
  68483. ){
  68484. JournalFile *p = (JournalFile *)pJfd;
  68485. memset(p, 0, sqlite3JournalSize(pVfs));
  68486. if( nBuf>0 ){
  68487. p->zBuf = sqlite3MallocZero(nBuf);
  68488. if( !p->zBuf ){
  68489. return SQLITE_NOMEM;
  68490. }
  68491. }else{
  68492. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  68493. }
  68494. p->pMethod = &JournalFileMethods;
  68495. p->nBuf = nBuf;
  68496. p->flags = flags;
  68497. p->zJournal = zName;
  68498. p->pVfs = pVfs;
  68499. return SQLITE_OK;
  68500. }
  68501. /*
  68502. ** If the argument p points to a JournalFile structure, and the underlying
  68503. ** file has not yet been created, create it now.
  68504. */
  68505. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  68506. if( p->pMethods!=&JournalFileMethods ){
  68507. return SQLITE_OK;
  68508. }
  68509. return createFile((JournalFile *)p);
  68510. }
  68511. /*
  68512. ** The file-handle passed as the only argument is guaranteed to be an open
  68513. ** file. It may or may not be of class JournalFile. If the file is a
  68514. ** JournalFile, and the underlying file on disk has not yet been opened,
  68515. ** return 0. Otherwise, return 1.
  68516. */
  68517. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  68518. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  68519. }
  68520. /*
  68521. ** Return the number of bytes required to store a JournalFile that uses vfs
  68522. ** pVfs to create the underlying on-disk files.
  68523. */
  68524. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  68525. return (pVfs->szOsFile+sizeof(JournalFile));
  68526. }
  68527. #endif
  68528. /************** End of journal.c *********************************************/
  68529. /************** Begin file memjournal.c **************************************/
  68530. /*
  68531. ** 2008 October 7
  68532. **
  68533. ** The author disclaims copyright to this source code. In place of
  68534. ** a legal notice, here is a blessing:
  68535. **
  68536. ** May you do good and not evil.
  68537. ** May you find forgiveness for yourself and forgive others.
  68538. ** May you share freely, never taking more than you give.
  68539. **
  68540. *************************************************************************
  68541. **
  68542. ** This file contains code use to implement an in-memory rollback journal.
  68543. ** The in-memory rollback journal is used to journal transactions for
  68544. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  68545. */
  68546. /* Forward references to internal structures */
  68547. typedef struct MemJournal MemJournal;
  68548. typedef struct FilePoint FilePoint;
  68549. typedef struct FileChunk FileChunk;
  68550. /* Space to hold the rollback journal is allocated in increments of
  68551. ** this many bytes.
  68552. **
  68553. ** The size chosen is a little less than a power of two. That way,
  68554. ** the FileChunk object will have a size that almost exactly fills
  68555. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  68556. ** memory allocators.
  68557. */
  68558. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  68559. /* Macro to find the minimum of two numeric values.
  68560. */
  68561. #ifndef MIN
  68562. # define MIN(x,y) ((x)<(y)?(x):(y))
  68563. #endif
  68564. /*
  68565. ** The rollback journal is composed of a linked list of these structures.
  68566. */
  68567. struct FileChunk {
  68568. FileChunk *pNext; /* Next chunk in the journal */
  68569. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  68570. };
  68571. /*
  68572. ** An instance of this object serves as a cursor into the rollback journal.
  68573. ** The cursor can be either for reading or writing.
  68574. */
  68575. struct FilePoint {
  68576. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  68577. FileChunk *pChunk; /* Specific chunk into which cursor points */
  68578. };
  68579. /*
  68580. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  68581. ** is an instance of this class.
  68582. */
  68583. struct MemJournal {
  68584. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  68585. FileChunk *pFirst; /* Head of in-memory chunk-list */
  68586. FilePoint endpoint; /* Pointer to the end of the file */
  68587. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  68588. };
  68589. /*
  68590. ** Read data from the in-memory journal file. This is the implementation
  68591. ** of the sqlite3_vfs.xRead method.
  68592. */
  68593. static int memjrnlRead(
  68594. sqlite3_file *pJfd, /* The journal file from which to read */
  68595. void *zBuf, /* Put the results here */
  68596. int iAmt, /* Number of bytes to read */
  68597. sqlite_int64 iOfst /* Begin reading at this offset */
  68598. ){
  68599. MemJournal *p = (MemJournal *)pJfd;
  68600. u8 *zOut = zBuf;
  68601. int nRead = iAmt;
  68602. int iChunkOffset;
  68603. FileChunk *pChunk;
  68604. /* SQLite never tries to read past the end of a rollback journal file */
  68605. assert( iOfst+iAmt<=p->endpoint.iOffset );
  68606. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  68607. sqlite3_int64 iOff = 0;
  68608. for(pChunk=p->pFirst;
  68609. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  68610. pChunk=pChunk->pNext
  68611. ){
  68612. iOff += JOURNAL_CHUNKSIZE;
  68613. }
  68614. }else{
  68615. pChunk = p->readpoint.pChunk;
  68616. }
  68617. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  68618. do {
  68619. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  68620. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  68621. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  68622. zOut += nCopy;
  68623. nRead -= iSpace;
  68624. iChunkOffset = 0;
  68625. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  68626. p->readpoint.iOffset = iOfst+iAmt;
  68627. p->readpoint.pChunk = pChunk;
  68628. return SQLITE_OK;
  68629. }
  68630. /*
  68631. ** Write data to the file.
  68632. */
  68633. static int memjrnlWrite(
  68634. sqlite3_file *pJfd, /* The journal file into which to write */
  68635. const void *zBuf, /* Take data to be written from here */
  68636. int iAmt, /* Number of bytes to write */
  68637. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  68638. ){
  68639. MemJournal *p = (MemJournal *)pJfd;
  68640. int nWrite = iAmt;
  68641. u8 *zWrite = (u8 *)zBuf;
  68642. /* An in-memory journal file should only ever be appended to. Random
  68643. ** access writes are not required by sqlite.
  68644. */
  68645. assert( iOfst==p->endpoint.iOffset );
  68646. UNUSED_PARAMETER(iOfst);
  68647. while( nWrite>0 ){
  68648. FileChunk *pChunk = p->endpoint.pChunk;
  68649. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  68650. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  68651. if( iChunkOffset==0 ){
  68652. /* New chunk is required to extend the file. */
  68653. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  68654. if( !pNew ){
  68655. return SQLITE_IOERR_NOMEM;
  68656. }
  68657. pNew->pNext = 0;
  68658. if( pChunk ){
  68659. assert( p->pFirst );
  68660. pChunk->pNext = pNew;
  68661. }else{
  68662. assert( !p->pFirst );
  68663. p->pFirst = pNew;
  68664. }
  68665. p->endpoint.pChunk = pNew;
  68666. }
  68667. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  68668. zWrite += iSpace;
  68669. nWrite -= iSpace;
  68670. p->endpoint.iOffset += iSpace;
  68671. }
  68672. return SQLITE_OK;
  68673. }
  68674. /*
  68675. ** Truncate the file.
  68676. */
  68677. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  68678. MemJournal *p = (MemJournal *)pJfd;
  68679. FileChunk *pChunk;
  68680. assert(size==0);
  68681. UNUSED_PARAMETER(size);
  68682. pChunk = p->pFirst;
  68683. while( pChunk ){
  68684. FileChunk *pTmp = pChunk;
  68685. pChunk = pChunk->pNext;
  68686. sqlite3_free(pTmp);
  68687. }
  68688. sqlite3MemJournalOpen(pJfd);
  68689. return SQLITE_OK;
  68690. }
  68691. /*
  68692. ** Close the file.
  68693. */
  68694. static int memjrnlClose(sqlite3_file *pJfd){
  68695. memjrnlTruncate(pJfd, 0);
  68696. return SQLITE_OK;
  68697. }
  68698. /*
  68699. ** Sync the file.
  68700. **
  68701. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  68702. ** is never called in a working implementation. This implementation
  68703. ** exists purely as a contingency, in case some malfunction in some other
  68704. ** part of SQLite causes Sync to be called by mistake.
  68705. */
  68706. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  68707. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  68708. return SQLITE_OK;
  68709. }
  68710. /*
  68711. ** Query the size of the file in bytes.
  68712. */
  68713. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  68714. MemJournal *p = (MemJournal *)pJfd;
  68715. *pSize = (sqlite_int64) p->endpoint.iOffset;
  68716. return SQLITE_OK;
  68717. }
  68718. /*
  68719. ** Table of methods for MemJournal sqlite3_file object.
  68720. */
  68721. static const struct sqlite3_io_methods MemJournalMethods = {
  68722. 1, /* iVersion */
  68723. memjrnlClose, /* xClose */
  68724. memjrnlRead, /* xRead */
  68725. memjrnlWrite, /* xWrite */
  68726. memjrnlTruncate, /* xTruncate */
  68727. memjrnlSync, /* xSync */
  68728. memjrnlFileSize, /* xFileSize */
  68729. 0, /* xLock */
  68730. 0, /* xUnlock */
  68731. 0, /* xCheckReservedLock */
  68732. 0, /* xFileControl */
  68733. 0, /* xSectorSize */
  68734. 0, /* xDeviceCharacteristics */
  68735. 0, /* xShmMap */
  68736. 0, /* xShmLock */
  68737. 0, /* xShmBarrier */
  68738. 0, /* xShmUnmap */
  68739. 0, /* xFetch */
  68740. 0 /* xUnfetch */
  68741. };
  68742. /*
  68743. ** Open a journal file.
  68744. */
  68745. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  68746. MemJournal *p = (MemJournal *)pJfd;
  68747. assert( EIGHT_BYTE_ALIGNMENT(p) );
  68748. memset(p, 0, sqlite3MemJournalSize());
  68749. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  68750. }
  68751. /*
  68752. ** Return true if the file-handle passed as an argument is
  68753. ** an in-memory journal
  68754. */
  68755. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  68756. return pJfd->pMethods==&MemJournalMethods;
  68757. }
  68758. /*
  68759. ** Return the number of bytes required to store a MemJournal file descriptor.
  68760. */
  68761. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  68762. return sizeof(MemJournal);
  68763. }
  68764. /************** End of memjournal.c ******************************************/
  68765. /************** Begin file walker.c ******************************************/
  68766. /*
  68767. ** 2008 August 16
  68768. **
  68769. ** The author disclaims copyright to this source code. In place of
  68770. ** a legal notice, here is a blessing:
  68771. **
  68772. ** May you do good and not evil.
  68773. ** May you find forgiveness for yourself and forgive others.
  68774. ** May you share freely, never taking more than you give.
  68775. **
  68776. *************************************************************************
  68777. ** This file contains routines used for walking the parser tree for
  68778. ** an SQL statement.
  68779. */
  68780. /* #include <stdlib.h> */
  68781. /* #include <string.h> */
  68782. /*
  68783. ** Walk an expression tree. Invoke the callback once for each node
  68784. ** of the expression, while decending. (In other words, the callback
  68785. ** is invoked before visiting children.)
  68786. **
  68787. ** The return value from the callback should be one of the WRC_*
  68788. ** constants to specify how to proceed with the walk.
  68789. **
  68790. ** WRC_Continue Continue descending down the tree.
  68791. **
  68792. ** WRC_Prune Do not descend into child nodes. But allow
  68793. ** the walk to continue with sibling nodes.
  68794. **
  68795. ** WRC_Abort Do no more callbacks. Unwind the stack and
  68796. ** return the top-level walk call.
  68797. **
  68798. ** The return value from this routine is WRC_Abort to abandon the tree walk
  68799. ** and WRC_Continue to continue.
  68800. */
  68801. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  68802. int rc;
  68803. if( pExpr==0 ) return WRC_Continue;
  68804. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  68805. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  68806. rc = pWalker->xExprCallback(pWalker, pExpr);
  68807. if( rc==WRC_Continue
  68808. && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
  68809. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  68810. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  68811. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  68812. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  68813. }else{
  68814. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  68815. }
  68816. }
  68817. return rc & WRC_Abort;
  68818. }
  68819. /*
  68820. ** Call sqlite3WalkExpr() for every expression in list p or until
  68821. ** an abort request is seen.
  68822. */
  68823. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  68824. int i;
  68825. struct ExprList_item *pItem;
  68826. if( p ){
  68827. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  68828. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  68829. }
  68830. }
  68831. return WRC_Continue;
  68832. }
  68833. /*
  68834. ** Walk all expressions associated with SELECT statement p. Do
  68835. ** not invoke the SELECT callback on p, but do (of course) invoke
  68836. ** any expr callbacks and SELECT callbacks that come from subqueries.
  68837. ** Return WRC_Abort or WRC_Continue.
  68838. */
  68839. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  68840. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  68841. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  68842. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  68843. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  68844. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  68845. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  68846. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  68847. return WRC_Continue;
  68848. }
  68849. /*
  68850. ** Walk the parse trees associated with all subqueries in the
  68851. ** FROM clause of SELECT statement p. Do not invoke the select
  68852. ** callback on p, but do invoke it on each FROM clause subquery
  68853. ** and on any subqueries further down in the tree. Return
  68854. ** WRC_Abort or WRC_Continue;
  68855. */
  68856. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  68857. SrcList *pSrc;
  68858. int i;
  68859. struct SrcList_item *pItem;
  68860. pSrc = p->pSrc;
  68861. if( ALWAYS(pSrc) ){
  68862. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  68863. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  68864. return WRC_Abort;
  68865. }
  68866. }
  68867. }
  68868. return WRC_Continue;
  68869. }
  68870. /*
  68871. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  68872. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  68873. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  68874. ** either before or after the walk of expressions and FROM clause, depending
  68875. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  68876. **
  68877. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  68878. ** there is an abort request.
  68879. **
  68880. ** If the Walker does not have an xSelectCallback() then this routine
  68881. ** is a no-op returning WRC_Continue.
  68882. */
  68883. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  68884. int rc;
  68885. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  68886. rc = WRC_Continue;
  68887. pWalker->walkerDepth++;
  68888. while( p ){
  68889. if( !pWalker->bSelectDepthFirst ){
  68890. rc = pWalker->xSelectCallback(pWalker, p);
  68891. if( rc ) break;
  68892. }
  68893. if( sqlite3WalkSelectExpr(pWalker, p)
  68894. || sqlite3WalkSelectFrom(pWalker, p)
  68895. ){
  68896. pWalker->walkerDepth--;
  68897. return WRC_Abort;
  68898. }
  68899. if( pWalker->bSelectDepthFirst ){
  68900. rc = pWalker->xSelectCallback(pWalker, p);
  68901. /* Depth-first search is currently only used for
  68902. ** selectAddSubqueryTypeInfo() and that routine always returns
  68903. ** WRC_Continue (0). So the following branch is never taken. */
  68904. if( NEVER(rc) ) break;
  68905. }
  68906. p = p->pPrior;
  68907. }
  68908. pWalker->walkerDepth--;
  68909. return rc & WRC_Abort;
  68910. }
  68911. /************** End of walker.c **********************************************/
  68912. /************** Begin file resolve.c *****************************************/
  68913. /*
  68914. ** 2008 August 18
  68915. **
  68916. ** The author disclaims copyright to this source code. In place of
  68917. ** a legal notice, here is a blessing:
  68918. **
  68919. ** May you do good and not evil.
  68920. ** May you find forgiveness for yourself and forgive others.
  68921. ** May you share freely, never taking more than you give.
  68922. **
  68923. *************************************************************************
  68924. **
  68925. ** This file contains routines used for walking the parser tree and
  68926. ** resolve all identifiers by associating them with a particular
  68927. ** table and column.
  68928. */
  68929. /* #include <stdlib.h> */
  68930. /* #include <string.h> */
  68931. /*
  68932. ** Walk the expression tree pExpr and increase the aggregate function
  68933. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  68934. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  68935. ** outer query into an inner subquery.
  68936. **
  68937. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  68938. ** is a helper function - a callback for the tree walker.
  68939. */
  68940. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  68941. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  68942. return WRC_Continue;
  68943. }
  68944. static void incrAggFunctionDepth(Expr *pExpr, int N){
  68945. if( N>0 ){
  68946. Walker w;
  68947. memset(&w, 0, sizeof(w));
  68948. w.xExprCallback = incrAggDepth;
  68949. w.u.i = N;
  68950. sqlite3WalkExpr(&w, pExpr);
  68951. }
  68952. }
  68953. /*
  68954. ** Turn the pExpr expression into an alias for the iCol-th column of the
  68955. ** result set in pEList.
  68956. **
  68957. ** If the result set column is a simple column reference, then this routine
  68958. ** makes an exact copy. But for any other kind of expression, this
  68959. ** routine make a copy of the result set column as the argument to the
  68960. ** TK_AS operator. The TK_AS operator causes the expression to be
  68961. ** evaluated just once and then reused for each alias.
  68962. **
  68963. ** The reason for suppressing the TK_AS term when the expression is a simple
  68964. ** column reference is so that the column reference will be recognized as
  68965. ** usable by indices within the WHERE clause processing logic.
  68966. **
  68967. ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
  68968. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  68969. **
  68970. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  68971. **
  68972. ** Is equivalent to:
  68973. **
  68974. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  68975. **
  68976. ** The result of random()%5 in the GROUP BY clause is probably different
  68977. ** from the result in the result-set. We might fix this someday. Or
  68978. ** then again, we might not...
  68979. **
  68980. ** If the reference is followed by a COLLATE operator, then make sure
  68981. ** the COLLATE operator is preserved. For example:
  68982. **
  68983. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  68984. **
  68985. ** Should be transformed into:
  68986. **
  68987. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  68988. **
  68989. ** The nSubquery parameter specifies how many levels of subquery the
  68990. ** alias is removed from the original expression. The usually value is
  68991. ** zero but it might be more if the alias is contained within a subquery
  68992. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  68993. ** structures must be increased by the nSubquery amount.
  68994. */
  68995. static void resolveAlias(
  68996. Parse *pParse, /* Parsing context */
  68997. ExprList *pEList, /* A result set */
  68998. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  68999. Expr *pExpr, /* Transform this into an alias to the result set */
  69000. const char *zType, /* "GROUP" or "ORDER" or "" */
  69001. int nSubquery /* Number of subqueries that the label is moving */
  69002. ){
  69003. Expr *pOrig; /* The iCol-th column of the result set */
  69004. Expr *pDup; /* Copy of pOrig */
  69005. sqlite3 *db; /* The database connection */
  69006. assert( iCol>=0 && iCol<pEList->nExpr );
  69007. pOrig = pEList->a[iCol].pExpr;
  69008. assert( pOrig!=0 );
  69009. assert( pOrig->flags & EP_Resolved );
  69010. db = pParse->db;
  69011. pDup = sqlite3ExprDup(db, pOrig, 0);
  69012. if( pDup==0 ) return;
  69013. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  69014. incrAggFunctionDepth(pDup, nSubquery);
  69015. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  69016. if( pDup==0 ) return;
  69017. if( pEList->a[iCol].iAlias==0 ){
  69018. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  69019. }
  69020. pDup->iTable = pEList->a[iCol].iAlias;
  69021. }
  69022. if( pExpr->op==TK_COLLATE ){
  69023. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  69024. }
  69025. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  69026. ** prevents ExprDelete() from deleting the Expr structure itself,
  69027. ** allowing it to be repopulated by the memcpy() on the following line.
  69028. ** The pExpr->u.zToken might point into memory that will be freed by the
  69029. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  69030. ** make a copy of the token before doing the sqlite3DbFree().
  69031. */
  69032. ExprSetProperty(pExpr, EP_Static);
  69033. sqlite3ExprDelete(db, pExpr);
  69034. memcpy(pExpr, pDup, sizeof(*pExpr));
  69035. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  69036. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  69037. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  69038. pExpr->flags2 |= EP2_MallocedToken;
  69039. }
  69040. sqlite3DbFree(db, pDup);
  69041. }
  69042. /*
  69043. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  69044. **
  69045. ** Return FALSE if the USING clause is NULL or if it does not contain
  69046. ** zCol.
  69047. */
  69048. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  69049. if( pUsing ){
  69050. int k;
  69051. for(k=0; k<pUsing->nId; k++){
  69052. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  69053. }
  69054. }
  69055. return 0;
  69056. }
  69057. /*
  69058. ** Subqueries stores the original database, table and column names for their
  69059. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  69060. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  69061. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  69062. ** match anything.
  69063. */
  69064. SQLITE_PRIVATE int sqlite3MatchSpanName(
  69065. const char *zSpan,
  69066. const char *zCol,
  69067. const char *zTab,
  69068. const char *zDb
  69069. ){
  69070. int n;
  69071. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  69072. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  69073. return 0;
  69074. }
  69075. zSpan += n+1;
  69076. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  69077. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  69078. return 0;
  69079. }
  69080. zSpan += n+1;
  69081. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  69082. return 0;
  69083. }
  69084. return 1;
  69085. }
  69086. /*
  69087. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  69088. ** that name in the set of source tables in pSrcList and make the pExpr
  69089. ** expression node refer back to that source column. The following changes
  69090. ** are made to pExpr:
  69091. **
  69092. ** pExpr->iDb Set the index in db->aDb[] of the database X
  69093. ** (even if X is implied).
  69094. ** pExpr->iTable Set to the cursor number for the table obtained
  69095. ** from pSrcList.
  69096. ** pExpr->pTab Points to the Table structure of X.Y (even if
  69097. ** X and/or Y are implied.)
  69098. ** pExpr->iColumn Set to the column number within the table.
  69099. ** pExpr->op Set to TK_COLUMN.
  69100. ** pExpr->pLeft Any expression this points to is deleted
  69101. ** pExpr->pRight Any expression this points to is deleted.
  69102. **
  69103. ** The zDb variable is the name of the database (the "X"). This value may be
  69104. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  69105. ** can be used. The zTable variable is the name of the table (the "Y"). This
  69106. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  69107. ** means that the form of the name is Z and that columns from any table
  69108. ** can be used.
  69109. **
  69110. ** If the name cannot be resolved unambiguously, leave an error message
  69111. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  69112. */
  69113. static int lookupName(
  69114. Parse *pParse, /* The parsing context */
  69115. const char *zDb, /* Name of the database containing table, or NULL */
  69116. const char *zTab, /* Name of table containing column, or NULL */
  69117. const char *zCol, /* Name of the column. */
  69118. NameContext *pNC, /* The name context used to resolve the name */
  69119. Expr *pExpr /* Make this EXPR node point to the selected column */
  69120. ){
  69121. int i, j; /* Loop counters */
  69122. int cnt = 0; /* Number of matching column names */
  69123. int cntTab = 0; /* Number of matching table names */
  69124. int nSubquery = 0; /* How many levels of subquery */
  69125. sqlite3 *db = pParse->db; /* The database connection */
  69126. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  69127. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  69128. NameContext *pTopNC = pNC; /* First namecontext in the list */
  69129. Schema *pSchema = 0; /* Schema of the expression */
  69130. int isTrigger = 0;
  69131. assert( pNC ); /* the name context cannot be NULL. */
  69132. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  69133. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  69134. /* Initialize the node to no-match */
  69135. pExpr->iTable = -1;
  69136. pExpr->pTab = 0;
  69137. ExprSetIrreducible(pExpr);
  69138. /* Translate the schema name in zDb into a pointer to the corresponding
  69139. ** schema. If not found, pSchema will remain NULL and nothing will match
  69140. ** resulting in an appropriate error message toward the end of this routine
  69141. */
  69142. if( zDb ){
  69143. for(i=0; i<db->nDb; i++){
  69144. assert( db->aDb[i].zName );
  69145. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  69146. pSchema = db->aDb[i].pSchema;
  69147. break;
  69148. }
  69149. }
  69150. }
  69151. /* Start at the inner-most context and move outward until a match is found */
  69152. while( pNC && cnt==0 ){
  69153. ExprList *pEList;
  69154. SrcList *pSrcList = pNC->pSrcList;
  69155. if( pSrcList ){
  69156. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  69157. Table *pTab;
  69158. Column *pCol;
  69159. pTab = pItem->pTab;
  69160. assert( pTab!=0 && pTab->zName!=0 );
  69161. assert( pTab->nCol>0 );
  69162. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  69163. int hit = 0;
  69164. pEList = pItem->pSelect->pEList;
  69165. for(j=0; j<pEList->nExpr; j++){
  69166. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  69167. cnt++;
  69168. cntTab = 2;
  69169. pMatch = pItem;
  69170. pExpr->iColumn = j;
  69171. hit = 1;
  69172. }
  69173. }
  69174. if( hit || zTab==0 ) continue;
  69175. }
  69176. if( zDb && pTab->pSchema!=pSchema ){
  69177. continue;
  69178. }
  69179. if( zTab ){
  69180. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  69181. assert( zTabName!=0 );
  69182. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  69183. continue;
  69184. }
  69185. }
  69186. if( 0==(cntTab++) ){
  69187. pMatch = pItem;
  69188. }
  69189. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  69190. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  69191. /* If there has been exactly one prior match and this match
  69192. ** is for the right-hand table of a NATURAL JOIN or is in a
  69193. ** USING clause, then skip this match.
  69194. */
  69195. if( cnt==1 ){
  69196. if( pItem->jointype & JT_NATURAL ) continue;
  69197. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  69198. }
  69199. cnt++;
  69200. pMatch = pItem;
  69201. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  69202. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  69203. break;
  69204. }
  69205. }
  69206. }
  69207. if( pMatch ){
  69208. pExpr->iTable = pMatch->iCursor;
  69209. pExpr->pTab = pMatch->pTab;
  69210. pSchema = pExpr->pTab->pSchema;
  69211. }
  69212. } /* if( pSrcList ) */
  69213. #ifndef SQLITE_OMIT_TRIGGER
  69214. /* If we have not already resolved the name, then maybe
  69215. ** it is a new.* or old.* trigger argument reference
  69216. */
  69217. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  69218. int op = pParse->eTriggerOp;
  69219. Table *pTab = 0;
  69220. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  69221. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  69222. pExpr->iTable = 1;
  69223. pTab = pParse->pTriggerTab;
  69224. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  69225. pExpr->iTable = 0;
  69226. pTab = pParse->pTriggerTab;
  69227. }
  69228. if( pTab ){
  69229. int iCol;
  69230. pSchema = pTab->pSchema;
  69231. cntTab++;
  69232. for(iCol=0; iCol<pTab->nCol; iCol++){
  69233. Column *pCol = &pTab->aCol[iCol];
  69234. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  69235. if( iCol==pTab->iPKey ){
  69236. iCol = -1;
  69237. }
  69238. break;
  69239. }
  69240. }
  69241. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  69242. iCol = -1; /* IMP: R-44911-55124 */
  69243. }
  69244. if( iCol<pTab->nCol ){
  69245. cnt++;
  69246. if( iCol<0 ){
  69247. pExpr->affinity = SQLITE_AFF_INTEGER;
  69248. }else if( pExpr->iTable==0 ){
  69249. testcase( iCol==31 );
  69250. testcase( iCol==32 );
  69251. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  69252. }else{
  69253. testcase( iCol==31 );
  69254. testcase( iCol==32 );
  69255. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  69256. }
  69257. pExpr->iColumn = (i16)iCol;
  69258. pExpr->pTab = pTab;
  69259. isTrigger = 1;
  69260. }
  69261. }
  69262. }
  69263. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  69264. /*
  69265. ** Perhaps the name is a reference to the ROWID
  69266. */
  69267. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  69268. cnt = 1;
  69269. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  69270. pExpr->affinity = SQLITE_AFF_INTEGER;
  69271. }
  69272. /*
  69273. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  69274. ** might refer to an result-set alias. This happens, for example, when
  69275. ** we are resolving names in the WHERE clause of the following command:
  69276. **
  69277. ** SELECT a+b AS x FROM table WHERE x<10;
  69278. **
  69279. ** In cases like this, replace pExpr with a copy of the expression that
  69280. ** forms the result set entry ("a+b" in the example) and return immediately.
  69281. ** Note that the expression in the result set should have already been
  69282. ** resolved by the time the WHERE clause is resolved.
  69283. */
  69284. if( (pEList = pNC->pEList)!=0
  69285. && zTab==0
  69286. && ((pNC->ncFlags & NC_AsMaybe)==0 || cnt==0)
  69287. ){
  69288. for(j=0; j<pEList->nExpr; j++){
  69289. char *zAs = pEList->a[j].zName;
  69290. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  69291. Expr *pOrig;
  69292. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  69293. assert( pExpr->x.pList==0 );
  69294. assert( pExpr->x.pSelect==0 );
  69295. pOrig = pEList->a[j].pExpr;
  69296. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  69297. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  69298. return WRC_Abort;
  69299. }
  69300. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  69301. cnt = 1;
  69302. pMatch = 0;
  69303. assert( zTab==0 && zDb==0 );
  69304. goto lookupname_end;
  69305. }
  69306. }
  69307. }
  69308. /* Advance to the next name context. The loop will exit when either
  69309. ** we have a match (cnt>0) or when we run out of name contexts.
  69310. */
  69311. if( cnt==0 ){
  69312. pNC = pNC->pNext;
  69313. nSubquery++;
  69314. }
  69315. }
  69316. /*
  69317. ** If X and Y are NULL (in other words if only the column name Z is
  69318. ** supplied) and the value of Z is enclosed in double-quotes, then
  69319. ** Z is a string literal if it doesn't match any column names. In that
  69320. ** case, we need to return right away and not make any changes to
  69321. ** pExpr.
  69322. **
  69323. ** Because no reference was made to outer contexts, the pNC->nRef
  69324. ** fields are not changed in any context.
  69325. */
  69326. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  69327. pExpr->op = TK_STRING;
  69328. pExpr->pTab = 0;
  69329. return WRC_Prune;
  69330. }
  69331. /*
  69332. ** cnt==0 means there was not match. cnt>1 means there were two or
  69333. ** more matches. Either way, we have an error.
  69334. */
  69335. if( cnt!=1 ){
  69336. const char *zErr;
  69337. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  69338. if( zDb ){
  69339. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  69340. }else if( zTab ){
  69341. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  69342. }else{
  69343. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  69344. }
  69345. pParse->checkSchema = 1;
  69346. pTopNC->nErr++;
  69347. }
  69348. /* If a column from a table in pSrcList is referenced, then record
  69349. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  69350. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  69351. ** column number is greater than the number of bits in the bitmask
  69352. ** then set the high-order bit of the bitmask.
  69353. */
  69354. if( pExpr->iColumn>=0 && pMatch!=0 ){
  69355. int n = pExpr->iColumn;
  69356. testcase( n==BMS-1 );
  69357. if( n>=BMS ){
  69358. n = BMS-1;
  69359. }
  69360. assert( pMatch->iCursor==pExpr->iTable );
  69361. pMatch->colUsed |= ((Bitmask)1)<<n;
  69362. }
  69363. /* Clean up and return
  69364. */
  69365. sqlite3ExprDelete(db, pExpr->pLeft);
  69366. pExpr->pLeft = 0;
  69367. sqlite3ExprDelete(db, pExpr->pRight);
  69368. pExpr->pRight = 0;
  69369. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  69370. lookupname_end:
  69371. if( cnt==1 ){
  69372. assert( pNC!=0 );
  69373. if( pExpr->op!=TK_AS ){
  69374. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  69375. }
  69376. /* Increment the nRef value on all name contexts from TopNC up to
  69377. ** the point where the name matched. */
  69378. for(;;){
  69379. assert( pTopNC!=0 );
  69380. pTopNC->nRef++;
  69381. if( pTopNC==pNC ) break;
  69382. pTopNC = pTopNC->pNext;
  69383. }
  69384. return WRC_Prune;
  69385. } else {
  69386. return WRC_Abort;
  69387. }
  69388. }
  69389. /*
  69390. ** Allocate and return a pointer to an expression to load the column iCol
  69391. ** from datasource iSrc in SrcList pSrc.
  69392. */
  69393. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  69394. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  69395. if( p ){
  69396. struct SrcList_item *pItem = &pSrc->a[iSrc];
  69397. p->pTab = pItem->pTab;
  69398. p->iTable = pItem->iCursor;
  69399. if( p->pTab->iPKey==iCol ){
  69400. p->iColumn = -1;
  69401. }else{
  69402. p->iColumn = (ynVar)iCol;
  69403. testcase( iCol==BMS );
  69404. testcase( iCol==BMS-1 );
  69405. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  69406. }
  69407. ExprSetProperty(p, EP_Resolved);
  69408. }
  69409. return p;
  69410. }
  69411. /*
  69412. ** This routine is callback for sqlite3WalkExpr().
  69413. **
  69414. ** Resolve symbolic names into TK_COLUMN operators for the current
  69415. ** node in the expression tree. Return 0 to continue the search down
  69416. ** the tree or 2 to abort the tree walk.
  69417. **
  69418. ** This routine also does error checking and name resolution for
  69419. ** function names. The operator for aggregate functions is changed
  69420. ** to TK_AGG_FUNCTION.
  69421. */
  69422. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  69423. NameContext *pNC;
  69424. Parse *pParse;
  69425. pNC = pWalker->u.pNC;
  69426. assert( pNC!=0 );
  69427. pParse = pNC->pParse;
  69428. assert( pParse==pWalker->pParse );
  69429. if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  69430. ExprSetProperty(pExpr, EP_Resolved);
  69431. #ifndef NDEBUG
  69432. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  69433. SrcList *pSrcList = pNC->pSrcList;
  69434. int i;
  69435. for(i=0; i<pNC->pSrcList->nSrc; i++){
  69436. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  69437. }
  69438. }
  69439. #endif
  69440. switch( pExpr->op ){
  69441. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  69442. /* The special operator TK_ROW means use the rowid for the first
  69443. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  69444. ** clause processing on UPDATE and DELETE statements.
  69445. */
  69446. case TK_ROW: {
  69447. SrcList *pSrcList = pNC->pSrcList;
  69448. struct SrcList_item *pItem;
  69449. assert( pSrcList && pSrcList->nSrc==1 );
  69450. pItem = pSrcList->a;
  69451. pExpr->op = TK_COLUMN;
  69452. pExpr->pTab = pItem->pTab;
  69453. pExpr->iTable = pItem->iCursor;
  69454. pExpr->iColumn = -1;
  69455. pExpr->affinity = SQLITE_AFF_INTEGER;
  69456. break;
  69457. }
  69458. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  69459. /* A lone identifier is the name of a column.
  69460. */
  69461. case TK_ID: {
  69462. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  69463. }
  69464. /* A table name and column name: ID.ID
  69465. ** Or a database, table and column: ID.ID.ID
  69466. */
  69467. case TK_DOT: {
  69468. const char *zColumn;
  69469. const char *zTable;
  69470. const char *zDb;
  69471. Expr *pRight;
  69472. /* if( pSrcList==0 ) break; */
  69473. pRight = pExpr->pRight;
  69474. if( pRight->op==TK_ID ){
  69475. zDb = 0;
  69476. zTable = pExpr->pLeft->u.zToken;
  69477. zColumn = pRight->u.zToken;
  69478. }else{
  69479. assert( pRight->op==TK_DOT );
  69480. zDb = pExpr->pLeft->u.zToken;
  69481. zTable = pRight->pLeft->u.zToken;
  69482. zColumn = pRight->pRight->u.zToken;
  69483. }
  69484. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  69485. }
  69486. /* Resolve function names
  69487. */
  69488. case TK_CONST_FUNC:
  69489. case TK_FUNCTION: {
  69490. ExprList *pList = pExpr->x.pList; /* The argument list */
  69491. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  69492. int no_such_func = 0; /* True if no such function exists */
  69493. int wrong_num_args = 0; /* True if wrong number of arguments */
  69494. int is_agg = 0; /* True if is an aggregate function */
  69495. int auth; /* Authorization to use the function */
  69496. int nId; /* Number of characters in function name */
  69497. const char *zId; /* The function name. */
  69498. FuncDef *pDef; /* Information about the function */
  69499. u8 enc = ENC(pParse->db); /* The database encoding */
  69500. testcase( pExpr->op==TK_CONST_FUNC );
  69501. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  69502. zId = pExpr->u.zToken;
  69503. nId = sqlite3Strlen30(zId);
  69504. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  69505. if( pDef==0 ){
  69506. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  69507. if( pDef==0 ){
  69508. no_such_func = 1;
  69509. }else{
  69510. wrong_num_args = 1;
  69511. }
  69512. }else{
  69513. is_agg = pDef->xFunc==0;
  69514. }
  69515. #ifndef SQLITE_OMIT_AUTHORIZATION
  69516. if( pDef ){
  69517. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  69518. if( auth!=SQLITE_OK ){
  69519. if( auth==SQLITE_DENY ){
  69520. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  69521. pDef->zName);
  69522. pNC->nErr++;
  69523. }
  69524. pExpr->op = TK_NULL;
  69525. return WRC_Prune;
  69526. }
  69527. }
  69528. #endif
  69529. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  69530. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  69531. pNC->nErr++;
  69532. is_agg = 0;
  69533. }else if( no_such_func && pParse->db->init.busy==0 ){
  69534. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  69535. pNC->nErr++;
  69536. }else if( wrong_num_args ){
  69537. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  69538. nId, zId);
  69539. pNC->nErr++;
  69540. }
  69541. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  69542. sqlite3WalkExprList(pWalker, pList);
  69543. if( is_agg ){
  69544. NameContext *pNC2 = pNC;
  69545. pExpr->op = TK_AGG_FUNCTION;
  69546. pExpr->op2 = 0;
  69547. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  69548. pExpr->op2++;
  69549. pNC2 = pNC2->pNext;
  69550. }
  69551. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  69552. pNC->ncFlags |= NC_AllowAgg;
  69553. }
  69554. /* FIX ME: Compute pExpr->affinity based on the expected return
  69555. ** type of the function
  69556. */
  69557. return WRC_Prune;
  69558. }
  69559. #ifndef SQLITE_OMIT_SUBQUERY
  69560. case TK_SELECT:
  69561. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  69562. #endif
  69563. case TK_IN: {
  69564. testcase( pExpr->op==TK_IN );
  69565. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  69566. int nRef = pNC->nRef;
  69567. #ifndef SQLITE_OMIT_CHECK
  69568. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  69569. sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
  69570. }
  69571. #endif
  69572. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  69573. assert( pNC->nRef>=nRef );
  69574. if( nRef!=pNC->nRef ){
  69575. ExprSetProperty(pExpr, EP_VarSelect);
  69576. }
  69577. }
  69578. break;
  69579. }
  69580. #ifndef SQLITE_OMIT_CHECK
  69581. case TK_VARIABLE: {
  69582. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  69583. sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
  69584. }
  69585. break;
  69586. }
  69587. #endif
  69588. }
  69589. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  69590. }
  69591. /*
  69592. ** pEList is a list of expressions which are really the result set of the
  69593. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  69594. ** This routine checks to see if pE is a simple identifier which corresponds
  69595. ** to the AS-name of one of the terms of the expression list. If it is,
  69596. ** this routine return an integer between 1 and N where N is the number of
  69597. ** elements in pEList, corresponding to the matching entry. If there is
  69598. ** no match, or if pE is not a simple identifier, then this routine
  69599. ** return 0.
  69600. **
  69601. ** pEList has been resolved. pE has not.
  69602. */
  69603. static int resolveAsName(
  69604. Parse *pParse, /* Parsing context for error messages */
  69605. ExprList *pEList, /* List of expressions to scan */
  69606. Expr *pE /* Expression we are trying to match */
  69607. ){
  69608. int i; /* Loop counter */
  69609. UNUSED_PARAMETER(pParse);
  69610. if( pE->op==TK_ID ){
  69611. char *zCol = pE->u.zToken;
  69612. for(i=0; i<pEList->nExpr; i++){
  69613. char *zAs = pEList->a[i].zName;
  69614. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  69615. return i+1;
  69616. }
  69617. }
  69618. }
  69619. return 0;
  69620. }
  69621. /*
  69622. ** pE is a pointer to an expression which is a single term in the
  69623. ** ORDER BY of a compound SELECT. The expression has not been
  69624. ** name resolved.
  69625. **
  69626. ** At the point this routine is called, we already know that the
  69627. ** ORDER BY term is not an integer index into the result set. That
  69628. ** case is handled by the calling routine.
  69629. **
  69630. ** Attempt to match pE against result set columns in the left-most
  69631. ** SELECT statement. Return the index i of the matching column,
  69632. ** as an indication to the caller that it should sort by the i-th column.
  69633. ** The left-most column is 1. In other words, the value returned is the
  69634. ** same integer value that would be used in the SQL statement to indicate
  69635. ** the column.
  69636. **
  69637. ** If there is no match, return 0. Return -1 if an error occurs.
  69638. */
  69639. static int resolveOrderByTermToExprList(
  69640. Parse *pParse, /* Parsing context for error messages */
  69641. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  69642. Expr *pE /* The specific ORDER BY term */
  69643. ){
  69644. int i; /* Loop counter */
  69645. ExprList *pEList; /* The columns of the result set */
  69646. NameContext nc; /* Name context for resolving pE */
  69647. sqlite3 *db; /* Database connection */
  69648. int rc; /* Return code from subprocedures */
  69649. u8 savedSuppErr; /* Saved value of db->suppressErr */
  69650. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  69651. pEList = pSelect->pEList;
  69652. /* Resolve all names in the ORDER BY term expression
  69653. */
  69654. memset(&nc, 0, sizeof(nc));
  69655. nc.pParse = pParse;
  69656. nc.pSrcList = pSelect->pSrc;
  69657. nc.pEList = pEList;
  69658. nc.ncFlags = NC_AllowAgg;
  69659. nc.nErr = 0;
  69660. db = pParse->db;
  69661. savedSuppErr = db->suppressErr;
  69662. db->suppressErr = 1;
  69663. rc = sqlite3ResolveExprNames(&nc, pE);
  69664. db->suppressErr = savedSuppErr;
  69665. if( rc ) return 0;
  69666. /* Try to match the ORDER BY expression against an expression
  69667. ** in the result set. Return an 1-based index of the matching
  69668. ** result-set entry.
  69669. */
  69670. for(i=0; i<pEList->nExpr; i++){
  69671. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
  69672. return i+1;
  69673. }
  69674. }
  69675. /* If no match, return 0. */
  69676. return 0;
  69677. }
  69678. /*
  69679. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  69680. */
  69681. static void resolveOutOfRangeError(
  69682. Parse *pParse, /* The error context into which to write the error */
  69683. const char *zType, /* "ORDER" or "GROUP" */
  69684. int i, /* The index (1-based) of the term out of range */
  69685. int mx /* Largest permissible value of i */
  69686. ){
  69687. sqlite3ErrorMsg(pParse,
  69688. "%r %s BY term out of range - should be "
  69689. "between 1 and %d", i, zType, mx);
  69690. }
  69691. /*
  69692. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  69693. ** each term of the ORDER BY clause is a constant integer between 1
  69694. ** and N where N is the number of columns in the compound SELECT.
  69695. **
  69696. ** ORDER BY terms that are already an integer between 1 and N are
  69697. ** unmodified. ORDER BY terms that are integers outside the range of
  69698. ** 1 through N generate an error. ORDER BY terms that are expressions
  69699. ** are matched against result set expressions of compound SELECT
  69700. ** beginning with the left-most SELECT and working toward the right.
  69701. ** At the first match, the ORDER BY expression is transformed into
  69702. ** the integer column number.
  69703. **
  69704. ** Return the number of errors seen.
  69705. */
  69706. static int resolveCompoundOrderBy(
  69707. Parse *pParse, /* Parsing context. Leave error messages here */
  69708. Select *pSelect /* The SELECT statement containing the ORDER BY */
  69709. ){
  69710. int i;
  69711. ExprList *pOrderBy;
  69712. ExprList *pEList;
  69713. sqlite3 *db;
  69714. int moreToDo = 1;
  69715. pOrderBy = pSelect->pOrderBy;
  69716. if( pOrderBy==0 ) return 0;
  69717. db = pParse->db;
  69718. #if SQLITE_MAX_COLUMN
  69719. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  69720. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  69721. return 1;
  69722. }
  69723. #endif
  69724. for(i=0; i<pOrderBy->nExpr; i++){
  69725. pOrderBy->a[i].done = 0;
  69726. }
  69727. pSelect->pNext = 0;
  69728. while( pSelect->pPrior ){
  69729. pSelect->pPrior->pNext = pSelect;
  69730. pSelect = pSelect->pPrior;
  69731. }
  69732. while( pSelect && moreToDo ){
  69733. struct ExprList_item *pItem;
  69734. moreToDo = 0;
  69735. pEList = pSelect->pEList;
  69736. assert( pEList!=0 );
  69737. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  69738. int iCol = -1;
  69739. Expr *pE, *pDup;
  69740. if( pItem->done ) continue;
  69741. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  69742. if( sqlite3ExprIsInteger(pE, &iCol) ){
  69743. if( iCol<=0 || iCol>pEList->nExpr ){
  69744. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  69745. return 1;
  69746. }
  69747. }else{
  69748. iCol = resolveAsName(pParse, pEList, pE);
  69749. if( iCol==0 ){
  69750. pDup = sqlite3ExprDup(db, pE, 0);
  69751. if( !db->mallocFailed ){
  69752. assert(pDup);
  69753. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  69754. }
  69755. sqlite3ExprDelete(db, pDup);
  69756. }
  69757. }
  69758. if( iCol>0 ){
  69759. /* Convert the ORDER BY term into an integer column number iCol,
  69760. ** taking care to preserve the COLLATE clause if it exists */
  69761. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  69762. if( pNew==0 ) return 1;
  69763. pNew->flags |= EP_IntValue;
  69764. pNew->u.iValue = iCol;
  69765. if( pItem->pExpr==pE ){
  69766. pItem->pExpr = pNew;
  69767. }else{
  69768. assert( pItem->pExpr->op==TK_COLLATE );
  69769. assert( pItem->pExpr->pLeft==pE );
  69770. pItem->pExpr->pLeft = pNew;
  69771. }
  69772. sqlite3ExprDelete(db, pE);
  69773. pItem->iOrderByCol = (u16)iCol;
  69774. pItem->done = 1;
  69775. }else{
  69776. moreToDo = 1;
  69777. }
  69778. }
  69779. pSelect = pSelect->pNext;
  69780. }
  69781. for(i=0; i<pOrderBy->nExpr; i++){
  69782. if( pOrderBy->a[i].done==0 ){
  69783. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  69784. "column in the result set", i+1);
  69785. return 1;
  69786. }
  69787. }
  69788. return 0;
  69789. }
  69790. /*
  69791. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  69792. ** the SELECT statement pSelect. If any term is reference to a
  69793. ** result set expression (as determined by the ExprList.a.iCol field)
  69794. ** then convert that term into a copy of the corresponding result set
  69795. ** column.
  69796. **
  69797. ** If any errors are detected, add an error message to pParse and
  69798. ** return non-zero. Return zero if no errors are seen.
  69799. */
  69800. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  69801. Parse *pParse, /* Parsing context. Leave error messages here */
  69802. Select *pSelect, /* The SELECT statement containing the clause */
  69803. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  69804. const char *zType /* "ORDER" or "GROUP" */
  69805. ){
  69806. int i;
  69807. sqlite3 *db = pParse->db;
  69808. ExprList *pEList;
  69809. struct ExprList_item *pItem;
  69810. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  69811. #if SQLITE_MAX_COLUMN
  69812. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  69813. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  69814. return 1;
  69815. }
  69816. #endif
  69817. pEList = pSelect->pEList;
  69818. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  69819. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  69820. if( pItem->iOrderByCol ){
  69821. if( pItem->iOrderByCol>pEList->nExpr ){
  69822. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  69823. return 1;
  69824. }
  69825. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  69826. }
  69827. }
  69828. return 0;
  69829. }
  69830. /*
  69831. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  69832. ** The Name context of the SELECT statement is pNC. zType is either
  69833. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  69834. **
  69835. ** This routine resolves each term of the clause into an expression.
  69836. ** If the order-by term is an integer I between 1 and N (where N is the
  69837. ** number of columns in the result set of the SELECT) then the expression
  69838. ** in the resolution is a copy of the I-th result-set expression. If
  69839. ** the order-by term is an identify that corresponds to the AS-name of
  69840. ** a result-set expression, then the term resolves to a copy of the
  69841. ** result-set expression. Otherwise, the expression is resolved in
  69842. ** the usual way - using sqlite3ResolveExprNames().
  69843. **
  69844. ** This routine returns the number of errors. If errors occur, then
  69845. ** an appropriate error message might be left in pParse. (OOM errors
  69846. ** excepted.)
  69847. */
  69848. static int resolveOrderGroupBy(
  69849. NameContext *pNC, /* The name context of the SELECT statement */
  69850. Select *pSelect, /* The SELECT statement holding pOrderBy */
  69851. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  69852. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  69853. ){
  69854. int i, j; /* Loop counters */
  69855. int iCol; /* Column number */
  69856. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  69857. Parse *pParse; /* Parsing context */
  69858. int nResult; /* Number of terms in the result set */
  69859. if( pOrderBy==0 ) return 0;
  69860. nResult = pSelect->pEList->nExpr;
  69861. pParse = pNC->pParse;
  69862. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  69863. Expr *pE = pItem->pExpr;
  69864. iCol = resolveAsName(pParse, pSelect->pEList, pE);
  69865. if( iCol>0 ){
  69866. /* If an AS-name match is found, mark this ORDER BY column as being
  69867. ** a copy of the iCol-th result-set column. The subsequent call to
  69868. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  69869. ** copy of the iCol-th result-set expression. */
  69870. pItem->iOrderByCol = (u16)iCol;
  69871. continue;
  69872. }
  69873. if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
  69874. /* The ORDER BY term is an integer constant. Again, set the column
  69875. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  69876. ** order-by term to a copy of the result-set expression */
  69877. if( iCol<1 || iCol>0xffff ){
  69878. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  69879. return 1;
  69880. }
  69881. pItem->iOrderByCol = (u16)iCol;
  69882. continue;
  69883. }
  69884. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  69885. pItem->iOrderByCol = 0;
  69886. if( sqlite3ResolveExprNames(pNC, pE) ){
  69887. return 1;
  69888. }
  69889. for(j=0; j<pSelect->pEList->nExpr; j++){
  69890. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
  69891. pItem->iOrderByCol = j+1;
  69892. }
  69893. }
  69894. }
  69895. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  69896. }
  69897. /*
  69898. ** Resolve names in the SELECT statement p and all of its descendents.
  69899. */
  69900. static int resolveSelectStep(Walker *pWalker, Select *p){
  69901. NameContext *pOuterNC; /* Context that contains this SELECT */
  69902. NameContext sNC; /* Name context of this SELECT */
  69903. int isCompound; /* True if p is a compound select */
  69904. int nCompound; /* Number of compound terms processed so far */
  69905. Parse *pParse; /* Parsing context */
  69906. ExprList *pEList; /* Result set expression list */
  69907. int i; /* Loop counter */
  69908. ExprList *pGroupBy; /* The GROUP BY clause */
  69909. Select *pLeftmost; /* Left-most of SELECT of a compound */
  69910. sqlite3 *db; /* Database connection */
  69911. assert( p!=0 );
  69912. if( p->selFlags & SF_Resolved ){
  69913. return WRC_Prune;
  69914. }
  69915. pOuterNC = pWalker->u.pNC;
  69916. pParse = pWalker->pParse;
  69917. db = pParse->db;
  69918. /* Normally sqlite3SelectExpand() will be called first and will have
  69919. ** already expanded this SELECT. However, if this is a subquery within
  69920. ** an expression, sqlite3ResolveExprNames() will be called without a
  69921. ** prior call to sqlite3SelectExpand(). When that happens, let
  69922. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  69923. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  69924. ** this routine in the correct order.
  69925. */
  69926. if( (p->selFlags & SF_Expanded)==0 ){
  69927. sqlite3SelectPrep(pParse, p, pOuterNC);
  69928. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  69929. }
  69930. isCompound = p->pPrior!=0;
  69931. nCompound = 0;
  69932. pLeftmost = p;
  69933. while( p ){
  69934. assert( (p->selFlags & SF_Expanded)!=0 );
  69935. assert( (p->selFlags & SF_Resolved)==0 );
  69936. p->selFlags |= SF_Resolved;
  69937. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  69938. ** are not allowed to refer to any names, so pass an empty NameContext.
  69939. */
  69940. memset(&sNC, 0, sizeof(sNC));
  69941. sNC.pParse = pParse;
  69942. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  69943. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  69944. return WRC_Abort;
  69945. }
  69946. /* Recursively resolve names in all subqueries
  69947. */
  69948. for(i=0; i<p->pSrc->nSrc; i++){
  69949. struct SrcList_item *pItem = &p->pSrc->a[i];
  69950. if( pItem->pSelect ){
  69951. NameContext *pNC; /* Used to iterate name contexts */
  69952. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  69953. const char *zSavedContext = pParse->zAuthContext;
  69954. /* Count the total number of references to pOuterNC and all of its
  69955. ** parent contexts. After resolving references to expressions in
  69956. ** pItem->pSelect, check if this value has changed. If so, then
  69957. ** SELECT statement pItem->pSelect must be correlated. Set the
  69958. ** pItem->isCorrelated flag if this is the case. */
  69959. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  69960. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  69961. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  69962. pParse->zAuthContext = zSavedContext;
  69963. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  69964. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  69965. assert( pItem->isCorrelated==0 && nRef<=0 );
  69966. pItem->isCorrelated = (nRef!=0);
  69967. }
  69968. }
  69969. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  69970. ** resolve the result-set expression list.
  69971. */
  69972. sNC.ncFlags = NC_AllowAgg;
  69973. sNC.pSrcList = p->pSrc;
  69974. sNC.pNext = pOuterNC;
  69975. /* Resolve names in the result set. */
  69976. pEList = p->pEList;
  69977. assert( pEList!=0 );
  69978. for(i=0; i<pEList->nExpr; i++){
  69979. Expr *pX = pEList->a[i].pExpr;
  69980. if( sqlite3ResolveExprNames(&sNC, pX) ){
  69981. return WRC_Abort;
  69982. }
  69983. }
  69984. /* If there are no aggregate functions in the result-set, and no GROUP BY
  69985. ** expression, do not allow aggregates in any of the other expressions.
  69986. */
  69987. assert( (p->selFlags & SF_Aggregate)==0 );
  69988. pGroupBy = p->pGroupBy;
  69989. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  69990. p->selFlags |= SF_Aggregate;
  69991. }else{
  69992. sNC.ncFlags &= ~NC_AllowAgg;
  69993. }
  69994. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  69995. */
  69996. if( p->pHaving && !pGroupBy ){
  69997. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  69998. return WRC_Abort;
  69999. }
  70000. /* Add the expression list to the name-context before parsing the
  70001. ** other expressions in the SELECT statement. This is so that
  70002. ** expressions in the WHERE clause (etc.) can refer to expressions by
  70003. ** aliases in the result set.
  70004. **
  70005. ** Minor point: If this is the case, then the expression will be
  70006. ** re-evaluated for each reference to it.
  70007. */
  70008. sNC.pEList = p->pEList;
  70009. sNC.ncFlags |= NC_AsMaybe;
  70010. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  70011. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  70012. sNC.ncFlags &= ~NC_AsMaybe;
  70013. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  70014. ** outer queries
  70015. */
  70016. sNC.pNext = 0;
  70017. sNC.ncFlags |= NC_AllowAgg;
  70018. /* Process the ORDER BY clause for singleton SELECT statements.
  70019. ** The ORDER BY clause for compounds SELECT statements is handled
  70020. ** below, after all of the result-sets for all of the elements of
  70021. ** the compound have been resolved.
  70022. */
  70023. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  70024. return WRC_Abort;
  70025. }
  70026. if( db->mallocFailed ){
  70027. return WRC_Abort;
  70028. }
  70029. /* Resolve the GROUP BY clause. At the same time, make sure
  70030. ** the GROUP BY clause does not contain aggregate functions.
  70031. */
  70032. if( pGroupBy ){
  70033. struct ExprList_item *pItem;
  70034. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  70035. return WRC_Abort;
  70036. }
  70037. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  70038. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  70039. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  70040. "the GROUP BY clause");
  70041. return WRC_Abort;
  70042. }
  70043. }
  70044. }
  70045. /* Advance to the next term of the compound
  70046. */
  70047. p = p->pPrior;
  70048. nCompound++;
  70049. }
  70050. /* Resolve the ORDER BY on a compound SELECT after all terms of
  70051. ** the compound have been resolved.
  70052. */
  70053. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  70054. return WRC_Abort;
  70055. }
  70056. return WRC_Prune;
  70057. }
  70058. /*
  70059. ** This routine walks an expression tree and resolves references to
  70060. ** table columns and result-set columns. At the same time, do error
  70061. ** checking on function usage and set a flag if any aggregate functions
  70062. ** are seen.
  70063. **
  70064. ** To resolve table columns references we look for nodes (or subtrees) of the
  70065. ** form X.Y.Z or Y.Z or just Z where
  70066. **
  70067. ** X: The name of a database. Ex: "main" or "temp" or
  70068. ** the symbolic name assigned to an ATTACH-ed database.
  70069. **
  70070. ** Y: The name of a table in a FROM clause. Or in a trigger
  70071. ** one of the special names "old" or "new".
  70072. **
  70073. ** Z: The name of a column in table Y.
  70074. **
  70075. ** The node at the root of the subtree is modified as follows:
  70076. **
  70077. ** Expr.op Changed to TK_COLUMN
  70078. ** Expr.pTab Points to the Table object for X.Y
  70079. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  70080. ** Expr.iTable The VDBE cursor number for X.Y
  70081. **
  70082. **
  70083. ** To resolve result-set references, look for expression nodes of the
  70084. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  70085. ** size of an AS clause in the result-set of a SELECT. The Z expression
  70086. ** is replaced by a copy of the left-hand side of the result-set expression.
  70087. ** Table-name and function resolution occurs on the substituted expression
  70088. ** tree. For example, in:
  70089. **
  70090. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  70091. **
  70092. ** The "x" term of the order by is replaced by "a+b" to render:
  70093. **
  70094. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  70095. **
  70096. ** Function calls are checked to make sure that the function is
  70097. ** defined and that the correct number of arguments are specified.
  70098. ** If the function is an aggregate function, then the NC_HasAgg flag is
  70099. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  70100. ** If an expression contains aggregate functions then the EP_Agg
  70101. ** property on the expression is set.
  70102. **
  70103. ** An error message is left in pParse if anything is amiss. The number
  70104. ** if errors is returned.
  70105. */
  70106. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  70107. NameContext *pNC, /* Namespace to resolve expressions in. */
  70108. Expr *pExpr /* The expression to be analyzed. */
  70109. ){
  70110. u8 savedHasAgg;
  70111. Walker w;
  70112. if( pExpr==0 ) return 0;
  70113. #if SQLITE_MAX_EXPR_DEPTH>0
  70114. {
  70115. Parse *pParse = pNC->pParse;
  70116. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  70117. return 1;
  70118. }
  70119. pParse->nHeight += pExpr->nHeight;
  70120. }
  70121. #endif
  70122. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  70123. pNC->ncFlags &= ~NC_HasAgg;
  70124. memset(&w, 0, sizeof(w));
  70125. w.xExprCallback = resolveExprStep;
  70126. w.xSelectCallback = resolveSelectStep;
  70127. w.pParse = pNC->pParse;
  70128. w.u.pNC = pNC;
  70129. sqlite3WalkExpr(&w, pExpr);
  70130. #if SQLITE_MAX_EXPR_DEPTH>0
  70131. pNC->pParse->nHeight -= pExpr->nHeight;
  70132. #endif
  70133. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  70134. ExprSetProperty(pExpr, EP_Error);
  70135. }
  70136. if( pNC->ncFlags & NC_HasAgg ){
  70137. ExprSetProperty(pExpr, EP_Agg);
  70138. }else if( savedHasAgg ){
  70139. pNC->ncFlags |= NC_HasAgg;
  70140. }
  70141. return ExprHasProperty(pExpr, EP_Error);
  70142. }
  70143. /*
  70144. ** Resolve all names in all expressions of a SELECT and in all
  70145. ** decendents of the SELECT, including compounds off of p->pPrior,
  70146. ** subqueries in expressions, and subqueries used as FROM clause
  70147. ** terms.
  70148. **
  70149. ** See sqlite3ResolveExprNames() for a description of the kinds of
  70150. ** transformations that occur.
  70151. **
  70152. ** All SELECT statements should have been expanded using
  70153. ** sqlite3SelectExpand() prior to invoking this routine.
  70154. */
  70155. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  70156. Parse *pParse, /* The parser context */
  70157. Select *p, /* The SELECT statement being coded. */
  70158. NameContext *pOuterNC /* Name context for parent SELECT statement */
  70159. ){
  70160. Walker w;
  70161. assert( p!=0 );
  70162. memset(&w, 0, sizeof(w));
  70163. w.xExprCallback = resolveExprStep;
  70164. w.xSelectCallback = resolveSelectStep;
  70165. w.pParse = pParse;
  70166. w.u.pNC = pOuterNC;
  70167. sqlite3WalkSelect(&w, p);
  70168. }
  70169. /************** End of resolve.c *********************************************/
  70170. /************** Begin file expr.c ********************************************/
  70171. /*
  70172. ** 2001 September 15
  70173. **
  70174. ** The author disclaims copyright to this source code. In place of
  70175. ** a legal notice, here is a blessing:
  70176. **
  70177. ** May you do good and not evil.
  70178. ** May you find forgiveness for yourself and forgive others.
  70179. ** May you share freely, never taking more than you give.
  70180. **
  70181. *************************************************************************
  70182. ** This file contains routines used for analyzing expressions and
  70183. ** for generating VDBE code that evaluates expressions in SQLite.
  70184. */
  70185. /*
  70186. ** Return the 'affinity' of the expression pExpr if any.
  70187. **
  70188. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  70189. ** or a sub-select with a column as the return value, then the
  70190. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  70191. ** indicating no affinity for the expression.
  70192. **
  70193. ** i.e. the WHERE clause expresssions in the following statements all
  70194. ** have an affinity:
  70195. **
  70196. ** CREATE TABLE t1(a);
  70197. ** SELECT * FROM t1 WHERE a;
  70198. ** SELECT a AS b FROM t1 WHERE b;
  70199. ** SELECT * FROM t1 WHERE (select a from t1);
  70200. */
  70201. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  70202. int op;
  70203. pExpr = sqlite3ExprSkipCollate(pExpr);
  70204. op = pExpr->op;
  70205. if( op==TK_SELECT ){
  70206. assert( pExpr->flags&EP_xIsSelect );
  70207. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  70208. }
  70209. #ifndef SQLITE_OMIT_CAST
  70210. if( op==TK_CAST ){
  70211. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  70212. return sqlite3AffinityType(pExpr->u.zToken);
  70213. }
  70214. #endif
  70215. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  70216. && pExpr->pTab!=0
  70217. ){
  70218. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  70219. ** a TK_COLUMN but was previously evaluated and cached in a register */
  70220. int j = pExpr->iColumn;
  70221. if( j<0 ) return SQLITE_AFF_INTEGER;
  70222. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  70223. return pExpr->pTab->aCol[j].affinity;
  70224. }
  70225. return pExpr->affinity;
  70226. }
  70227. /*
  70228. ** Set the collating sequence for expression pExpr to be the collating
  70229. ** sequence named by pToken. Return a pointer to a new Expr node that
  70230. ** implements the COLLATE operator.
  70231. **
  70232. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  70233. ** and the pExpr parameter is returned unchanged.
  70234. */
  70235. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  70236. if( pCollName->n>0 ){
  70237. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  70238. if( pNew ){
  70239. pNew->pLeft = pExpr;
  70240. pNew->flags |= EP_Collate;
  70241. pExpr = pNew;
  70242. }
  70243. }
  70244. return pExpr;
  70245. }
  70246. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  70247. Token s;
  70248. assert( zC!=0 );
  70249. s.z = zC;
  70250. s.n = sqlite3Strlen30(s.z);
  70251. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  70252. }
  70253. /*
  70254. ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
  70255. ** an expression.
  70256. */
  70257. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  70258. while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
  70259. pExpr = pExpr->pLeft;
  70260. }
  70261. return pExpr;
  70262. }
  70263. /*
  70264. ** Return the collation sequence for the expression pExpr. If
  70265. ** there is no defined collating sequence, return NULL.
  70266. **
  70267. ** The collating sequence might be determined by a COLLATE operator
  70268. ** or by the presence of a column with a defined collating sequence.
  70269. ** COLLATE operators take first precedence. Left operands take
  70270. ** precedence over right operands.
  70271. */
  70272. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  70273. sqlite3 *db = pParse->db;
  70274. CollSeq *pColl = 0;
  70275. Expr *p = pExpr;
  70276. while( p ){
  70277. int op = p->op;
  70278. if( op==TK_CAST || op==TK_UPLUS ){
  70279. p = p->pLeft;
  70280. continue;
  70281. }
  70282. assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
  70283. if( op==TK_COLLATE ){
  70284. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  70285. break;
  70286. }
  70287. if( p->pTab!=0
  70288. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  70289. || op==TK_REGISTER || op==TK_TRIGGER)
  70290. ){
  70291. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  70292. ** a TK_COLUMN but was previously evaluated and cached in a register */
  70293. int j = p->iColumn;
  70294. if( j>=0 ){
  70295. const char *zColl = p->pTab->aCol[j].zColl;
  70296. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  70297. }
  70298. break;
  70299. }
  70300. if( p->flags & EP_Collate ){
  70301. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  70302. p = p->pLeft;
  70303. }else{
  70304. p = p->pRight;
  70305. }
  70306. }else{
  70307. break;
  70308. }
  70309. }
  70310. if( sqlite3CheckCollSeq(pParse, pColl) ){
  70311. pColl = 0;
  70312. }
  70313. return pColl;
  70314. }
  70315. /*
  70316. ** pExpr is an operand of a comparison operator. aff2 is the
  70317. ** type affinity of the other operand. This routine returns the
  70318. ** type affinity that should be used for the comparison operator.
  70319. */
  70320. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  70321. char aff1 = sqlite3ExprAffinity(pExpr);
  70322. if( aff1 && aff2 ){
  70323. /* Both sides of the comparison are columns. If one has numeric
  70324. ** affinity, use that. Otherwise use no affinity.
  70325. */
  70326. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  70327. return SQLITE_AFF_NUMERIC;
  70328. }else{
  70329. return SQLITE_AFF_NONE;
  70330. }
  70331. }else if( !aff1 && !aff2 ){
  70332. /* Neither side of the comparison is a column. Compare the
  70333. ** results directly.
  70334. */
  70335. return SQLITE_AFF_NONE;
  70336. }else{
  70337. /* One side is a column, the other is not. Use the columns affinity. */
  70338. assert( aff1==0 || aff2==0 );
  70339. return (aff1 + aff2);
  70340. }
  70341. }
  70342. /*
  70343. ** pExpr is a comparison operator. Return the type affinity that should
  70344. ** be applied to both operands prior to doing the comparison.
  70345. */
  70346. static char comparisonAffinity(Expr *pExpr){
  70347. char aff;
  70348. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  70349. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  70350. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  70351. assert( pExpr->pLeft );
  70352. aff = sqlite3ExprAffinity(pExpr->pLeft);
  70353. if( pExpr->pRight ){
  70354. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  70355. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  70356. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  70357. }else if( !aff ){
  70358. aff = SQLITE_AFF_NONE;
  70359. }
  70360. return aff;
  70361. }
  70362. /*
  70363. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  70364. ** idx_affinity is the affinity of an indexed column. Return true
  70365. ** if the index with affinity idx_affinity may be used to implement
  70366. ** the comparison in pExpr.
  70367. */
  70368. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  70369. char aff = comparisonAffinity(pExpr);
  70370. switch( aff ){
  70371. case SQLITE_AFF_NONE:
  70372. return 1;
  70373. case SQLITE_AFF_TEXT:
  70374. return idx_affinity==SQLITE_AFF_TEXT;
  70375. default:
  70376. return sqlite3IsNumericAffinity(idx_affinity);
  70377. }
  70378. }
  70379. /*
  70380. ** Return the P5 value that should be used for a binary comparison
  70381. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  70382. */
  70383. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  70384. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  70385. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  70386. return aff;
  70387. }
  70388. /*
  70389. ** Return a pointer to the collation sequence that should be used by
  70390. ** a binary comparison operator comparing pLeft and pRight.
  70391. **
  70392. ** If the left hand expression has a collating sequence type, then it is
  70393. ** used. Otherwise the collation sequence for the right hand expression
  70394. ** is used, or the default (BINARY) if neither expression has a collating
  70395. ** type.
  70396. **
  70397. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  70398. ** it is not considered.
  70399. */
  70400. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  70401. Parse *pParse,
  70402. Expr *pLeft,
  70403. Expr *pRight
  70404. ){
  70405. CollSeq *pColl;
  70406. assert( pLeft );
  70407. if( pLeft->flags & EP_Collate ){
  70408. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  70409. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  70410. pColl = sqlite3ExprCollSeq(pParse, pRight);
  70411. }else{
  70412. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  70413. if( !pColl ){
  70414. pColl = sqlite3ExprCollSeq(pParse, pRight);
  70415. }
  70416. }
  70417. return pColl;
  70418. }
  70419. /*
  70420. ** Generate code for a comparison operator.
  70421. */
  70422. static int codeCompare(
  70423. Parse *pParse, /* The parsing (and code generating) context */
  70424. Expr *pLeft, /* The left operand */
  70425. Expr *pRight, /* The right operand */
  70426. int opcode, /* The comparison opcode */
  70427. int in1, int in2, /* Register holding operands */
  70428. int dest, /* Jump here if true. */
  70429. int jumpIfNull /* If true, jump if either operand is NULL */
  70430. ){
  70431. int p5;
  70432. int addr;
  70433. CollSeq *p4;
  70434. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  70435. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  70436. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  70437. (void*)p4, P4_COLLSEQ);
  70438. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  70439. return addr;
  70440. }
  70441. #if SQLITE_MAX_EXPR_DEPTH>0
  70442. /*
  70443. ** Check that argument nHeight is less than or equal to the maximum
  70444. ** expression depth allowed. If it is not, leave an error message in
  70445. ** pParse.
  70446. */
  70447. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  70448. int rc = SQLITE_OK;
  70449. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  70450. if( nHeight>mxHeight ){
  70451. sqlite3ErrorMsg(pParse,
  70452. "Expression tree is too large (maximum depth %d)", mxHeight
  70453. );
  70454. rc = SQLITE_ERROR;
  70455. }
  70456. return rc;
  70457. }
  70458. /* The following three functions, heightOfExpr(), heightOfExprList()
  70459. ** and heightOfSelect(), are used to determine the maximum height
  70460. ** of any expression tree referenced by the structure passed as the
  70461. ** first argument.
  70462. **
  70463. ** If this maximum height is greater than the current value pointed
  70464. ** to by pnHeight, the second parameter, then set *pnHeight to that
  70465. ** value.
  70466. */
  70467. static void heightOfExpr(Expr *p, int *pnHeight){
  70468. if( p ){
  70469. if( p->nHeight>*pnHeight ){
  70470. *pnHeight = p->nHeight;
  70471. }
  70472. }
  70473. }
  70474. static void heightOfExprList(ExprList *p, int *pnHeight){
  70475. if( p ){
  70476. int i;
  70477. for(i=0; i<p->nExpr; i++){
  70478. heightOfExpr(p->a[i].pExpr, pnHeight);
  70479. }
  70480. }
  70481. }
  70482. static void heightOfSelect(Select *p, int *pnHeight){
  70483. if( p ){
  70484. heightOfExpr(p->pWhere, pnHeight);
  70485. heightOfExpr(p->pHaving, pnHeight);
  70486. heightOfExpr(p->pLimit, pnHeight);
  70487. heightOfExpr(p->pOffset, pnHeight);
  70488. heightOfExprList(p->pEList, pnHeight);
  70489. heightOfExprList(p->pGroupBy, pnHeight);
  70490. heightOfExprList(p->pOrderBy, pnHeight);
  70491. heightOfSelect(p->pPrior, pnHeight);
  70492. }
  70493. }
  70494. /*
  70495. ** Set the Expr.nHeight variable in the structure passed as an
  70496. ** argument. An expression with no children, Expr.pList or
  70497. ** Expr.pSelect member has a height of 1. Any other expression
  70498. ** has a height equal to the maximum height of any other
  70499. ** referenced Expr plus one.
  70500. */
  70501. static void exprSetHeight(Expr *p){
  70502. int nHeight = 0;
  70503. heightOfExpr(p->pLeft, &nHeight);
  70504. heightOfExpr(p->pRight, &nHeight);
  70505. if( ExprHasProperty(p, EP_xIsSelect) ){
  70506. heightOfSelect(p->x.pSelect, &nHeight);
  70507. }else{
  70508. heightOfExprList(p->x.pList, &nHeight);
  70509. }
  70510. p->nHeight = nHeight + 1;
  70511. }
  70512. /*
  70513. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  70514. ** the height is greater than the maximum allowed expression depth,
  70515. ** leave an error in pParse.
  70516. */
  70517. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  70518. exprSetHeight(p);
  70519. sqlite3ExprCheckHeight(pParse, p->nHeight);
  70520. }
  70521. /*
  70522. ** Return the maximum height of any expression tree referenced
  70523. ** by the select statement passed as an argument.
  70524. */
  70525. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  70526. int nHeight = 0;
  70527. heightOfSelect(p, &nHeight);
  70528. return nHeight;
  70529. }
  70530. #else
  70531. #define exprSetHeight(y)
  70532. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  70533. /*
  70534. ** This routine is the core allocator for Expr nodes.
  70535. **
  70536. ** Construct a new expression node and return a pointer to it. Memory
  70537. ** for this node and for the pToken argument is a single allocation
  70538. ** obtained from sqlite3DbMalloc(). The calling function
  70539. ** is responsible for making sure the node eventually gets freed.
  70540. **
  70541. ** If dequote is true, then the token (if it exists) is dequoted.
  70542. ** If dequote is false, no dequoting is performance. The deQuote
  70543. ** parameter is ignored if pToken is NULL or if the token does not
  70544. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  70545. ** then the EP_DblQuoted flag is set on the expression node.
  70546. **
  70547. ** Special case: If op==TK_INTEGER and pToken points to a string that
  70548. ** can be translated into a 32-bit integer, then the token is not
  70549. ** stored in u.zToken. Instead, the integer values is written
  70550. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  70551. ** is allocated to hold the integer text and the dequote flag is ignored.
  70552. */
  70553. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  70554. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  70555. int op, /* Expression opcode */
  70556. const Token *pToken, /* Token argument. Might be NULL */
  70557. int dequote /* True to dequote */
  70558. ){
  70559. Expr *pNew;
  70560. int nExtra = 0;
  70561. int iValue = 0;
  70562. if( pToken ){
  70563. if( op!=TK_INTEGER || pToken->z==0
  70564. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  70565. nExtra = pToken->n+1;
  70566. assert( iValue>=0 );
  70567. }
  70568. }
  70569. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  70570. if( pNew ){
  70571. pNew->op = (u8)op;
  70572. pNew->iAgg = -1;
  70573. if( pToken ){
  70574. if( nExtra==0 ){
  70575. pNew->flags |= EP_IntValue;
  70576. pNew->u.iValue = iValue;
  70577. }else{
  70578. int c;
  70579. pNew->u.zToken = (char*)&pNew[1];
  70580. assert( pToken->z!=0 || pToken->n==0 );
  70581. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  70582. pNew->u.zToken[pToken->n] = 0;
  70583. if( dequote && nExtra>=3
  70584. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  70585. sqlite3Dequote(pNew->u.zToken);
  70586. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  70587. }
  70588. }
  70589. }
  70590. #if SQLITE_MAX_EXPR_DEPTH>0
  70591. pNew->nHeight = 1;
  70592. #endif
  70593. }
  70594. return pNew;
  70595. }
  70596. /*
  70597. ** Allocate a new expression node from a zero-terminated token that has
  70598. ** already been dequoted.
  70599. */
  70600. SQLITE_PRIVATE Expr *sqlite3Expr(
  70601. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  70602. int op, /* Expression opcode */
  70603. const char *zToken /* Token argument. Might be NULL */
  70604. ){
  70605. Token x;
  70606. x.z = zToken;
  70607. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  70608. return sqlite3ExprAlloc(db, op, &x, 0);
  70609. }
  70610. /*
  70611. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  70612. **
  70613. ** If pRoot==NULL that means that a memory allocation error has occurred.
  70614. ** In that case, delete the subtrees pLeft and pRight.
  70615. */
  70616. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  70617. sqlite3 *db,
  70618. Expr *pRoot,
  70619. Expr *pLeft,
  70620. Expr *pRight
  70621. ){
  70622. if( pRoot==0 ){
  70623. assert( db->mallocFailed );
  70624. sqlite3ExprDelete(db, pLeft);
  70625. sqlite3ExprDelete(db, pRight);
  70626. }else{
  70627. if( pRight ){
  70628. pRoot->pRight = pRight;
  70629. pRoot->flags |= EP_Collate & pRight->flags;
  70630. }
  70631. if( pLeft ){
  70632. pRoot->pLeft = pLeft;
  70633. pRoot->flags |= EP_Collate & pLeft->flags;
  70634. }
  70635. exprSetHeight(pRoot);
  70636. }
  70637. }
  70638. /*
  70639. ** Allocate a Expr node which joins as many as two subtrees.
  70640. **
  70641. ** One or both of the subtrees can be NULL. Return a pointer to the new
  70642. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  70643. ** free the subtrees and return NULL.
  70644. */
  70645. SQLITE_PRIVATE Expr *sqlite3PExpr(
  70646. Parse *pParse, /* Parsing context */
  70647. int op, /* Expression opcode */
  70648. Expr *pLeft, /* Left operand */
  70649. Expr *pRight, /* Right operand */
  70650. const Token *pToken /* Argument token */
  70651. ){
  70652. Expr *p;
  70653. if( op==TK_AND && pLeft && pRight ){
  70654. /* Take advantage of short-circuit false optimization for AND */
  70655. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  70656. }else{
  70657. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  70658. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  70659. }
  70660. if( p ) {
  70661. sqlite3ExprCheckHeight(pParse, p->nHeight);
  70662. }
  70663. return p;
  70664. }
  70665. /*
  70666. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  70667. ** expression might be true. This is an optimization. If is OK to
  70668. ** return 0 here even if the expression really is always false (a
  70669. ** false negative). But it is a bug to return 1 if the expression
  70670. ** might be true in some rare circumstances (a false positive.)
  70671. **
  70672. ** Note that if the expression is part of conditional for a
  70673. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  70674. ** is it true or false, so always return 0.
  70675. */
  70676. static int exprAlwaysFalse(Expr *p){
  70677. int v = 0;
  70678. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  70679. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  70680. return v==0;
  70681. }
  70682. /*
  70683. ** Join two expressions using an AND operator. If either expression is
  70684. ** NULL, then just return the other expression.
  70685. **
  70686. ** If one side or the other of the AND is known to be false, then instead
  70687. ** of returning an AND expression, just return a constant expression with
  70688. ** a value of false.
  70689. */
  70690. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  70691. if( pLeft==0 ){
  70692. return pRight;
  70693. }else if( pRight==0 ){
  70694. return pLeft;
  70695. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  70696. sqlite3ExprDelete(db, pLeft);
  70697. sqlite3ExprDelete(db, pRight);
  70698. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  70699. }else{
  70700. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  70701. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  70702. return pNew;
  70703. }
  70704. }
  70705. /*
  70706. ** Construct a new expression node for a function with multiple
  70707. ** arguments.
  70708. */
  70709. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  70710. Expr *pNew;
  70711. sqlite3 *db = pParse->db;
  70712. assert( pToken );
  70713. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  70714. if( pNew==0 ){
  70715. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  70716. return 0;
  70717. }
  70718. pNew->x.pList = pList;
  70719. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  70720. sqlite3ExprSetHeight(pParse, pNew);
  70721. return pNew;
  70722. }
  70723. /*
  70724. ** Assign a variable number to an expression that encodes a wildcard
  70725. ** in the original SQL statement.
  70726. **
  70727. ** Wildcards consisting of a single "?" are assigned the next sequential
  70728. ** variable number.
  70729. **
  70730. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  70731. ** sure "nnn" is not too be to avoid a denial of service attack when
  70732. ** the SQL statement comes from an external source.
  70733. **
  70734. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  70735. ** as the previous instance of the same wildcard. Or if this is the first
  70736. ** instance of the wildcard, the next sequenial variable number is
  70737. ** assigned.
  70738. */
  70739. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  70740. sqlite3 *db = pParse->db;
  70741. const char *z;
  70742. if( pExpr==0 ) return;
  70743. assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  70744. z = pExpr->u.zToken;
  70745. assert( z!=0 );
  70746. assert( z[0]!=0 );
  70747. if( z[1]==0 ){
  70748. /* Wildcard of the form "?". Assign the next variable number */
  70749. assert( z[0]=='?' );
  70750. pExpr->iColumn = (ynVar)(++pParse->nVar);
  70751. }else{
  70752. ynVar x = 0;
  70753. u32 n = sqlite3Strlen30(z);
  70754. if( z[0]=='?' ){
  70755. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  70756. ** use it as the variable number */
  70757. i64 i;
  70758. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  70759. pExpr->iColumn = x = (ynVar)i;
  70760. testcase( i==0 );
  70761. testcase( i==1 );
  70762. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  70763. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  70764. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  70765. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  70766. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  70767. x = 0;
  70768. }
  70769. if( i>pParse->nVar ){
  70770. pParse->nVar = (int)i;
  70771. }
  70772. }else{
  70773. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  70774. ** number as the prior appearance of the same name, or if the name
  70775. ** has never appeared before, reuse the same variable number
  70776. */
  70777. ynVar i;
  70778. for(i=0; i<pParse->nzVar; i++){
  70779. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  70780. pExpr->iColumn = x = (ynVar)i+1;
  70781. break;
  70782. }
  70783. }
  70784. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  70785. }
  70786. if( x>0 ){
  70787. if( x>pParse->nzVar ){
  70788. char **a;
  70789. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  70790. if( a==0 ) return; /* Error reported through db->mallocFailed */
  70791. pParse->azVar = a;
  70792. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  70793. pParse->nzVar = x;
  70794. }
  70795. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  70796. sqlite3DbFree(db, pParse->azVar[x-1]);
  70797. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  70798. }
  70799. }
  70800. }
  70801. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  70802. sqlite3ErrorMsg(pParse, "too many SQL variables");
  70803. }
  70804. }
  70805. /*
  70806. ** Recursively delete an expression tree.
  70807. */
  70808. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  70809. if( p==0 ) return;
  70810. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  70811. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  70812. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  70813. sqlite3ExprDelete(db, p->pLeft);
  70814. sqlite3ExprDelete(db, p->pRight);
  70815. if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
  70816. sqlite3DbFree(db, p->u.zToken);
  70817. }
  70818. if( ExprHasProperty(p, EP_xIsSelect) ){
  70819. sqlite3SelectDelete(db, p->x.pSelect);
  70820. }else{
  70821. sqlite3ExprListDelete(db, p->x.pList);
  70822. }
  70823. }
  70824. if( !ExprHasProperty(p, EP_Static) ){
  70825. sqlite3DbFree(db, p);
  70826. }
  70827. }
  70828. /*
  70829. ** Return the number of bytes allocated for the expression structure
  70830. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  70831. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  70832. */
  70833. static int exprStructSize(Expr *p){
  70834. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  70835. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  70836. return EXPR_FULLSIZE;
  70837. }
  70838. /*
  70839. ** The dupedExpr*Size() routines each return the number of bytes required
  70840. ** to store a copy of an expression or expression tree. They differ in
  70841. ** how much of the tree is measured.
  70842. **
  70843. ** dupedExprStructSize() Size of only the Expr structure
  70844. ** dupedExprNodeSize() Size of Expr + space for token
  70845. ** dupedExprSize() Expr + token + subtree components
  70846. **
  70847. ***************************************************************************
  70848. **
  70849. ** The dupedExprStructSize() function returns two values OR-ed together:
  70850. ** (1) the space required for a copy of the Expr structure only and
  70851. ** (2) the EP_xxx flags that indicate what the structure size should be.
  70852. ** The return values is always one of:
  70853. **
  70854. ** EXPR_FULLSIZE
  70855. ** EXPR_REDUCEDSIZE | EP_Reduced
  70856. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  70857. **
  70858. ** The size of the structure can be found by masking the return value
  70859. ** of this routine with 0xfff. The flags can be found by masking the
  70860. ** return value with EP_Reduced|EP_TokenOnly.
  70861. **
  70862. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  70863. ** (unreduced) Expr objects as they or originally constructed by the parser.
  70864. ** During expression analysis, extra information is computed and moved into
  70865. ** later parts of teh Expr object and that extra information might get chopped
  70866. ** off if the expression is reduced. Note also that it does not work to
  70867. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  70868. ** to reduce a pristine expression tree from the parser. The implementation
  70869. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  70870. ** to enforce this constraint.
  70871. */
  70872. static int dupedExprStructSize(Expr *p, int flags){
  70873. int nSize;
  70874. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  70875. if( 0==(flags&EXPRDUP_REDUCE) ){
  70876. nSize = EXPR_FULLSIZE;
  70877. }else{
  70878. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  70879. assert( !ExprHasProperty(p, EP_FromJoin) );
  70880. assert( (p->flags2 & EP2_MallocedToken)==0 );
  70881. assert( (p->flags2 & EP2_Irreducible)==0 );
  70882. if( p->pLeft || p->pRight || p->x.pList ){
  70883. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  70884. }else{
  70885. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  70886. }
  70887. }
  70888. return nSize;
  70889. }
  70890. /*
  70891. ** This function returns the space in bytes required to store the copy
  70892. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  70893. ** string is defined.)
  70894. */
  70895. static int dupedExprNodeSize(Expr *p, int flags){
  70896. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  70897. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  70898. nByte += sqlite3Strlen30(p->u.zToken)+1;
  70899. }
  70900. return ROUND8(nByte);
  70901. }
  70902. /*
  70903. ** Return the number of bytes required to create a duplicate of the
  70904. ** expression passed as the first argument. The second argument is a
  70905. ** mask containing EXPRDUP_XXX flags.
  70906. **
  70907. ** The value returned includes space to create a copy of the Expr struct
  70908. ** itself and the buffer referred to by Expr.u.zToken, if any.
  70909. **
  70910. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  70911. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  70912. ** and Expr.pRight variables (but not for any structures pointed to or
  70913. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  70914. */
  70915. static int dupedExprSize(Expr *p, int flags){
  70916. int nByte = 0;
  70917. if( p ){
  70918. nByte = dupedExprNodeSize(p, flags);
  70919. if( flags&EXPRDUP_REDUCE ){
  70920. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  70921. }
  70922. }
  70923. return nByte;
  70924. }
  70925. /*
  70926. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  70927. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  70928. ** to store the copy of expression p, the copies of p->u.zToken
  70929. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  70930. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  70931. ** portion of the buffer copied into by this function.
  70932. */
  70933. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  70934. Expr *pNew = 0; /* Value to return */
  70935. if( p ){
  70936. const int isReduced = (flags&EXPRDUP_REDUCE);
  70937. u8 *zAlloc;
  70938. u32 staticFlag = 0;
  70939. assert( pzBuffer==0 || isReduced );
  70940. /* Figure out where to write the new Expr structure. */
  70941. if( pzBuffer ){
  70942. zAlloc = *pzBuffer;
  70943. staticFlag = EP_Static;
  70944. }else{
  70945. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  70946. }
  70947. pNew = (Expr *)zAlloc;
  70948. if( pNew ){
  70949. /* Set nNewSize to the size allocated for the structure pointed to
  70950. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  70951. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  70952. ** by the copy of the p->u.zToken string (if any).
  70953. */
  70954. const unsigned nStructSize = dupedExprStructSize(p, flags);
  70955. const int nNewSize = nStructSize & 0xfff;
  70956. int nToken;
  70957. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  70958. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  70959. }else{
  70960. nToken = 0;
  70961. }
  70962. if( isReduced ){
  70963. assert( ExprHasProperty(p, EP_Reduced)==0 );
  70964. memcpy(zAlloc, p, nNewSize);
  70965. }else{
  70966. int nSize = exprStructSize(p);
  70967. memcpy(zAlloc, p, nSize);
  70968. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  70969. }
  70970. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  70971. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
  70972. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  70973. pNew->flags |= staticFlag;
  70974. /* Copy the p->u.zToken string, if any. */
  70975. if( nToken ){
  70976. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  70977. memcpy(zToken, p->u.zToken, nToken);
  70978. }
  70979. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  70980. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  70981. if( ExprHasProperty(p, EP_xIsSelect) ){
  70982. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  70983. }else{
  70984. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  70985. }
  70986. }
  70987. /* Fill in pNew->pLeft and pNew->pRight. */
  70988. if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  70989. zAlloc += dupedExprNodeSize(p, flags);
  70990. if( ExprHasProperty(pNew, EP_Reduced) ){
  70991. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  70992. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  70993. }
  70994. if( pzBuffer ){
  70995. *pzBuffer = zAlloc;
  70996. }
  70997. }else{
  70998. pNew->flags2 = 0;
  70999. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  71000. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  71001. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  71002. }
  71003. }
  71004. }
  71005. }
  71006. return pNew;
  71007. }
  71008. /*
  71009. ** The following group of routines make deep copies of expressions,
  71010. ** expression lists, ID lists, and select statements. The copies can
  71011. ** be deleted (by being passed to their respective ...Delete() routines)
  71012. ** without effecting the originals.
  71013. **
  71014. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  71015. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  71016. ** by subsequent calls to sqlite*ListAppend() routines.
  71017. **
  71018. ** Any tables that the SrcList might point to are not duplicated.
  71019. **
  71020. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  71021. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  71022. ** truncated version of the usual Expr structure that will be stored as
  71023. ** part of the in-memory representation of the database schema.
  71024. */
  71025. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  71026. return exprDup(db, p, flags, 0);
  71027. }
  71028. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  71029. ExprList *pNew;
  71030. struct ExprList_item *pItem, *pOldItem;
  71031. int i;
  71032. if( p==0 ) return 0;
  71033. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  71034. if( pNew==0 ) return 0;
  71035. pNew->iECursor = 0;
  71036. pNew->nExpr = i = p->nExpr;
  71037. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  71038. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  71039. if( pItem==0 ){
  71040. sqlite3DbFree(db, pNew);
  71041. return 0;
  71042. }
  71043. pOldItem = p->a;
  71044. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  71045. Expr *pOldExpr = pOldItem->pExpr;
  71046. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  71047. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  71048. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  71049. pItem->sortOrder = pOldItem->sortOrder;
  71050. pItem->done = 0;
  71051. pItem->iOrderByCol = pOldItem->iOrderByCol;
  71052. pItem->iAlias = pOldItem->iAlias;
  71053. }
  71054. return pNew;
  71055. }
  71056. /*
  71057. ** If cursors, triggers, views and subqueries are all omitted from
  71058. ** the build, then none of the following routines, except for
  71059. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  71060. ** called with a NULL argument.
  71061. */
  71062. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  71063. || !defined(SQLITE_OMIT_SUBQUERY)
  71064. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  71065. SrcList *pNew;
  71066. int i;
  71067. int nByte;
  71068. if( p==0 ) return 0;
  71069. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  71070. pNew = sqlite3DbMallocRaw(db, nByte );
  71071. if( pNew==0 ) return 0;
  71072. pNew->nSrc = pNew->nAlloc = p->nSrc;
  71073. for(i=0; i<p->nSrc; i++){
  71074. struct SrcList_item *pNewItem = &pNew->a[i];
  71075. struct SrcList_item *pOldItem = &p->a[i];
  71076. Table *pTab;
  71077. pNewItem->pSchema = pOldItem->pSchema;
  71078. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  71079. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  71080. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  71081. pNewItem->jointype = pOldItem->jointype;
  71082. pNewItem->iCursor = pOldItem->iCursor;
  71083. pNewItem->addrFillSub = pOldItem->addrFillSub;
  71084. pNewItem->regReturn = pOldItem->regReturn;
  71085. pNewItem->isCorrelated = pOldItem->isCorrelated;
  71086. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  71087. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  71088. pNewItem->notIndexed = pOldItem->notIndexed;
  71089. pNewItem->pIndex = pOldItem->pIndex;
  71090. pTab = pNewItem->pTab = pOldItem->pTab;
  71091. if( pTab ){
  71092. pTab->nRef++;
  71093. }
  71094. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  71095. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  71096. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  71097. pNewItem->colUsed = pOldItem->colUsed;
  71098. }
  71099. return pNew;
  71100. }
  71101. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  71102. IdList *pNew;
  71103. int i;
  71104. if( p==0 ) return 0;
  71105. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  71106. if( pNew==0 ) return 0;
  71107. pNew->nId = p->nId;
  71108. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  71109. if( pNew->a==0 ){
  71110. sqlite3DbFree(db, pNew);
  71111. return 0;
  71112. }
  71113. /* Note that because the size of the allocation for p->a[] is not
  71114. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  71115. ** on the duplicate created by this function. */
  71116. for(i=0; i<p->nId; i++){
  71117. struct IdList_item *pNewItem = &pNew->a[i];
  71118. struct IdList_item *pOldItem = &p->a[i];
  71119. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  71120. pNewItem->idx = pOldItem->idx;
  71121. }
  71122. return pNew;
  71123. }
  71124. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  71125. Select *pNew, *pPrior;
  71126. if( p==0 ) return 0;
  71127. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  71128. if( pNew==0 ) return 0;
  71129. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  71130. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  71131. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  71132. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  71133. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  71134. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  71135. pNew->op = p->op;
  71136. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  71137. if( pPrior ) pPrior->pNext = pNew;
  71138. pNew->pNext = 0;
  71139. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  71140. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  71141. pNew->iLimit = 0;
  71142. pNew->iOffset = 0;
  71143. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  71144. pNew->pRightmost = 0;
  71145. pNew->addrOpenEphm[0] = -1;
  71146. pNew->addrOpenEphm[1] = -1;
  71147. pNew->addrOpenEphm[2] = -1;
  71148. return pNew;
  71149. }
  71150. #else
  71151. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  71152. assert( p==0 );
  71153. return 0;
  71154. }
  71155. #endif
  71156. /*
  71157. ** Add a new element to the end of an expression list. If pList is
  71158. ** initially NULL, then create a new expression list.
  71159. **
  71160. ** If a memory allocation error occurs, the entire list is freed and
  71161. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  71162. ** that the new entry was successfully appended.
  71163. */
  71164. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  71165. Parse *pParse, /* Parsing context */
  71166. ExprList *pList, /* List to which to append. Might be NULL */
  71167. Expr *pExpr /* Expression to be appended. Might be NULL */
  71168. ){
  71169. sqlite3 *db = pParse->db;
  71170. if( pList==0 ){
  71171. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  71172. if( pList==0 ){
  71173. goto no_mem;
  71174. }
  71175. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  71176. if( pList->a==0 ) goto no_mem;
  71177. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  71178. struct ExprList_item *a;
  71179. assert( pList->nExpr>0 );
  71180. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  71181. if( a==0 ){
  71182. goto no_mem;
  71183. }
  71184. pList->a = a;
  71185. }
  71186. assert( pList->a!=0 );
  71187. if( 1 ){
  71188. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  71189. memset(pItem, 0, sizeof(*pItem));
  71190. pItem->pExpr = pExpr;
  71191. }
  71192. return pList;
  71193. no_mem:
  71194. /* Avoid leaking memory if malloc has failed. */
  71195. sqlite3ExprDelete(db, pExpr);
  71196. sqlite3ExprListDelete(db, pList);
  71197. return 0;
  71198. }
  71199. /*
  71200. ** Set the ExprList.a[].zName element of the most recently added item
  71201. ** on the expression list.
  71202. **
  71203. ** pList might be NULL following an OOM error. But pName should never be
  71204. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  71205. ** is set.
  71206. */
  71207. SQLITE_PRIVATE void sqlite3ExprListSetName(
  71208. Parse *pParse, /* Parsing context */
  71209. ExprList *pList, /* List to which to add the span. */
  71210. Token *pName, /* Name to be added */
  71211. int dequote /* True to cause the name to be dequoted */
  71212. ){
  71213. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  71214. if( pList ){
  71215. struct ExprList_item *pItem;
  71216. assert( pList->nExpr>0 );
  71217. pItem = &pList->a[pList->nExpr-1];
  71218. assert( pItem->zName==0 );
  71219. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  71220. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  71221. }
  71222. }
  71223. /*
  71224. ** Set the ExprList.a[].zSpan element of the most recently added item
  71225. ** on the expression list.
  71226. **
  71227. ** pList might be NULL following an OOM error. But pSpan should never be
  71228. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  71229. ** is set.
  71230. */
  71231. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  71232. Parse *pParse, /* Parsing context */
  71233. ExprList *pList, /* List to which to add the span. */
  71234. ExprSpan *pSpan /* The span to be added */
  71235. ){
  71236. sqlite3 *db = pParse->db;
  71237. assert( pList!=0 || db->mallocFailed!=0 );
  71238. if( pList ){
  71239. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  71240. assert( pList->nExpr>0 );
  71241. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  71242. sqlite3DbFree(db, pItem->zSpan);
  71243. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  71244. (int)(pSpan->zEnd - pSpan->zStart));
  71245. }
  71246. }
  71247. /*
  71248. ** If the expression list pEList contains more than iLimit elements,
  71249. ** leave an error message in pParse.
  71250. */
  71251. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  71252. Parse *pParse,
  71253. ExprList *pEList,
  71254. const char *zObject
  71255. ){
  71256. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  71257. testcase( pEList && pEList->nExpr==mx );
  71258. testcase( pEList && pEList->nExpr==mx+1 );
  71259. if( pEList && pEList->nExpr>mx ){
  71260. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  71261. }
  71262. }
  71263. /*
  71264. ** Delete an entire expression list.
  71265. */
  71266. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  71267. int i;
  71268. struct ExprList_item *pItem;
  71269. if( pList==0 ) return;
  71270. assert( pList->a!=0 || pList->nExpr==0 );
  71271. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  71272. sqlite3ExprDelete(db, pItem->pExpr);
  71273. sqlite3DbFree(db, pItem->zName);
  71274. sqlite3DbFree(db, pItem->zSpan);
  71275. }
  71276. sqlite3DbFree(db, pList->a);
  71277. sqlite3DbFree(db, pList);
  71278. }
  71279. /*
  71280. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  71281. ** to an integer. These routines are checking an expression to see
  71282. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  71283. ** not constant.
  71284. **
  71285. ** These callback routines are used to implement the following:
  71286. **
  71287. ** sqlite3ExprIsConstant()
  71288. ** sqlite3ExprIsConstantNotJoin()
  71289. ** sqlite3ExprIsConstantOrFunction()
  71290. **
  71291. */
  71292. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  71293. /* If pWalker->u.i is 3 then any term of the expression that comes from
  71294. ** the ON or USING clauses of a join disqualifies the expression
  71295. ** from being considered constant. */
  71296. if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
  71297. pWalker->u.i = 0;
  71298. return WRC_Abort;
  71299. }
  71300. switch( pExpr->op ){
  71301. /* Consider functions to be constant if all their arguments are constant
  71302. ** and pWalker->u.i==2 */
  71303. case TK_FUNCTION:
  71304. if( pWalker->u.i==2 ) return 0;
  71305. /* Fall through */
  71306. case TK_ID:
  71307. case TK_COLUMN:
  71308. case TK_AGG_FUNCTION:
  71309. case TK_AGG_COLUMN:
  71310. testcase( pExpr->op==TK_ID );
  71311. testcase( pExpr->op==TK_COLUMN );
  71312. testcase( pExpr->op==TK_AGG_FUNCTION );
  71313. testcase( pExpr->op==TK_AGG_COLUMN );
  71314. pWalker->u.i = 0;
  71315. return WRC_Abort;
  71316. default:
  71317. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  71318. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  71319. return WRC_Continue;
  71320. }
  71321. }
  71322. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  71323. UNUSED_PARAMETER(NotUsed);
  71324. pWalker->u.i = 0;
  71325. return WRC_Abort;
  71326. }
  71327. static int exprIsConst(Expr *p, int initFlag){
  71328. Walker w;
  71329. memset(&w, 0, sizeof(w));
  71330. w.u.i = initFlag;
  71331. w.xExprCallback = exprNodeIsConstant;
  71332. w.xSelectCallback = selectNodeIsConstant;
  71333. sqlite3WalkExpr(&w, p);
  71334. return w.u.i;
  71335. }
  71336. /*
  71337. ** Walk an expression tree. Return 1 if the expression is constant
  71338. ** and 0 if it involves variables or function calls.
  71339. **
  71340. ** For the purposes of this function, a double-quoted string (ex: "abc")
  71341. ** is considered a variable but a single-quoted string (ex: 'abc') is
  71342. ** a constant.
  71343. */
  71344. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  71345. return exprIsConst(p, 1);
  71346. }
  71347. /*
  71348. ** Walk an expression tree. Return 1 if the expression is constant
  71349. ** that does no originate from the ON or USING clauses of a join.
  71350. ** Return 0 if it involves variables or function calls or terms from
  71351. ** an ON or USING clause.
  71352. */
  71353. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  71354. return exprIsConst(p, 3);
  71355. }
  71356. /*
  71357. ** Walk an expression tree. Return 1 if the expression is constant
  71358. ** or a function call with constant arguments. Return and 0 if there
  71359. ** are any variables.
  71360. **
  71361. ** For the purposes of this function, a double-quoted string (ex: "abc")
  71362. ** is considered a variable but a single-quoted string (ex: 'abc') is
  71363. ** a constant.
  71364. */
  71365. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  71366. return exprIsConst(p, 2);
  71367. }
  71368. /*
  71369. ** If the expression p codes a constant integer that is small enough
  71370. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  71371. ** in *pValue. If the expression is not an integer or if it is too big
  71372. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  71373. */
  71374. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  71375. int rc = 0;
  71376. /* If an expression is an integer literal that fits in a signed 32-bit
  71377. ** integer, then the EP_IntValue flag will have already been set */
  71378. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  71379. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  71380. if( p->flags & EP_IntValue ){
  71381. *pValue = p->u.iValue;
  71382. return 1;
  71383. }
  71384. switch( p->op ){
  71385. case TK_UPLUS: {
  71386. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  71387. break;
  71388. }
  71389. case TK_UMINUS: {
  71390. int v;
  71391. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  71392. *pValue = -v;
  71393. rc = 1;
  71394. }
  71395. break;
  71396. }
  71397. default: break;
  71398. }
  71399. return rc;
  71400. }
  71401. /*
  71402. ** Return FALSE if there is no chance that the expression can be NULL.
  71403. **
  71404. ** If the expression might be NULL or if the expression is too complex
  71405. ** to tell return TRUE.
  71406. **
  71407. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  71408. ** when we know that a value cannot be NULL. Hence, a false positive
  71409. ** (returning TRUE when in fact the expression can never be NULL) might
  71410. ** be a small performance hit but is otherwise harmless. On the other
  71411. ** hand, a false negative (returning FALSE when the result could be NULL)
  71412. ** will likely result in an incorrect answer. So when in doubt, return
  71413. ** TRUE.
  71414. */
  71415. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  71416. u8 op;
  71417. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  71418. op = p->op;
  71419. if( op==TK_REGISTER ) op = p->op2;
  71420. switch( op ){
  71421. case TK_INTEGER:
  71422. case TK_STRING:
  71423. case TK_FLOAT:
  71424. case TK_BLOB:
  71425. return 0;
  71426. default:
  71427. return 1;
  71428. }
  71429. }
  71430. /*
  71431. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  71432. ** to location iDest if the value in iReg is NULL. The value in iReg
  71433. ** was computed by pExpr. If we can look at pExpr at compile-time and
  71434. ** determine that it can never generate a NULL, then the OP_IsNull operation
  71435. ** can be omitted.
  71436. */
  71437. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  71438. Vdbe *v, /* The VDBE under construction */
  71439. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  71440. int iReg, /* Test the value in this register for NULL */
  71441. int iDest /* Jump here if the value is null */
  71442. ){
  71443. if( sqlite3ExprCanBeNull(pExpr) ){
  71444. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  71445. }
  71446. }
  71447. /*
  71448. ** Return TRUE if the given expression is a constant which would be
  71449. ** unchanged by OP_Affinity with the affinity given in the second
  71450. ** argument.
  71451. **
  71452. ** This routine is used to determine if the OP_Affinity operation
  71453. ** can be omitted. When in doubt return FALSE. A false negative
  71454. ** is harmless. A false positive, however, can result in the wrong
  71455. ** answer.
  71456. */
  71457. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  71458. u8 op;
  71459. if( aff==SQLITE_AFF_NONE ) return 1;
  71460. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  71461. op = p->op;
  71462. if( op==TK_REGISTER ) op = p->op2;
  71463. switch( op ){
  71464. case TK_INTEGER: {
  71465. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  71466. }
  71467. case TK_FLOAT: {
  71468. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  71469. }
  71470. case TK_STRING: {
  71471. return aff==SQLITE_AFF_TEXT;
  71472. }
  71473. case TK_BLOB: {
  71474. return 1;
  71475. }
  71476. case TK_COLUMN: {
  71477. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  71478. return p->iColumn<0
  71479. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  71480. }
  71481. default: {
  71482. return 0;
  71483. }
  71484. }
  71485. }
  71486. /*
  71487. ** Return TRUE if the given string is a row-id column name.
  71488. */
  71489. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  71490. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  71491. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  71492. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  71493. return 0;
  71494. }
  71495. /*
  71496. ** Return true if we are able to the IN operator optimization on a
  71497. ** query of the form
  71498. **
  71499. ** x IN (SELECT ...)
  71500. **
  71501. ** Where the SELECT... clause is as specified by the parameter to this
  71502. ** routine.
  71503. **
  71504. ** The Select object passed in has already been preprocessed and no
  71505. ** errors have been found.
  71506. */
  71507. #ifndef SQLITE_OMIT_SUBQUERY
  71508. static int isCandidateForInOpt(Select *p){
  71509. SrcList *pSrc;
  71510. ExprList *pEList;
  71511. Table *pTab;
  71512. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  71513. if( p->pPrior ) return 0; /* Not a compound SELECT */
  71514. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  71515. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  71516. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  71517. return 0; /* No DISTINCT keyword and no aggregate functions */
  71518. }
  71519. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  71520. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  71521. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  71522. if( p->pWhere ) return 0; /* Has no WHERE clause */
  71523. pSrc = p->pSrc;
  71524. assert( pSrc!=0 );
  71525. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  71526. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  71527. pTab = pSrc->a[0].pTab;
  71528. if( NEVER(pTab==0) ) return 0;
  71529. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  71530. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  71531. pEList = p->pEList;
  71532. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  71533. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  71534. return 1;
  71535. }
  71536. #endif /* SQLITE_OMIT_SUBQUERY */
  71537. /*
  71538. ** Code an OP_Once instruction and allocate space for its flag. Return the
  71539. ** address of the new instruction.
  71540. */
  71541. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  71542. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  71543. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  71544. }
  71545. /*
  71546. ** This function is used by the implementation of the IN (...) operator.
  71547. ** The pX parameter is the expression on the RHS of the IN operator, which
  71548. ** might be either a list of expressions or a subquery.
  71549. **
  71550. ** The job of this routine is to find or create a b-tree object that can
  71551. ** be used either to test for membership in the RHS set or to iterate through
  71552. ** all members of the RHS set, skipping duplicates.
  71553. **
  71554. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  71555. ** and pX->iTable is set to the index of that cursor.
  71556. **
  71557. ** The returned value of this function indicates the b-tree type, as follows:
  71558. **
  71559. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  71560. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  71561. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  71562. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  71563. ** populated epheremal table.
  71564. **
  71565. ** An existing b-tree might be used if the RHS expression pX is a simple
  71566. ** subquery such as:
  71567. **
  71568. ** SELECT <column> FROM <table>
  71569. **
  71570. ** If the RHS of the IN operator is a list or a more complex subquery, then
  71571. ** an ephemeral table might need to be generated from the RHS and then
  71572. ** pX->iTable made to point to the ephermeral table instead of an
  71573. ** existing table.
  71574. **
  71575. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  71576. ** through the set members, skipping any duplicates. In this case an
  71577. ** epheremal table must be used unless the selected <column> is guaranteed
  71578. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  71579. ** has a UNIQUE constraint or UNIQUE index.
  71580. **
  71581. ** If the prNotFound parameter is not 0, then the b-tree will be used
  71582. ** for fast set membership tests. In this case an epheremal table must
  71583. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  71584. ** be found with <column> as its left-most column.
  71585. **
  71586. ** When the b-tree is being used for membership tests, the calling function
  71587. ** needs to know whether or not the structure contains an SQL NULL
  71588. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  71589. ** If there is any chance that the (...) might contain a NULL value at
  71590. ** runtime, then a register is allocated and the register number written
  71591. ** to *prNotFound. If there is no chance that the (...) contains a
  71592. ** NULL value, then *prNotFound is left unchanged.
  71593. **
  71594. ** If a register is allocated and its location stored in *prNotFound, then
  71595. ** its initial value is NULL. If the (...) does not remain constant
  71596. ** for the duration of the query (i.e. the SELECT within the (...)
  71597. ** is a correlated subquery) then the value of the allocated register is
  71598. ** reset to NULL each time the subquery is rerun. This allows the
  71599. ** caller to use vdbe code equivalent to the following:
  71600. **
  71601. ** if( register==NULL ){
  71602. ** has_null = <test if data structure contains null>
  71603. ** register = 1
  71604. ** }
  71605. **
  71606. ** in order to avoid running the <test if data structure contains null>
  71607. ** test more often than is necessary.
  71608. */
  71609. #ifndef SQLITE_OMIT_SUBQUERY
  71610. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  71611. Select *p; /* SELECT to the right of IN operator */
  71612. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  71613. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  71614. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  71615. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  71616. assert( pX->op==TK_IN );
  71617. /* Check to see if an existing table or index can be used to
  71618. ** satisfy the query. This is preferable to generating a new
  71619. ** ephemeral table.
  71620. */
  71621. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  71622. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  71623. sqlite3 *db = pParse->db; /* Database connection */
  71624. Table *pTab; /* Table <table>. */
  71625. Expr *pExpr; /* Expression <column> */
  71626. int iCol; /* Index of column <column> */
  71627. int iDb; /* Database idx for pTab */
  71628. assert( p ); /* Because of isCandidateForInOpt(p) */
  71629. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  71630. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  71631. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  71632. pTab = p->pSrc->a[0].pTab;
  71633. pExpr = p->pEList->a[0].pExpr;
  71634. iCol = pExpr->iColumn;
  71635. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  71636. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  71637. sqlite3CodeVerifySchema(pParse, iDb);
  71638. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  71639. /* This function is only called from two places. In both cases the vdbe
  71640. ** has already been allocated. So assume sqlite3GetVdbe() is always
  71641. ** successful here.
  71642. */
  71643. assert(v);
  71644. if( iCol<0 ){
  71645. int iAddr;
  71646. iAddr = sqlite3CodeOnce(pParse);
  71647. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  71648. eType = IN_INDEX_ROWID;
  71649. sqlite3VdbeJumpHere(v, iAddr);
  71650. }else{
  71651. Index *pIdx; /* Iterator variable */
  71652. /* The collation sequence used by the comparison. If an index is to
  71653. ** be used in place of a temp-table, it must be ordered according
  71654. ** to this collation sequence. */
  71655. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  71656. /* Check that the affinity that will be used to perform the
  71657. ** comparison is the same as the affinity of the column. If
  71658. ** it is not, it is not possible to use any index.
  71659. */
  71660. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  71661. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  71662. if( (pIdx->aiColumn[0]==iCol)
  71663. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  71664. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  71665. ){
  71666. int iAddr;
  71667. char *pKey;
  71668. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  71669. iAddr = sqlite3CodeOnce(pParse);
  71670. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  71671. pKey,P4_KEYINFO_HANDOFF);
  71672. VdbeComment((v, "%s", pIdx->zName));
  71673. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  71674. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  71675. sqlite3VdbeJumpHere(v, iAddr);
  71676. if( prNotFound && !pTab->aCol[iCol].notNull ){
  71677. *prNotFound = ++pParse->nMem;
  71678. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  71679. }
  71680. }
  71681. }
  71682. }
  71683. }
  71684. if( eType==0 ){
  71685. /* Could not found an existing table or index to use as the RHS b-tree.
  71686. ** We will have to generate an ephemeral table to do the job.
  71687. */
  71688. double savedNQueryLoop = pParse->nQueryLoop;
  71689. int rMayHaveNull = 0;
  71690. eType = IN_INDEX_EPH;
  71691. if( prNotFound ){
  71692. *prNotFound = rMayHaveNull = ++pParse->nMem;
  71693. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  71694. }else{
  71695. testcase( pParse->nQueryLoop>(double)1 );
  71696. pParse->nQueryLoop = (double)1;
  71697. if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
  71698. eType = IN_INDEX_ROWID;
  71699. }
  71700. }
  71701. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  71702. pParse->nQueryLoop = savedNQueryLoop;
  71703. }else{
  71704. pX->iTable = iTab;
  71705. }
  71706. return eType;
  71707. }
  71708. #endif
  71709. /*
  71710. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  71711. ** or IN operators. Examples:
  71712. **
  71713. ** (SELECT a FROM b) -- subquery
  71714. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  71715. ** x IN (4,5,11) -- IN operator with list on right-hand side
  71716. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  71717. **
  71718. ** The pExpr parameter describes the expression that contains the IN
  71719. ** operator or subquery.
  71720. **
  71721. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  71722. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  71723. ** to some integer key column of a table B-Tree. In this case, use an
  71724. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  71725. ** (slower) variable length keys B-Tree.
  71726. **
  71727. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  71728. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  71729. ** Furthermore, the IN is in a WHERE clause and that we really want
  71730. ** to iterate over the RHS of the IN operator in order to quickly locate
  71731. ** all corresponding LHS elements. All this routine does is initialize
  71732. ** the register given by rMayHaveNull to NULL. Calling routines will take
  71733. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  71734. **
  71735. ** If rMayHaveNull is zero, that means that the subquery is being used
  71736. ** for membership testing only. There is no need to initialize any
  71737. ** registers to indicate the presense or absence of NULLs on the RHS.
  71738. **
  71739. ** For a SELECT or EXISTS operator, return the register that holds the
  71740. ** result. For IN operators or if an error occurs, the return value is 0.
  71741. */
  71742. #ifndef SQLITE_OMIT_SUBQUERY
  71743. SQLITE_PRIVATE int sqlite3CodeSubselect(
  71744. Parse *pParse, /* Parsing context */
  71745. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  71746. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  71747. int isRowid /* If true, LHS of IN operator is a rowid */
  71748. ){
  71749. int testAddr = -1; /* One-time test address */
  71750. int rReg = 0; /* Register storing resulting */
  71751. Vdbe *v = sqlite3GetVdbe(pParse);
  71752. if( NEVER(v==0) ) return 0;
  71753. sqlite3ExprCachePush(pParse);
  71754. /* This code must be run in its entirety every time it is encountered
  71755. ** if any of the following is true:
  71756. **
  71757. ** * The right-hand side is a correlated subquery
  71758. ** * The right-hand side is an expression list containing variables
  71759. ** * We are inside a trigger
  71760. **
  71761. ** If all of the above are false, then we can run this code just once
  71762. ** save the results, and reuse the same result on subsequent invocations.
  71763. */
  71764. if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
  71765. testAddr = sqlite3CodeOnce(pParse);
  71766. }
  71767. #ifndef SQLITE_OMIT_EXPLAIN
  71768. if( pParse->explain==2 ){
  71769. char *zMsg = sqlite3MPrintf(
  71770. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  71771. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  71772. );
  71773. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  71774. }
  71775. #endif
  71776. switch( pExpr->op ){
  71777. case TK_IN: {
  71778. char affinity; /* Affinity of the LHS of the IN */
  71779. KeyInfo keyInfo; /* Keyinfo for the generated table */
  71780. static u8 sortOrder = 0; /* Fake aSortOrder for keyInfo */
  71781. int addr; /* Address of OP_OpenEphemeral instruction */
  71782. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  71783. if( rMayHaveNull ){
  71784. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  71785. }
  71786. affinity = sqlite3ExprAffinity(pLeft);
  71787. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  71788. ** expression it is handled the same way. An ephemeral table is
  71789. ** filled with single-field index keys representing the results
  71790. ** from the SELECT or the <exprlist>.
  71791. **
  71792. ** If the 'x' expression is a column value, or the SELECT...
  71793. ** statement returns a column value, then the affinity of that
  71794. ** column is used to build the index keys. If both 'x' and the
  71795. ** SELECT... statement are columns, then numeric affinity is used
  71796. ** if either column has NUMERIC or INTEGER affinity. If neither
  71797. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  71798. ** is used.
  71799. */
  71800. pExpr->iTable = pParse->nTab++;
  71801. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  71802. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  71803. memset(&keyInfo, 0, sizeof(keyInfo));
  71804. keyInfo.nField = 1;
  71805. keyInfo.aSortOrder = &sortOrder;
  71806. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  71807. /* Case 1: expr IN (SELECT ...)
  71808. **
  71809. ** Generate code to write the results of the select into the temporary
  71810. ** table allocated and opened above.
  71811. */
  71812. SelectDest dest;
  71813. ExprList *pEList;
  71814. assert( !isRowid );
  71815. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  71816. dest.affSdst = (u8)affinity;
  71817. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  71818. pExpr->x.pSelect->iLimit = 0;
  71819. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  71820. return 0;
  71821. }
  71822. pEList = pExpr->x.pSelect->pEList;
  71823. if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
  71824. keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  71825. pEList->a[0].pExpr);
  71826. }
  71827. }else if( ALWAYS(pExpr->x.pList!=0) ){
  71828. /* Case 2: expr IN (exprlist)
  71829. **
  71830. ** For each expression, build an index key from the evaluation and
  71831. ** store it in the temporary table. If <expr> is a column, then use
  71832. ** that columns affinity when building index keys. If <expr> is not
  71833. ** a column, use numeric affinity.
  71834. */
  71835. int i;
  71836. ExprList *pList = pExpr->x.pList;
  71837. struct ExprList_item *pItem;
  71838. int r1, r2, r3;
  71839. if( !affinity ){
  71840. affinity = SQLITE_AFF_NONE;
  71841. }
  71842. keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  71843. keyInfo.aSortOrder = &sortOrder;
  71844. /* Loop through each expression in <exprlist>. */
  71845. r1 = sqlite3GetTempReg(pParse);
  71846. r2 = sqlite3GetTempReg(pParse);
  71847. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  71848. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  71849. Expr *pE2 = pItem->pExpr;
  71850. int iValToIns;
  71851. /* If the expression is not constant then we will need to
  71852. ** disable the test that was generated above that makes sure
  71853. ** this code only executes once. Because for a non-constant
  71854. ** expression we need to rerun this code each time.
  71855. */
  71856. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  71857. sqlite3VdbeChangeToNoop(v, testAddr);
  71858. testAddr = -1;
  71859. }
  71860. /* Evaluate the expression and insert it into the temp table */
  71861. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  71862. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  71863. }else{
  71864. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  71865. if( isRowid ){
  71866. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  71867. sqlite3VdbeCurrentAddr(v)+2);
  71868. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  71869. }else{
  71870. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  71871. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  71872. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  71873. }
  71874. }
  71875. }
  71876. sqlite3ReleaseTempReg(pParse, r1);
  71877. sqlite3ReleaseTempReg(pParse, r2);
  71878. }
  71879. if( !isRowid ){
  71880. sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
  71881. }
  71882. break;
  71883. }
  71884. case TK_EXISTS:
  71885. case TK_SELECT:
  71886. default: {
  71887. /* If this has to be a scalar SELECT. Generate code to put the
  71888. ** value of this select in a memory cell and record the number
  71889. ** of the memory cell in iColumn. If this is an EXISTS, write
  71890. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  71891. ** and record that memory cell in iColumn.
  71892. */
  71893. Select *pSel; /* SELECT statement to encode */
  71894. SelectDest dest; /* How to deal with SELECt result */
  71895. testcase( pExpr->op==TK_EXISTS );
  71896. testcase( pExpr->op==TK_SELECT );
  71897. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  71898. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  71899. pSel = pExpr->x.pSelect;
  71900. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  71901. if( pExpr->op==TK_SELECT ){
  71902. dest.eDest = SRT_Mem;
  71903. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  71904. VdbeComment((v, "Init subquery result"));
  71905. }else{
  71906. dest.eDest = SRT_Exists;
  71907. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  71908. VdbeComment((v, "Init EXISTS result"));
  71909. }
  71910. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  71911. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  71912. &sqlite3IntTokens[1]);
  71913. pSel->iLimit = 0;
  71914. if( sqlite3Select(pParse, pSel, &dest) ){
  71915. return 0;
  71916. }
  71917. rReg = dest.iSDParm;
  71918. ExprSetIrreducible(pExpr);
  71919. break;
  71920. }
  71921. }
  71922. if( testAddr>=0 ){
  71923. sqlite3VdbeJumpHere(v, testAddr);
  71924. }
  71925. sqlite3ExprCachePop(pParse, 1);
  71926. return rReg;
  71927. }
  71928. #endif /* SQLITE_OMIT_SUBQUERY */
  71929. #ifndef SQLITE_OMIT_SUBQUERY
  71930. /*
  71931. ** Generate code for an IN expression.
  71932. **
  71933. ** x IN (SELECT ...)
  71934. ** x IN (value, value, ...)
  71935. **
  71936. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  71937. ** is an array of zero or more values. The expression is true if the LHS is
  71938. ** contained within the RHS. The value of the expression is unknown (NULL)
  71939. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  71940. ** RHS contains one or more NULL values.
  71941. **
  71942. ** This routine generates code will jump to destIfFalse if the LHS is not
  71943. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  71944. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  71945. ** within the RHS then fall through.
  71946. */
  71947. static void sqlite3ExprCodeIN(
  71948. Parse *pParse, /* Parsing and code generating context */
  71949. Expr *pExpr, /* The IN expression */
  71950. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  71951. int destIfNull /* Jump here if the results are unknown due to NULLs */
  71952. ){
  71953. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  71954. char affinity; /* Comparison affinity to use */
  71955. int eType; /* Type of the RHS */
  71956. int r1; /* Temporary use register */
  71957. Vdbe *v; /* Statement under construction */
  71958. /* Compute the RHS. After this step, the table with cursor
  71959. ** pExpr->iTable will contains the values that make up the RHS.
  71960. */
  71961. v = pParse->pVdbe;
  71962. assert( v!=0 ); /* OOM detected prior to this routine */
  71963. VdbeNoopComment((v, "begin IN expr"));
  71964. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  71965. /* Figure out the affinity to use to create a key from the results
  71966. ** of the expression. affinityStr stores a static string suitable for
  71967. ** P4 of OP_MakeRecord.
  71968. */
  71969. affinity = comparisonAffinity(pExpr);
  71970. /* Code the LHS, the <expr> from "<expr> IN (...)".
  71971. */
  71972. sqlite3ExprCachePush(pParse);
  71973. r1 = sqlite3GetTempReg(pParse);
  71974. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  71975. /* If the LHS is NULL, then the result is either false or NULL depending
  71976. ** on whether the RHS is empty or not, respectively.
  71977. */
  71978. if( destIfNull==destIfFalse ){
  71979. /* Shortcut for the common case where the false and NULL outcomes are
  71980. ** the same. */
  71981. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  71982. }else{
  71983. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  71984. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  71985. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  71986. sqlite3VdbeJumpHere(v, addr1);
  71987. }
  71988. if( eType==IN_INDEX_ROWID ){
  71989. /* In this case, the RHS is the ROWID of table b-tree
  71990. */
  71991. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  71992. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  71993. }else{
  71994. /* In this case, the RHS is an index b-tree.
  71995. */
  71996. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  71997. /* If the set membership test fails, then the result of the
  71998. ** "x IN (...)" expression must be either 0 or NULL. If the set
  71999. ** contains no NULL values, then the result is 0. If the set
  72000. ** contains one or more NULL values, then the result of the
  72001. ** expression is also NULL.
  72002. */
  72003. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  72004. /* This branch runs if it is known at compile time that the RHS
  72005. ** cannot contain NULL values. This happens as the result
  72006. ** of a "NOT NULL" constraint in the database schema.
  72007. **
  72008. ** Also run this branch if NULL is equivalent to FALSE
  72009. ** for this particular IN operator.
  72010. */
  72011. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  72012. }else{
  72013. /* In this branch, the RHS of the IN might contain a NULL and
  72014. ** the presence of a NULL on the RHS makes a difference in the
  72015. ** outcome.
  72016. */
  72017. int j1, j2, j3;
  72018. /* First check to see if the LHS is contained in the RHS. If so,
  72019. ** then the presence of NULLs in the RHS does not matter, so jump
  72020. ** over all of the code that follows.
  72021. */
  72022. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  72023. /* Here we begin generating code that runs if the LHS is not
  72024. ** contained within the RHS. Generate additional code that
  72025. ** tests the RHS for NULLs. If the RHS contains a NULL then
  72026. ** jump to destIfNull. If there are no NULLs in the RHS then
  72027. ** jump to destIfFalse.
  72028. */
  72029. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  72030. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  72031. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  72032. sqlite3VdbeJumpHere(v, j3);
  72033. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  72034. sqlite3VdbeJumpHere(v, j2);
  72035. /* Jump to the appropriate target depending on whether or not
  72036. ** the RHS contains a NULL
  72037. */
  72038. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  72039. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  72040. /* The OP_Found at the top of this branch jumps here when true,
  72041. ** causing the overall IN expression evaluation to fall through.
  72042. */
  72043. sqlite3VdbeJumpHere(v, j1);
  72044. }
  72045. }
  72046. sqlite3ReleaseTempReg(pParse, r1);
  72047. sqlite3ExprCachePop(pParse, 1);
  72048. VdbeComment((v, "end IN expr"));
  72049. }
  72050. #endif /* SQLITE_OMIT_SUBQUERY */
  72051. /*
  72052. ** Duplicate an 8-byte value
  72053. */
  72054. static char *dup8bytes(Vdbe *v, const char *in){
  72055. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  72056. if( out ){
  72057. memcpy(out, in, 8);
  72058. }
  72059. return out;
  72060. }
  72061. #ifndef SQLITE_OMIT_FLOATING_POINT
  72062. /*
  72063. ** Generate an instruction that will put the floating point
  72064. ** value described by z[0..n-1] into register iMem.
  72065. **
  72066. ** The z[] string will probably not be zero-terminated. But the
  72067. ** z[n] character is guaranteed to be something that does not look
  72068. ** like the continuation of the number.
  72069. */
  72070. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  72071. if( ALWAYS(z!=0) ){
  72072. double value;
  72073. char *zV;
  72074. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  72075. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  72076. if( negateFlag ) value = -value;
  72077. zV = dup8bytes(v, (char*)&value);
  72078. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  72079. }
  72080. }
  72081. #endif
  72082. /*
  72083. ** Generate an instruction that will put the integer describe by
  72084. ** text z[0..n-1] into register iMem.
  72085. **
  72086. ** Expr.u.zToken is always UTF8 and zero-terminated.
  72087. */
  72088. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  72089. Vdbe *v = pParse->pVdbe;
  72090. if( pExpr->flags & EP_IntValue ){
  72091. int i = pExpr->u.iValue;
  72092. assert( i>=0 );
  72093. if( negFlag ) i = -i;
  72094. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  72095. }else{
  72096. int c;
  72097. i64 value;
  72098. const char *z = pExpr->u.zToken;
  72099. assert( z!=0 );
  72100. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  72101. if( c==0 || (c==2 && negFlag) ){
  72102. char *zV;
  72103. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  72104. zV = dup8bytes(v, (char*)&value);
  72105. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  72106. }else{
  72107. #ifdef SQLITE_OMIT_FLOATING_POINT
  72108. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  72109. #else
  72110. codeReal(v, z, negFlag, iMem);
  72111. #endif
  72112. }
  72113. }
  72114. }
  72115. /*
  72116. ** Clear a cache entry.
  72117. */
  72118. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  72119. if( p->tempReg ){
  72120. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  72121. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  72122. }
  72123. p->tempReg = 0;
  72124. }
  72125. }
  72126. /*
  72127. ** Record in the column cache that a particular column from a
  72128. ** particular table is stored in a particular register.
  72129. */
  72130. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  72131. int i;
  72132. int minLru;
  72133. int idxLru;
  72134. struct yColCache *p;
  72135. assert( iReg>0 ); /* Register numbers are always positive */
  72136. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  72137. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  72138. ** for testing only - to verify that SQLite always gets the same answer
  72139. ** with and without the column cache.
  72140. */
  72141. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  72142. /* First replace any existing entry.
  72143. **
  72144. ** Actually, the way the column cache is currently used, we are guaranteed
  72145. ** that the object will never already be in cache. Verify this guarantee.
  72146. */
  72147. #ifndef NDEBUG
  72148. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72149. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  72150. }
  72151. #endif
  72152. /* Find an empty slot and replace it */
  72153. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72154. if( p->iReg==0 ){
  72155. p->iLevel = pParse->iCacheLevel;
  72156. p->iTable = iTab;
  72157. p->iColumn = iCol;
  72158. p->iReg = iReg;
  72159. p->tempReg = 0;
  72160. p->lru = pParse->iCacheCnt++;
  72161. return;
  72162. }
  72163. }
  72164. /* Replace the last recently used */
  72165. minLru = 0x7fffffff;
  72166. idxLru = -1;
  72167. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72168. if( p->lru<minLru ){
  72169. idxLru = i;
  72170. minLru = p->lru;
  72171. }
  72172. }
  72173. if( ALWAYS(idxLru>=0) ){
  72174. p = &pParse->aColCache[idxLru];
  72175. p->iLevel = pParse->iCacheLevel;
  72176. p->iTable = iTab;
  72177. p->iColumn = iCol;
  72178. p->iReg = iReg;
  72179. p->tempReg = 0;
  72180. p->lru = pParse->iCacheCnt++;
  72181. return;
  72182. }
  72183. }
  72184. /*
  72185. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  72186. ** Purge the range of registers from the column cache.
  72187. */
  72188. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  72189. int i;
  72190. int iLast = iReg + nReg - 1;
  72191. struct yColCache *p;
  72192. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72193. int r = p->iReg;
  72194. if( r>=iReg && r<=iLast ){
  72195. cacheEntryClear(pParse, p);
  72196. p->iReg = 0;
  72197. }
  72198. }
  72199. }
  72200. /*
  72201. ** Remember the current column cache context. Any new entries added
  72202. ** added to the column cache after this call are removed when the
  72203. ** corresponding pop occurs.
  72204. */
  72205. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  72206. pParse->iCacheLevel++;
  72207. }
  72208. /*
  72209. ** Remove from the column cache any entries that were added since the
  72210. ** the previous N Push operations. In other words, restore the cache
  72211. ** to the state it was in N Pushes ago.
  72212. */
  72213. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  72214. int i;
  72215. struct yColCache *p;
  72216. assert( N>0 );
  72217. assert( pParse->iCacheLevel>=N );
  72218. pParse->iCacheLevel -= N;
  72219. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72220. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  72221. cacheEntryClear(pParse, p);
  72222. p->iReg = 0;
  72223. }
  72224. }
  72225. }
  72226. /*
  72227. ** When a cached column is reused, make sure that its register is
  72228. ** no longer available as a temp register. ticket #3879: that same
  72229. ** register might be in the cache in multiple places, so be sure to
  72230. ** get them all.
  72231. */
  72232. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  72233. int i;
  72234. struct yColCache *p;
  72235. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72236. if( p->iReg==iReg ){
  72237. p->tempReg = 0;
  72238. }
  72239. }
  72240. }
  72241. /*
  72242. ** Generate code to extract the value of the iCol-th column of a table.
  72243. */
  72244. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  72245. Vdbe *v, /* The VDBE under construction */
  72246. Table *pTab, /* The table containing the value */
  72247. int iTabCur, /* The cursor for this table */
  72248. int iCol, /* Index of the column to extract */
  72249. int regOut /* Extract the valud into this register */
  72250. ){
  72251. if( iCol<0 || iCol==pTab->iPKey ){
  72252. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  72253. }else{
  72254. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  72255. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  72256. }
  72257. if( iCol>=0 ){
  72258. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  72259. }
  72260. }
  72261. /*
  72262. ** Generate code that will extract the iColumn-th column from
  72263. ** table pTab and store the column value in a register. An effort
  72264. ** is made to store the column value in register iReg, but this is
  72265. ** not guaranteed. The location of the column value is returned.
  72266. **
  72267. ** There must be an open cursor to pTab in iTable when this routine
  72268. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  72269. */
  72270. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  72271. Parse *pParse, /* Parsing and code generating context */
  72272. Table *pTab, /* Description of the table we are reading from */
  72273. int iColumn, /* Index of the table column */
  72274. int iTable, /* The cursor pointing to the table */
  72275. int iReg, /* Store results here */
  72276. u8 p5 /* P5 value for OP_Column */
  72277. ){
  72278. Vdbe *v = pParse->pVdbe;
  72279. int i;
  72280. struct yColCache *p;
  72281. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72282. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  72283. p->lru = pParse->iCacheCnt++;
  72284. sqlite3ExprCachePinRegister(pParse, p->iReg);
  72285. return p->iReg;
  72286. }
  72287. }
  72288. assert( v!=0 );
  72289. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  72290. if( p5 ){
  72291. sqlite3VdbeChangeP5(v, p5);
  72292. }else{
  72293. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  72294. }
  72295. return iReg;
  72296. }
  72297. /*
  72298. ** Clear all column cache entries.
  72299. */
  72300. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  72301. int i;
  72302. struct yColCache *p;
  72303. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72304. if( p->iReg ){
  72305. cacheEntryClear(pParse, p);
  72306. p->iReg = 0;
  72307. }
  72308. }
  72309. }
  72310. /*
  72311. ** Record the fact that an affinity change has occurred on iCount
  72312. ** registers starting with iStart.
  72313. */
  72314. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  72315. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  72316. }
  72317. /*
  72318. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  72319. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  72320. */
  72321. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  72322. int i;
  72323. struct yColCache *p;
  72324. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  72325. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  72326. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72327. int x = p->iReg;
  72328. if( x>=iFrom && x<iFrom+nReg ){
  72329. p->iReg += iTo-iFrom;
  72330. }
  72331. }
  72332. }
  72333. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  72334. /*
  72335. ** Return true if any register in the range iFrom..iTo (inclusive)
  72336. ** is used as part of the column cache.
  72337. **
  72338. ** This routine is used within assert() and testcase() macros only
  72339. ** and does not appear in a normal build.
  72340. */
  72341. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  72342. int i;
  72343. struct yColCache *p;
  72344. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72345. int r = p->iReg;
  72346. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  72347. }
  72348. return 0;
  72349. }
  72350. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  72351. /*
  72352. ** Generate code into the current Vdbe to evaluate the given
  72353. ** expression. Attempt to store the results in register "target".
  72354. ** Return the register where results are stored.
  72355. **
  72356. ** With this routine, there is no guarantee that results will
  72357. ** be stored in target. The result might be stored in some other
  72358. ** register if it is convenient to do so. The calling function
  72359. ** must check the return code and move the results to the desired
  72360. ** register.
  72361. */
  72362. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  72363. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  72364. int op; /* The opcode being coded */
  72365. int inReg = target; /* Results stored in register inReg */
  72366. int regFree1 = 0; /* If non-zero free this temporary register */
  72367. int regFree2 = 0; /* If non-zero free this temporary register */
  72368. int r1, r2, r3, r4; /* Various register numbers */
  72369. sqlite3 *db = pParse->db; /* The database connection */
  72370. assert( target>0 && target<=pParse->nMem );
  72371. if( v==0 ){
  72372. assert( pParse->db->mallocFailed );
  72373. return 0;
  72374. }
  72375. if( pExpr==0 ){
  72376. op = TK_NULL;
  72377. }else{
  72378. op = pExpr->op;
  72379. }
  72380. switch( op ){
  72381. case TK_AGG_COLUMN: {
  72382. AggInfo *pAggInfo = pExpr->pAggInfo;
  72383. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  72384. if( !pAggInfo->directMode ){
  72385. assert( pCol->iMem>0 );
  72386. inReg = pCol->iMem;
  72387. break;
  72388. }else if( pAggInfo->useSortingIdx ){
  72389. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  72390. pCol->iSorterColumn, target);
  72391. break;
  72392. }
  72393. /* Otherwise, fall thru into the TK_COLUMN case */
  72394. }
  72395. case TK_COLUMN: {
  72396. if( pExpr->iTable<0 ){
  72397. /* This only happens when coding check constraints */
  72398. assert( pParse->ckBase>0 );
  72399. inReg = pExpr->iColumn + pParse->ckBase;
  72400. }else{
  72401. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  72402. pExpr->iColumn, pExpr->iTable, target,
  72403. pExpr->op2);
  72404. }
  72405. break;
  72406. }
  72407. case TK_INTEGER: {
  72408. codeInteger(pParse, pExpr, 0, target);
  72409. break;
  72410. }
  72411. #ifndef SQLITE_OMIT_FLOATING_POINT
  72412. case TK_FLOAT: {
  72413. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72414. codeReal(v, pExpr->u.zToken, 0, target);
  72415. break;
  72416. }
  72417. #endif
  72418. case TK_STRING: {
  72419. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72420. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  72421. break;
  72422. }
  72423. case TK_NULL: {
  72424. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  72425. break;
  72426. }
  72427. #ifndef SQLITE_OMIT_BLOB_LITERAL
  72428. case TK_BLOB: {
  72429. int n;
  72430. const char *z;
  72431. char *zBlob;
  72432. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72433. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  72434. assert( pExpr->u.zToken[1]=='\'' );
  72435. z = &pExpr->u.zToken[2];
  72436. n = sqlite3Strlen30(z) - 1;
  72437. assert( z[n]=='\'' );
  72438. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  72439. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  72440. break;
  72441. }
  72442. #endif
  72443. case TK_VARIABLE: {
  72444. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72445. assert( pExpr->u.zToken!=0 );
  72446. assert( pExpr->u.zToken[0]!=0 );
  72447. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  72448. if( pExpr->u.zToken[1]!=0 ){
  72449. assert( pExpr->u.zToken[0]=='?'
  72450. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  72451. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  72452. }
  72453. break;
  72454. }
  72455. case TK_REGISTER: {
  72456. inReg = pExpr->iTable;
  72457. break;
  72458. }
  72459. case TK_AS: {
  72460. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  72461. break;
  72462. }
  72463. #ifndef SQLITE_OMIT_CAST
  72464. case TK_CAST: {
  72465. /* Expressions of the form: CAST(pLeft AS token) */
  72466. int aff, to_op;
  72467. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  72468. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72469. aff = sqlite3AffinityType(pExpr->u.zToken);
  72470. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  72471. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  72472. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  72473. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  72474. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  72475. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  72476. testcase( to_op==OP_ToText );
  72477. testcase( to_op==OP_ToBlob );
  72478. testcase( to_op==OP_ToNumeric );
  72479. testcase( to_op==OP_ToInt );
  72480. testcase( to_op==OP_ToReal );
  72481. if( inReg!=target ){
  72482. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  72483. inReg = target;
  72484. }
  72485. sqlite3VdbeAddOp1(v, to_op, inReg);
  72486. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  72487. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  72488. break;
  72489. }
  72490. #endif /* SQLITE_OMIT_CAST */
  72491. case TK_LT:
  72492. case TK_LE:
  72493. case TK_GT:
  72494. case TK_GE:
  72495. case TK_NE:
  72496. case TK_EQ: {
  72497. assert( TK_LT==OP_Lt );
  72498. assert( TK_LE==OP_Le );
  72499. assert( TK_GT==OP_Gt );
  72500. assert( TK_GE==OP_Ge );
  72501. assert( TK_EQ==OP_Eq );
  72502. assert( TK_NE==OP_Ne );
  72503. testcase( op==TK_LT );
  72504. testcase( op==TK_LE );
  72505. testcase( op==TK_GT );
  72506. testcase( op==TK_GE );
  72507. testcase( op==TK_EQ );
  72508. testcase( op==TK_NE );
  72509. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72510. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72511. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72512. r1, r2, inReg, SQLITE_STOREP2);
  72513. testcase( regFree1==0 );
  72514. testcase( regFree2==0 );
  72515. break;
  72516. }
  72517. case TK_IS:
  72518. case TK_ISNOT: {
  72519. testcase( op==TK_IS );
  72520. testcase( op==TK_ISNOT );
  72521. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72522. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72523. op = (op==TK_IS) ? TK_EQ : TK_NE;
  72524. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72525. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  72526. testcase( regFree1==0 );
  72527. testcase( regFree2==0 );
  72528. break;
  72529. }
  72530. case TK_AND:
  72531. case TK_OR:
  72532. case TK_PLUS:
  72533. case TK_STAR:
  72534. case TK_MINUS:
  72535. case TK_REM:
  72536. case TK_BITAND:
  72537. case TK_BITOR:
  72538. case TK_SLASH:
  72539. case TK_LSHIFT:
  72540. case TK_RSHIFT:
  72541. case TK_CONCAT: {
  72542. assert( TK_AND==OP_And );
  72543. assert( TK_OR==OP_Or );
  72544. assert( TK_PLUS==OP_Add );
  72545. assert( TK_MINUS==OP_Subtract );
  72546. assert( TK_REM==OP_Remainder );
  72547. assert( TK_BITAND==OP_BitAnd );
  72548. assert( TK_BITOR==OP_BitOr );
  72549. assert( TK_SLASH==OP_Divide );
  72550. assert( TK_LSHIFT==OP_ShiftLeft );
  72551. assert( TK_RSHIFT==OP_ShiftRight );
  72552. assert( TK_CONCAT==OP_Concat );
  72553. testcase( op==TK_AND );
  72554. testcase( op==TK_OR );
  72555. testcase( op==TK_PLUS );
  72556. testcase( op==TK_MINUS );
  72557. testcase( op==TK_REM );
  72558. testcase( op==TK_BITAND );
  72559. testcase( op==TK_BITOR );
  72560. testcase( op==TK_SLASH );
  72561. testcase( op==TK_LSHIFT );
  72562. testcase( op==TK_RSHIFT );
  72563. testcase( op==TK_CONCAT );
  72564. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72565. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72566. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  72567. testcase( regFree1==0 );
  72568. testcase( regFree2==0 );
  72569. break;
  72570. }
  72571. case TK_UMINUS: {
  72572. Expr *pLeft = pExpr->pLeft;
  72573. assert( pLeft );
  72574. if( pLeft->op==TK_INTEGER ){
  72575. codeInteger(pParse, pLeft, 1, target);
  72576. #ifndef SQLITE_OMIT_FLOATING_POINT
  72577. }else if( pLeft->op==TK_FLOAT ){
  72578. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72579. codeReal(v, pLeft->u.zToken, 1, target);
  72580. #endif
  72581. }else{
  72582. regFree1 = r1 = sqlite3GetTempReg(pParse);
  72583. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  72584. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  72585. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  72586. testcase( regFree2==0 );
  72587. }
  72588. inReg = target;
  72589. break;
  72590. }
  72591. case TK_BITNOT:
  72592. case TK_NOT: {
  72593. assert( TK_BITNOT==OP_BitNot );
  72594. assert( TK_NOT==OP_Not );
  72595. testcase( op==TK_BITNOT );
  72596. testcase( op==TK_NOT );
  72597. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72598. testcase( regFree1==0 );
  72599. inReg = target;
  72600. sqlite3VdbeAddOp2(v, op, r1, inReg);
  72601. break;
  72602. }
  72603. case TK_ISNULL:
  72604. case TK_NOTNULL: {
  72605. int addr;
  72606. assert( TK_ISNULL==OP_IsNull );
  72607. assert( TK_NOTNULL==OP_NotNull );
  72608. testcase( op==TK_ISNULL );
  72609. testcase( op==TK_NOTNULL );
  72610. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  72611. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72612. testcase( regFree1==0 );
  72613. addr = sqlite3VdbeAddOp1(v, op, r1);
  72614. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  72615. sqlite3VdbeJumpHere(v, addr);
  72616. break;
  72617. }
  72618. case TK_AGG_FUNCTION: {
  72619. AggInfo *pInfo = pExpr->pAggInfo;
  72620. if( pInfo==0 ){
  72621. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72622. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  72623. }else{
  72624. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  72625. }
  72626. break;
  72627. }
  72628. case TK_CONST_FUNC:
  72629. case TK_FUNCTION: {
  72630. ExprList *pFarg; /* List of function arguments */
  72631. int nFarg; /* Number of function arguments */
  72632. FuncDef *pDef; /* The function definition object */
  72633. int nId; /* Length of the function name in bytes */
  72634. const char *zId; /* The function name */
  72635. int constMask = 0; /* Mask of function arguments that are constant */
  72636. int i; /* Loop counter */
  72637. u8 enc = ENC(db); /* The text encoding used by this database */
  72638. CollSeq *pColl = 0; /* A collating sequence */
  72639. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  72640. testcase( op==TK_CONST_FUNC );
  72641. testcase( op==TK_FUNCTION );
  72642. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
  72643. pFarg = 0;
  72644. }else{
  72645. pFarg = pExpr->x.pList;
  72646. }
  72647. nFarg = pFarg ? pFarg->nExpr : 0;
  72648. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72649. zId = pExpr->u.zToken;
  72650. nId = sqlite3Strlen30(zId);
  72651. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  72652. if( pDef==0 ){
  72653. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  72654. break;
  72655. }
  72656. /* Attempt a direct implementation of the built-in COALESCE() and
  72657. ** IFNULL() functions. This avoids unnecessary evalation of
  72658. ** arguments past the first non-NULL argument.
  72659. */
  72660. if( pDef->flags & SQLITE_FUNC_COALESCE ){
  72661. int endCoalesce = sqlite3VdbeMakeLabel(v);
  72662. assert( nFarg>=2 );
  72663. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  72664. for(i=1; i<nFarg; i++){
  72665. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  72666. sqlite3ExprCacheRemove(pParse, target, 1);
  72667. sqlite3ExprCachePush(pParse);
  72668. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  72669. sqlite3ExprCachePop(pParse, 1);
  72670. }
  72671. sqlite3VdbeResolveLabel(v, endCoalesce);
  72672. break;
  72673. }
  72674. if( pFarg ){
  72675. r1 = sqlite3GetTempRange(pParse, nFarg);
  72676. /* For length() and typeof() functions with a column argument,
  72677. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  72678. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  72679. ** loading.
  72680. */
  72681. if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  72682. u8 exprOp;
  72683. assert( nFarg==1 );
  72684. assert( pFarg->a[0].pExpr!=0 );
  72685. exprOp = pFarg->a[0].pExpr->op;
  72686. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  72687. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  72688. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  72689. testcase( pDef->flags==SQLITE_FUNC_LENGTH );
  72690. pFarg->a[0].pExpr->op2 = pDef->flags;
  72691. }
  72692. }
  72693. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  72694. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  72695. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  72696. }else{
  72697. r1 = 0;
  72698. }
  72699. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72700. /* Possibly overload the function if the first argument is
  72701. ** a virtual table column.
  72702. **
  72703. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  72704. ** second argument, not the first, as the argument to test to
  72705. ** see if it is a column in a virtual table. This is done because
  72706. ** the left operand of infix functions (the operand we want to
  72707. ** control overloading) ends up as the second argument to the
  72708. ** function. The expression "A glob B" is equivalent to
  72709. ** "glob(B,A). We want to use the A in "A glob B" to test
  72710. ** for function overloading. But we use the B term in "glob(B,A)".
  72711. */
  72712. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  72713. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  72714. }else if( nFarg>0 ){
  72715. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  72716. }
  72717. #endif
  72718. for(i=0; i<nFarg; i++){
  72719. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  72720. constMask |= (1<<i);
  72721. }
  72722. if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  72723. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  72724. }
  72725. }
  72726. if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
  72727. if( !pColl ) pColl = db->pDfltColl;
  72728. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  72729. }
  72730. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  72731. (char*)pDef, P4_FUNCDEF);
  72732. sqlite3VdbeChangeP5(v, (u8)nFarg);
  72733. if( nFarg ){
  72734. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  72735. }
  72736. break;
  72737. }
  72738. #ifndef SQLITE_OMIT_SUBQUERY
  72739. case TK_EXISTS:
  72740. case TK_SELECT: {
  72741. testcase( op==TK_EXISTS );
  72742. testcase( op==TK_SELECT );
  72743. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  72744. break;
  72745. }
  72746. case TK_IN: {
  72747. int destIfFalse = sqlite3VdbeMakeLabel(v);
  72748. int destIfNull = sqlite3VdbeMakeLabel(v);
  72749. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  72750. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  72751. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  72752. sqlite3VdbeResolveLabel(v, destIfFalse);
  72753. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  72754. sqlite3VdbeResolveLabel(v, destIfNull);
  72755. break;
  72756. }
  72757. #endif /* SQLITE_OMIT_SUBQUERY */
  72758. /*
  72759. ** x BETWEEN y AND z
  72760. **
  72761. ** This is equivalent to
  72762. **
  72763. ** x>=y AND x<=z
  72764. **
  72765. ** X is stored in pExpr->pLeft.
  72766. ** Y is stored in pExpr->pList->a[0].pExpr.
  72767. ** Z is stored in pExpr->pList->a[1].pExpr.
  72768. */
  72769. case TK_BETWEEN: {
  72770. Expr *pLeft = pExpr->pLeft;
  72771. struct ExprList_item *pLItem = pExpr->x.pList->a;
  72772. Expr *pRight = pLItem->pExpr;
  72773. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  72774. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  72775. testcase( regFree1==0 );
  72776. testcase( regFree2==0 );
  72777. r3 = sqlite3GetTempReg(pParse);
  72778. r4 = sqlite3GetTempReg(pParse);
  72779. codeCompare(pParse, pLeft, pRight, OP_Ge,
  72780. r1, r2, r3, SQLITE_STOREP2);
  72781. pLItem++;
  72782. pRight = pLItem->pExpr;
  72783. sqlite3ReleaseTempReg(pParse, regFree2);
  72784. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  72785. testcase( regFree2==0 );
  72786. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  72787. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  72788. sqlite3ReleaseTempReg(pParse, r3);
  72789. sqlite3ReleaseTempReg(pParse, r4);
  72790. break;
  72791. }
  72792. case TK_COLLATE:
  72793. case TK_UPLUS: {
  72794. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  72795. break;
  72796. }
  72797. case TK_TRIGGER: {
  72798. /* If the opcode is TK_TRIGGER, then the expression is a reference
  72799. ** to a column in the new.* or old.* pseudo-tables available to
  72800. ** trigger programs. In this case Expr.iTable is set to 1 for the
  72801. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  72802. ** is set to the column of the pseudo-table to read, or to -1 to
  72803. ** read the rowid field.
  72804. **
  72805. ** The expression is implemented using an OP_Param opcode. The p1
  72806. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  72807. ** to reference another column of the old.* pseudo-table, where
  72808. ** i is the index of the column. For a new.rowid reference, p1 is
  72809. ** set to (n+1), where n is the number of columns in each pseudo-table.
  72810. ** For a reference to any other column in the new.* pseudo-table, p1
  72811. ** is set to (n+2+i), where n and i are as defined previously. For
  72812. ** example, if the table on which triggers are being fired is
  72813. ** declared as:
  72814. **
  72815. ** CREATE TABLE t1(a, b);
  72816. **
  72817. ** Then p1 is interpreted as follows:
  72818. **
  72819. ** p1==0 -> old.rowid p1==3 -> new.rowid
  72820. ** p1==1 -> old.a p1==4 -> new.a
  72821. ** p1==2 -> old.b p1==5 -> new.b
  72822. */
  72823. Table *pTab = pExpr->pTab;
  72824. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  72825. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  72826. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  72827. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  72828. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  72829. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  72830. VdbeComment((v, "%s.%s -> $%d",
  72831. (pExpr->iTable ? "new" : "old"),
  72832. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  72833. target
  72834. ));
  72835. #ifndef SQLITE_OMIT_FLOATING_POINT
  72836. /* If the column has REAL affinity, it may currently be stored as an
  72837. ** integer. Use OP_RealAffinity to make sure it is really real. */
  72838. if( pExpr->iColumn>=0
  72839. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  72840. ){
  72841. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  72842. }
  72843. #endif
  72844. break;
  72845. }
  72846. /*
  72847. ** Form A:
  72848. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  72849. **
  72850. ** Form B:
  72851. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  72852. **
  72853. ** Form A is can be transformed into the equivalent form B as follows:
  72854. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  72855. ** WHEN x=eN THEN rN ELSE y END
  72856. **
  72857. ** X (if it exists) is in pExpr->pLeft.
  72858. ** Y is in pExpr->pRight. The Y is also optional. If there is no
  72859. ** ELSE clause and no other term matches, then the result of the
  72860. ** exprssion is NULL.
  72861. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  72862. **
  72863. ** The result of the expression is the Ri for the first matching Ei,
  72864. ** or if there is no matching Ei, the ELSE term Y, or if there is
  72865. ** no ELSE term, NULL.
  72866. */
  72867. default: assert( op==TK_CASE ); {
  72868. int endLabel; /* GOTO label for end of CASE stmt */
  72869. int nextCase; /* GOTO label for next WHEN clause */
  72870. int nExpr; /* 2x number of WHEN terms */
  72871. int i; /* Loop counter */
  72872. ExprList *pEList; /* List of WHEN terms */
  72873. struct ExprList_item *aListelem; /* Array of WHEN terms */
  72874. Expr opCompare; /* The X==Ei expression */
  72875. Expr cacheX; /* Cached expression X */
  72876. Expr *pX; /* The X expression */
  72877. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  72878. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  72879. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  72880. assert((pExpr->x.pList->nExpr % 2) == 0);
  72881. assert(pExpr->x.pList->nExpr > 0);
  72882. pEList = pExpr->x.pList;
  72883. aListelem = pEList->a;
  72884. nExpr = pEList->nExpr;
  72885. endLabel = sqlite3VdbeMakeLabel(v);
  72886. if( (pX = pExpr->pLeft)!=0 ){
  72887. cacheX = *pX;
  72888. testcase( pX->op==TK_COLUMN );
  72889. testcase( pX->op==TK_REGISTER );
  72890. cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
  72891. testcase( regFree1==0 );
  72892. cacheX.op = TK_REGISTER;
  72893. opCompare.op = TK_EQ;
  72894. opCompare.pLeft = &cacheX;
  72895. pTest = &opCompare;
  72896. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  72897. ** The value in regFree1 might get SCopy-ed into the file result.
  72898. ** So make sure that the regFree1 register is not reused for other
  72899. ** purposes and possibly overwritten. */
  72900. regFree1 = 0;
  72901. }
  72902. for(i=0; i<nExpr; i=i+2){
  72903. sqlite3ExprCachePush(pParse);
  72904. if( pX ){
  72905. assert( pTest!=0 );
  72906. opCompare.pRight = aListelem[i].pExpr;
  72907. }else{
  72908. pTest = aListelem[i].pExpr;
  72909. }
  72910. nextCase = sqlite3VdbeMakeLabel(v);
  72911. testcase( pTest->op==TK_COLUMN );
  72912. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  72913. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  72914. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  72915. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  72916. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  72917. sqlite3ExprCachePop(pParse, 1);
  72918. sqlite3VdbeResolveLabel(v, nextCase);
  72919. }
  72920. if( pExpr->pRight ){
  72921. sqlite3ExprCachePush(pParse);
  72922. sqlite3ExprCode(pParse, pExpr->pRight, target);
  72923. sqlite3ExprCachePop(pParse, 1);
  72924. }else{
  72925. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  72926. }
  72927. assert( db->mallocFailed || pParse->nErr>0
  72928. || pParse->iCacheLevel==iCacheLevel );
  72929. sqlite3VdbeResolveLabel(v, endLabel);
  72930. break;
  72931. }
  72932. #ifndef SQLITE_OMIT_TRIGGER
  72933. case TK_RAISE: {
  72934. assert( pExpr->affinity==OE_Rollback
  72935. || pExpr->affinity==OE_Abort
  72936. || pExpr->affinity==OE_Fail
  72937. || pExpr->affinity==OE_Ignore
  72938. );
  72939. if( !pParse->pTriggerTab ){
  72940. sqlite3ErrorMsg(pParse,
  72941. "RAISE() may only be used within a trigger-program");
  72942. return 0;
  72943. }
  72944. if( pExpr->affinity==OE_Abort ){
  72945. sqlite3MayAbort(pParse);
  72946. }
  72947. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72948. if( pExpr->affinity==OE_Ignore ){
  72949. sqlite3VdbeAddOp4(
  72950. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  72951. }else{
  72952. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  72953. pExpr->affinity, pExpr->u.zToken, 0);
  72954. }
  72955. break;
  72956. }
  72957. #endif
  72958. }
  72959. sqlite3ReleaseTempReg(pParse, regFree1);
  72960. sqlite3ReleaseTempReg(pParse, regFree2);
  72961. return inReg;
  72962. }
  72963. /*
  72964. ** Generate code to evaluate an expression and store the results
  72965. ** into a register. Return the register number where the results
  72966. ** are stored.
  72967. **
  72968. ** If the register is a temporary register that can be deallocated,
  72969. ** then write its number into *pReg. If the result register is not
  72970. ** a temporary, then set *pReg to zero.
  72971. */
  72972. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  72973. int r1 = sqlite3GetTempReg(pParse);
  72974. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  72975. if( r2==r1 ){
  72976. *pReg = r1;
  72977. }else{
  72978. sqlite3ReleaseTempReg(pParse, r1);
  72979. *pReg = 0;
  72980. }
  72981. return r2;
  72982. }
  72983. /*
  72984. ** Generate code that will evaluate expression pExpr and store the
  72985. ** results in register target. The results are guaranteed to appear
  72986. ** in register target.
  72987. */
  72988. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  72989. int inReg;
  72990. assert( target>0 && target<=pParse->nMem );
  72991. if( pExpr && pExpr->op==TK_REGISTER ){
  72992. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  72993. }else{
  72994. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  72995. assert( pParse->pVdbe || pParse->db->mallocFailed );
  72996. if( inReg!=target && pParse->pVdbe ){
  72997. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  72998. }
  72999. }
  73000. return target;
  73001. }
  73002. /*
  73003. ** Generate code that evalutes the given expression and puts the result
  73004. ** in register target.
  73005. **
  73006. ** Also make a copy of the expression results into another "cache" register
  73007. ** and modify the expression so that the next time it is evaluated,
  73008. ** the result is a copy of the cache register.
  73009. **
  73010. ** This routine is used for expressions that are used multiple
  73011. ** times. They are evaluated once and the results of the expression
  73012. ** are reused.
  73013. */
  73014. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  73015. Vdbe *v = pParse->pVdbe;
  73016. int inReg;
  73017. inReg = sqlite3ExprCode(pParse, pExpr, target);
  73018. assert( target>0 );
  73019. /* This routine is called for terms to INSERT or UPDATE. And the only
  73020. ** other place where expressions can be converted into TK_REGISTER is
  73021. ** in WHERE clause processing. So as currently implemented, there is
  73022. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  73023. ** keep the ALWAYS() in case the conditions above change with future
  73024. ** modifications or enhancements. */
  73025. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  73026. int iMem;
  73027. iMem = ++pParse->nMem;
  73028. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  73029. pExpr->iTable = iMem;
  73030. pExpr->op2 = pExpr->op;
  73031. pExpr->op = TK_REGISTER;
  73032. }
  73033. return inReg;
  73034. }
  73035. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  73036. /*
  73037. ** Generate a human-readable explanation of an expression tree.
  73038. */
  73039. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  73040. int op; /* The opcode being coded */
  73041. const char *zBinOp = 0; /* Binary operator */
  73042. const char *zUniOp = 0; /* Unary operator */
  73043. if( pExpr==0 ){
  73044. op = TK_NULL;
  73045. }else{
  73046. op = pExpr->op;
  73047. }
  73048. switch( op ){
  73049. case TK_AGG_COLUMN: {
  73050. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  73051. pExpr->iTable, pExpr->iColumn);
  73052. break;
  73053. }
  73054. case TK_COLUMN: {
  73055. if( pExpr->iTable<0 ){
  73056. /* This only happens when coding check constraints */
  73057. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  73058. }else{
  73059. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  73060. pExpr->iTable, pExpr->iColumn);
  73061. }
  73062. break;
  73063. }
  73064. case TK_INTEGER: {
  73065. if( pExpr->flags & EP_IntValue ){
  73066. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  73067. }else{
  73068. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  73069. }
  73070. break;
  73071. }
  73072. #ifndef SQLITE_OMIT_FLOATING_POINT
  73073. case TK_FLOAT: {
  73074. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  73075. break;
  73076. }
  73077. #endif
  73078. case TK_STRING: {
  73079. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  73080. break;
  73081. }
  73082. case TK_NULL: {
  73083. sqlite3ExplainPrintf(pOut,"NULL");
  73084. break;
  73085. }
  73086. #ifndef SQLITE_OMIT_BLOB_LITERAL
  73087. case TK_BLOB: {
  73088. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  73089. break;
  73090. }
  73091. #endif
  73092. case TK_VARIABLE: {
  73093. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  73094. pExpr->u.zToken, pExpr->iColumn);
  73095. break;
  73096. }
  73097. case TK_REGISTER: {
  73098. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  73099. break;
  73100. }
  73101. case TK_AS: {
  73102. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73103. break;
  73104. }
  73105. #ifndef SQLITE_OMIT_CAST
  73106. case TK_CAST: {
  73107. /* Expressions of the form: CAST(pLeft AS token) */
  73108. const char *zAff = "unk";
  73109. switch( sqlite3AffinityType(pExpr->u.zToken) ){
  73110. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  73111. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  73112. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  73113. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  73114. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  73115. }
  73116. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  73117. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73118. sqlite3ExplainPrintf(pOut, ")");
  73119. break;
  73120. }
  73121. #endif /* SQLITE_OMIT_CAST */
  73122. case TK_LT: zBinOp = "LT"; break;
  73123. case TK_LE: zBinOp = "LE"; break;
  73124. case TK_GT: zBinOp = "GT"; break;
  73125. case TK_GE: zBinOp = "GE"; break;
  73126. case TK_NE: zBinOp = "NE"; break;
  73127. case TK_EQ: zBinOp = "EQ"; break;
  73128. case TK_IS: zBinOp = "IS"; break;
  73129. case TK_ISNOT: zBinOp = "ISNOT"; break;
  73130. case TK_AND: zBinOp = "AND"; break;
  73131. case TK_OR: zBinOp = "OR"; break;
  73132. case TK_PLUS: zBinOp = "ADD"; break;
  73133. case TK_STAR: zBinOp = "MUL"; break;
  73134. case TK_MINUS: zBinOp = "SUB"; break;
  73135. case TK_REM: zBinOp = "REM"; break;
  73136. case TK_BITAND: zBinOp = "BITAND"; break;
  73137. case TK_BITOR: zBinOp = "BITOR"; break;
  73138. case TK_SLASH: zBinOp = "DIV"; break;
  73139. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  73140. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  73141. case TK_CONCAT: zBinOp = "CONCAT"; break;
  73142. case TK_UMINUS: zUniOp = "UMINUS"; break;
  73143. case TK_UPLUS: zUniOp = "UPLUS"; break;
  73144. case TK_BITNOT: zUniOp = "BITNOT"; break;
  73145. case TK_NOT: zUniOp = "NOT"; break;
  73146. case TK_ISNULL: zUniOp = "ISNULL"; break;
  73147. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  73148. case TK_COLLATE: {
  73149. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73150. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  73151. break;
  73152. }
  73153. case TK_AGG_FUNCTION:
  73154. case TK_CONST_FUNC:
  73155. case TK_FUNCTION: {
  73156. ExprList *pFarg; /* List of function arguments */
  73157. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
  73158. pFarg = 0;
  73159. }else{
  73160. pFarg = pExpr->x.pList;
  73161. }
  73162. if( op==TK_AGG_FUNCTION ){
  73163. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  73164. pExpr->op2, pExpr->u.zToken);
  73165. }else{
  73166. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  73167. }
  73168. if( pFarg ){
  73169. sqlite3ExplainExprList(pOut, pFarg);
  73170. }
  73171. sqlite3ExplainPrintf(pOut, ")");
  73172. break;
  73173. }
  73174. #ifndef SQLITE_OMIT_SUBQUERY
  73175. case TK_EXISTS: {
  73176. sqlite3ExplainPrintf(pOut, "EXISTS(");
  73177. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  73178. sqlite3ExplainPrintf(pOut,")");
  73179. break;
  73180. }
  73181. case TK_SELECT: {
  73182. sqlite3ExplainPrintf(pOut, "(");
  73183. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  73184. sqlite3ExplainPrintf(pOut, ")");
  73185. break;
  73186. }
  73187. case TK_IN: {
  73188. sqlite3ExplainPrintf(pOut, "IN(");
  73189. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73190. sqlite3ExplainPrintf(pOut, ",");
  73191. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  73192. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  73193. }else{
  73194. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  73195. }
  73196. sqlite3ExplainPrintf(pOut, ")");
  73197. break;
  73198. }
  73199. #endif /* SQLITE_OMIT_SUBQUERY */
  73200. /*
  73201. ** x BETWEEN y AND z
  73202. **
  73203. ** This is equivalent to
  73204. **
  73205. ** x>=y AND x<=z
  73206. **
  73207. ** X is stored in pExpr->pLeft.
  73208. ** Y is stored in pExpr->pList->a[0].pExpr.
  73209. ** Z is stored in pExpr->pList->a[1].pExpr.
  73210. */
  73211. case TK_BETWEEN: {
  73212. Expr *pX = pExpr->pLeft;
  73213. Expr *pY = pExpr->x.pList->a[0].pExpr;
  73214. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  73215. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  73216. sqlite3ExplainExpr(pOut, pX);
  73217. sqlite3ExplainPrintf(pOut, ",");
  73218. sqlite3ExplainExpr(pOut, pY);
  73219. sqlite3ExplainPrintf(pOut, ",");
  73220. sqlite3ExplainExpr(pOut, pZ);
  73221. sqlite3ExplainPrintf(pOut, ")");
  73222. break;
  73223. }
  73224. case TK_TRIGGER: {
  73225. /* If the opcode is TK_TRIGGER, then the expression is a reference
  73226. ** to a column in the new.* or old.* pseudo-tables available to
  73227. ** trigger programs. In this case Expr.iTable is set to 1 for the
  73228. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  73229. ** is set to the column of the pseudo-table to read, or to -1 to
  73230. ** read the rowid field.
  73231. */
  73232. sqlite3ExplainPrintf(pOut, "%s(%d)",
  73233. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  73234. break;
  73235. }
  73236. case TK_CASE: {
  73237. sqlite3ExplainPrintf(pOut, "CASE(");
  73238. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73239. sqlite3ExplainPrintf(pOut, ",");
  73240. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  73241. break;
  73242. }
  73243. #ifndef SQLITE_OMIT_TRIGGER
  73244. case TK_RAISE: {
  73245. const char *zType = "unk";
  73246. switch( pExpr->affinity ){
  73247. case OE_Rollback: zType = "rollback"; break;
  73248. case OE_Abort: zType = "abort"; break;
  73249. case OE_Fail: zType = "fail"; break;
  73250. case OE_Ignore: zType = "ignore"; break;
  73251. }
  73252. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  73253. break;
  73254. }
  73255. #endif
  73256. }
  73257. if( zBinOp ){
  73258. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  73259. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73260. sqlite3ExplainPrintf(pOut,",");
  73261. sqlite3ExplainExpr(pOut, pExpr->pRight);
  73262. sqlite3ExplainPrintf(pOut,")");
  73263. }else if( zUniOp ){
  73264. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  73265. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  73266. sqlite3ExplainPrintf(pOut,")");
  73267. }
  73268. }
  73269. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  73270. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  73271. /*
  73272. ** Generate a human-readable explanation of an expression list.
  73273. */
  73274. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  73275. int i;
  73276. if( pList==0 || pList->nExpr==0 ){
  73277. sqlite3ExplainPrintf(pOut, "(empty-list)");
  73278. return;
  73279. }else if( pList->nExpr==1 ){
  73280. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  73281. }else{
  73282. sqlite3ExplainPush(pOut);
  73283. for(i=0; i<pList->nExpr; i++){
  73284. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  73285. sqlite3ExplainPush(pOut);
  73286. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  73287. sqlite3ExplainPop(pOut);
  73288. if( pList->a[i].zName ){
  73289. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  73290. }
  73291. if( pList->a[i].bSpanIsTab ){
  73292. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  73293. }
  73294. if( i<pList->nExpr-1 ){
  73295. sqlite3ExplainNL(pOut);
  73296. }
  73297. }
  73298. sqlite3ExplainPop(pOut);
  73299. }
  73300. }
  73301. #endif /* SQLITE_DEBUG */
  73302. /*
  73303. ** Return TRUE if pExpr is an constant expression that is appropriate
  73304. ** for factoring out of a loop. Appropriate expressions are:
  73305. **
  73306. ** * Any expression that evaluates to two or more opcodes.
  73307. **
  73308. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  73309. ** or OP_Variable that does not need to be placed in a
  73310. ** specific register.
  73311. **
  73312. ** There is no point in factoring out single-instruction constant
  73313. ** expressions that need to be placed in a particular register.
  73314. ** We could factor them out, but then we would end up adding an
  73315. ** OP_SCopy instruction to move the value into the correct register
  73316. ** later. We might as well just use the original instruction and
  73317. ** avoid the OP_SCopy.
  73318. */
  73319. static int isAppropriateForFactoring(Expr *p){
  73320. if( !sqlite3ExprIsConstantNotJoin(p) ){
  73321. return 0; /* Only constant expressions are appropriate for factoring */
  73322. }
  73323. if( (p->flags & EP_FixedDest)==0 ){
  73324. return 1; /* Any constant without a fixed destination is appropriate */
  73325. }
  73326. while( p->op==TK_UPLUS ) p = p->pLeft;
  73327. switch( p->op ){
  73328. #ifndef SQLITE_OMIT_BLOB_LITERAL
  73329. case TK_BLOB:
  73330. #endif
  73331. case TK_VARIABLE:
  73332. case TK_INTEGER:
  73333. case TK_FLOAT:
  73334. case TK_NULL:
  73335. case TK_STRING: {
  73336. testcase( p->op==TK_BLOB );
  73337. testcase( p->op==TK_VARIABLE );
  73338. testcase( p->op==TK_INTEGER );
  73339. testcase( p->op==TK_FLOAT );
  73340. testcase( p->op==TK_NULL );
  73341. testcase( p->op==TK_STRING );
  73342. /* Single-instruction constants with a fixed destination are
  73343. ** better done in-line. If we factor them, they will just end
  73344. ** up generating an OP_SCopy to move the value to the destination
  73345. ** register. */
  73346. return 0;
  73347. }
  73348. case TK_UMINUS: {
  73349. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  73350. return 0;
  73351. }
  73352. break;
  73353. }
  73354. default: {
  73355. break;
  73356. }
  73357. }
  73358. return 1;
  73359. }
  73360. /*
  73361. ** If pExpr is a constant expression that is appropriate for
  73362. ** factoring out of a loop, then evaluate the expression
  73363. ** into a register and convert the expression into a TK_REGISTER
  73364. ** expression.
  73365. */
  73366. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  73367. Parse *pParse = pWalker->pParse;
  73368. switch( pExpr->op ){
  73369. case TK_IN:
  73370. case TK_REGISTER: {
  73371. return WRC_Prune;
  73372. }
  73373. case TK_COLLATE: {
  73374. return WRC_Continue;
  73375. }
  73376. case TK_FUNCTION:
  73377. case TK_AGG_FUNCTION:
  73378. case TK_CONST_FUNC: {
  73379. /* The arguments to a function have a fixed destination.
  73380. ** Mark them this way to avoid generated unneeded OP_SCopy
  73381. ** instructions.
  73382. */
  73383. ExprList *pList = pExpr->x.pList;
  73384. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  73385. if( pList ){
  73386. int i = pList->nExpr;
  73387. struct ExprList_item *pItem = pList->a;
  73388. for(; i>0; i--, pItem++){
  73389. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  73390. }
  73391. }
  73392. break;
  73393. }
  73394. }
  73395. if( isAppropriateForFactoring(pExpr) ){
  73396. int r1 = ++pParse->nMem;
  73397. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  73398. /* If r2!=r1, it means that register r1 is never used. That is harmless
  73399. ** but suboptimal, so we want to know about the situation to fix it.
  73400. ** Hence the following assert: */
  73401. assert( r2==r1 );
  73402. pExpr->op2 = pExpr->op;
  73403. pExpr->op = TK_REGISTER;
  73404. pExpr->iTable = r2;
  73405. return WRC_Prune;
  73406. }
  73407. return WRC_Continue;
  73408. }
  73409. /*
  73410. ** Preevaluate constant subexpressions within pExpr and store the
  73411. ** results in registers. Modify pExpr so that the constant subexpresions
  73412. ** are TK_REGISTER opcodes that refer to the precomputed values.
  73413. **
  73414. ** This routine is a no-op if the jump to the cookie-check code has
  73415. ** already occur. Since the cookie-check jump is generated prior to
  73416. ** any other serious processing, this check ensures that there is no
  73417. ** way to accidently bypass the constant initializations.
  73418. **
  73419. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  73420. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  73421. ** interface. This allows test logic to verify that the same answer is
  73422. ** obtained for queries regardless of whether or not constants are
  73423. ** precomputed into registers or if they are inserted in-line.
  73424. */
  73425. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  73426. Walker w;
  73427. if( pParse->cookieGoto ) return;
  73428. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  73429. memset(&w, 0, sizeof(w));
  73430. w.xExprCallback = evalConstExpr;
  73431. w.pParse = pParse;
  73432. sqlite3WalkExpr(&w, pExpr);
  73433. }
  73434. /*
  73435. ** Generate code that pushes the value of every element of the given
  73436. ** expression list into a sequence of registers beginning at target.
  73437. **
  73438. ** Return the number of elements evaluated.
  73439. */
  73440. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  73441. Parse *pParse, /* Parsing context */
  73442. ExprList *pList, /* The expression list to be coded */
  73443. int target, /* Where to write results */
  73444. int doHardCopy /* Make a hard copy of every element */
  73445. ){
  73446. struct ExprList_item *pItem;
  73447. int i, n;
  73448. assert( pList!=0 );
  73449. assert( target>0 );
  73450. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  73451. n = pList->nExpr;
  73452. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  73453. Expr *pExpr = pItem->pExpr;
  73454. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  73455. if( inReg!=target+i ){
  73456. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  73457. inReg, target+i);
  73458. }
  73459. }
  73460. return n;
  73461. }
  73462. /*
  73463. ** Generate code for a BETWEEN operator.
  73464. **
  73465. ** x BETWEEN y AND z
  73466. **
  73467. ** The above is equivalent to
  73468. **
  73469. ** x>=y AND x<=z
  73470. **
  73471. ** Code it as such, taking care to do the common subexpression
  73472. ** elementation of x.
  73473. */
  73474. static void exprCodeBetween(
  73475. Parse *pParse, /* Parsing and code generating context */
  73476. Expr *pExpr, /* The BETWEEN expression */
  73477. int dest, /* Jump here if the jump is taken */
  73478. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  73479. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  73480. ){
  73481. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  73482. Expr compLeft; /* The x>=y term */
  73483. Expr compRight; /* The x<=z term */
  73484. Expr exprX; /* The x subexpression */
  73485. int regFree1 = 0; /* Temporary use register */
  73486. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  73487. exprX = *pExpr->pLeft;
  73488. exprAnd.op = TK_AND;
  73489. exprAnd.pLeft = &compLeft;
  73490. exprAnd.pRight = &compRight;
  73491. compLeft.op = TK_GE;
  73492. compLeft.pLeft = &exprX;
  73493. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  73494. compRight.op = TK_LE;
  73495. compRight.pLeft = &exprX;
  73496. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  73497. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  73498. exprX.op = TK_REGISTER;
  73499. if( jumpIfTrue ){
  73500. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  73501. }else{
  73502. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  73503. }
  73504. sqlite3ReleaseTempReg(pParse, regFree1);
  73505. /* Ensure adequate test coverage */
  73506. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  73507. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  73508. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  73509. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  73510. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  73511. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  73512. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  73513. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  73514. }
  73515. /*
  73516. ** Generate code for a boolean expression such that a jump is made
  73517. ** to the label "dest" if the expression is true but execution
  73518. ** continues straight thru if the expression is false.
  73519. **
  73520. ** If the expression evaluates to NULL (neither true nor false), then
  73521. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  73522. **
  73523. ** This code depends on the fact that certain token values (ex: TK_EQ)
  73524. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  73525. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  73526. ** the make process cause these values to align. Assert()s in the code
  73527. ** below verify that the numbers are aligned correctly.
  73528. */
  73529. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  73530. Vdbe *v = pParse->pVdbe;
  73531. int op = 0;
  73532. int regFree1 = 0;
  73533. int regFree2 = 0;
  73534. int r1, r2;
  73535. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  73536. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  73537. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  73538. op = pExpr->op;
  73539. switch( op ){
  73540. case TK_AND: {
  73541. int d2 = sqlite3VdbeMakeLabel(v);
  73542. testcase( jumpIfNull==0 );
  73543. sqlite3ExprCachePush(pParse);
  73544. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  73545. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  73546. sqlite3VdbeResolveLabel(v, d2);
  73547. sqlite3ExprCachePop(pParse, 1);
  73548. break;
  73549. }
  73550. case TK_OR: {
  73551. testcase( jumpIfNull==0 );
  73552. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  73553. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  73554. break;
  73555. }
  73556. case TK_NOT: {
  73557. testcase( jumpIfNull==0 );
  73558. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  73559. break;
  73560. }
  73561. case TK_LT:
  73562. case TK_LE:
  73563. case TK_GT:
  73564. case TK_GE:
  73565. case TK_NE:
  73566. case TK_EQ: {
  73567. assert( TK_LT==OP_Lt );
  73568. assert( TK_LE==OP_Le );
  73569. assert( TK_GT==OP_Gt );
  73570. assert( TK_GE==OP_Ge );
  73571. assert( TK_EQ==OP_Eq );
  73572. assert( TK_NE==OP_Ne );
  73573. testcase( op==TK_LT );
  73574. testcase( op==TK_LE );
  73575. testcase( op==TK_GT );
  73576. testcase( op==TK_GE );
  73577. testcase( op==TK_EQ );
  73578. testcase( op==TK_NE );
  73579. testcase( jumpIfNull==0 );
  73580. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73581. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73582. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73583. r1, r2, dest, jumpIfNull);
  73584. testcase( regFree1==0 );
  73585. testcase( regFree2==0 );
  73586. break;
  73587. }
  73588. case TK_IS:
  73589. case TK_ISNOT: {
  73590. testcase( op==TK_IS );
  73591. testcase( op==TK_ISNOT );
  73592. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73593. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73594. op = (op==TK_IS) ? TK_EQ : TK_NE;
  73595. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73596. r1, r2, dest, SQLITE_NULLEQ);
  73597. testcase( regFree1==0 );
  73598. testcase( regFree2==0 );
  73599. break;
  73600. }
  73601. case TK_ISNULL:
  73602. case TK_NOTNULL: {
  73603. assert( TK_ISNULL==OP_IsNull );
  73604. assert( TK_NOTNULL==OP_NotNull );
  73605. testcase( op==TK_ISNULL );
  73606. testcase( op==TK_NOTNULL );
  73607. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73608. sqlite3VdbeAddOp2(v, op, r1, dest);
  73609. testcase( regFree1==0 );
  73610. break;
  73611. }
  73612. case TK_BETWEEN: {
  73613. testcase( jumpIfNull==0 );
  73614. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  73615. break;
  73616. }
  73617. #ifndef SQLITE_OMIT_SUBQUERY
  73618. case TK_IN: {
  73619. int destIfFalse = sqlite3VdbeMakeLabel(v);
  73620. int destIfNull = jumpIfNull ? dest : destIfFalse;
  73621. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  73622. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  73623. sqlite3VdbeResolveLabel(v, destIfFalse);
  73624. break;
  73625. }
  73626. #endif
  73627. default: {
  73628. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  73629. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  73630. testcase( regFree1==0 );
  73631. testcase( jumpIfNull==0 );
  73632. break;
  73633. }
  73634. }
  73635. sqlite3ReleaseTempReg(pParse, regFree1);
  73636. sqlite3ReleaseTempReg(pParse, regFree2);
  73637. }
  73638. /*
  73639. ** Generate code for a boolean expression such that a jump is made
  73640. ** to the label "dest" if the expression is false but execution
  73641. ** continues straight thru if the expression is true.
  73642. **
  73643. ** If the expression evaluates to NULL (neither true nor false) then
  73644. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  73645. ** is 0.
  73646. */
  73647. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  73648. Vdbe *v = pParse->pVdbe;
  73649. int op = 0;
  73650. int regFree1 = 0;
  73651. int regFree2 = 0;
  73652. int r1, r2;
  73653. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  73654. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  73655. if( pExpr==0 ) return;
  73656. /* The value of pExpr->op and op are related as follows:
  73657. **
  73658. ** pExpr->op op
  73659. ** --------- ----------
  73660. ** TK_ISNULL OP_NotNull
  73661. ** TK_NOTNULL OP_IsNull
  73662. ** TK_NE OP_Eq
  73663. ** TK_EQ OP_Ne
  73664. ** TK_GT OP_Le
  73665. ** TK_LE OP_Gt
  73666. ** TK_GE OP_Lt
  73667. ** TK_LT OP_Ge
  73668. **
  73669. ** For other values of pExpr->op, op is undefined and unused.
  73670. ** The value of TK_ and OP_ constants are arranged such that we
  73671. ** can compute the mapping above using the following expression.
  73672. ** Assert()s verify that the computation is correct.
  73673. */
  73674. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  73675. /* Verify correct alignment of TK_ and OP_ constants
  73676. */
  73677. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  73678. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  73679. assert( pExpr->op!=TK_NE || op==OP_Eq );
  73680. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  73681. assert( pExpr->op!=TK_LT || op==OP_Ge );
  73682. assert( pExpr->op!=TK_LE || op==OP_Gt );
  73683. assert( pExpr->op!=TK_GT || op==OP_Le );
  73684. assert( pExpr->op!=TK_GE || op==OP_Lt );
  73685. switch( pExpr->op ){
  73686. case TK_AND: {
  73687. testcase( jumpIfNull==0 );
  73688. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  73689. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  73690. break;
  73691. }
  73692. case TK_OR: {
  73693. int d2 = sqlite3VdbeMakeLabel(v);
  73694. testcase( jumpIfNull==0 );
  73695. sqlite3ExprCachePush(pParse);
  73696. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  73697. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  73698. sqlite3VdbeResolveLabel(v, d2);
  73699. sqlite3ExprCachePop(pParse, 1);
  73700. break;
  73701. }
  73702. case TK_NOT: {
  73703. testcase( jumpIfNull==0 );
  73704. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  73705. break;
  73706. }
  73707. case TK_LT:
  73708. case TK_LE:
  73709. case TK_GT:
  73710. case TK_GE:
  73711. case TK_NE:
  73712. case TK_EQ: {
  73713. testcase( op==TK_LT );
  73714. testcase( op==TK_LE );
  73715. testcase( op==TK_GT );
  73716. testcase( op==TK_GE );
  73717. testcase( op==TK_EQ );
  73718. testcase( op==TK_NE );
  73719. testcase( jumpIfNull==0 );
  73720. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73721. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73722. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73723. r1, r2, dest, jumpIfNull);
  73724. testcase( regFree1==0 );
  73725. testcase( regFree2==0 );
  73726. break;
  73727. }
  73728. case TK_IS:
  73729. case TK_ISNOT: {
  73730. testcase( pExpr->op==TK_IS );
  73731. testcase( pExpr->op==TK_ISNOT );
  73732. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73733. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  73734. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  73735. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  73736. r1, r2, dest, SQLITE_NULLEQ);
  73737. testcase( regFree1==0 );
  73738. testcase( regFree2==0 );
  73739. break;
  73740. }
  73741. case TK_ISNULL:
  73742. case TK_NOTNULL: {
  73743. testcase( op==TK_ISNULL );
  73744. testcase( op==TK_NOTNULL );
  73745. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  73746. sqlite3VdbeAddOp2(v, op, r1, dest);
  73747. testcase( regFree1==0 );
  73748. break;
  73749. }
  73750. case TK_BETWEEN: {
  73751. testcase( jumpIfNull==0 );
  73752. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  73753. break;
  73754. }
  73755. #ifndef SQLITE_OMIT_SUBQUERY
  73756. case TK_IN: {
  73757. if( jumpIfNull ){
  73758. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  73759. }else{
  73760. int destIfNull = sqlite3VdbeMakeLabel(v);
  73761. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  73762. sqlite3VdbeResolveLabel(v, destIfNull);
  73763. }
  73764. break;
  73765. }
  73766. #endif
  73767. default: {
  73768. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  73769. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  73770. testcase( regFree1==0 );
  73771. testcase( jumpIfNull==0 );
  73772. break;
  73773. }
  73774. }
  73775. sqlite3ReleaseTempReg(pParse, regFree1);
  73776. sqlite3ReleaseTempReg(pParse, regFree2);
  73777. }
  73778. /*
  73779. ** Do a deep comparison of two expression trees. Return 0 if the two
  73780. ** expressions are completely identical. Return 1 if they differ only
  73781. ** by a COLLATE operator at the top level. Return 2 if there are differences
  73782. ** other than the top-level COLLATE operator.
  73783. **
  73784. ** Sometimes this routine will return 2 even if the two expressions
  73785. ** really are equivalent. If we cannot prove that the expressions are
  73786. ** identical, we return 2 just to be safe. So if this routine
  73787. ** returns 2, then you do not really know for certain if the two
  73788. ** expressions are the same. But if you get a 0 or 1 return, then you
  73789. ** can be sure the expressions are the same. In the places where
  73790. ** this routine is used, it does not hurt to get an extra 2 - that
  73791. ** just might result in some slightly slower code. But returning
  73792. ** an incorrect 0 or 1 could lead to a malfunction.
  73793. */
  73794. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  73795. if( pA==0||pB==0 ){
  73796. return pB==pA ? 0 : 2;
  73797. }
  73798. assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
  73799. assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
  73800. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  73801. return 2;
  73802. }
  73803. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  73804. if( pA->op!=pB->op ){
  73805. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
  73806. return 1;
  73807. }
  73808. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
  73809. return 1;
  73810. }
  73811. return 2;
  73812. }
  73813. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
  73814. if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
  73815. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
  73816. if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
  73817. if( ExprHasProperty(pA, EP_IntValue) ){
  73818. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  73819. return 2;
  73820. }
  73821. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  73822. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  73823. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  73824. return pA->op==TK_COLLATE ? 1 : 2;
  73825. }
  73826. }
  73827. return 0;
  73828. }
  73829. /*
  73830. ** Compare two ExprList objects. Return 0 if they are identical and
  73831. ** non-zero if they differ in any way.
  73832. **
  73833. ** This routine might return non-zero for equivalent ExprLists. The
  73834. ** only consequence will be disabled optimizations. But this routine
  73835. ** must never return 0 if the two ExprList objects are different, or
  73836. ** a malfunction will result.
  73837. **
  73838. ** Two NULL pointers are considered to be the same. But a NULL pointer
  73839. ** always differs from a non-NULL pointer.
  73840. */
  73841. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
  73842. int i;
  73843. if( pA==0 && pB==0 ) return 0;
  73844. if( pA==0 || pB==0 ) return 1;
  73845. if( pA->nExpr!=pB->nExpr ) return 1;
  73846. for(i=0; i<pA->nExpr; i++){
  73847. Expr *pExprA = pA->a[i].pExpr;
  73848. Expr *pExprB = pB->a[i].pExpr;
  73849. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  73850. if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
  73851. }
  73852. return 0;
  73853. }
  73854. /*
  73855. ** An instance of the following structure is used by the tree walker
  73856. ** to count references to table columns in the arguments of an
  73857. ** aggregate function, in order to implement the
  73858. ** sqlite3FunctionThisSrc() routine.
  73859. */
  73860. struct SrcCount {
  73861. SrcList *pSrc; /* One particular FROM clause in a nested query */
  73862. int nThis; /* Number of references to columns in pSrcList */
  73863. int nOther; /* Number of references to columns in other FROM clauses */
  73864. };
  73865. /*
  73866. ** Count the number of references to columns.
  73867. */
  73868. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  73869. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  73870. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  73871. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  73872. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  73873. ** NEVER() will need to be removed. */
  73874. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  73875. int i;
  73876. struct SrcCount *p = pWalker->u.pSrcCount;
  73877. SrcList *pSrc = p->pSrc;
  73878. for(i=0; i<pSrc->nSrc; i++){
  73879. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  73880. }
  73881. if( i<pSrc->nSrc ){
  73882. p->nThis++;
  73883. }else{
  73884. p->nOther++;
  73885. }
  73886. }
  73887. return WRC_Continue;
  73888. }
  73889. /*
  73890. ** Determine if any of the arguments to the pExpr Function reference
  73891. ** pSrcList. Return true if they do. Also return true if the function
  73892. ** has no arguments or has only constant arguments. Return false if pExpr
  73893. ** references columns but not columns of tables found in pSrcList.
  73894. */
  73895. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  73896. Walker w;
  73897. struct SrcCount cnt;
  73898. assert( pExpr->op==TK_AGG_FUNCTION );
  73899. memset(&w, 0, sizeof(w));
  73900. w.xExprCallback = exprSrcCount;
  73901. w.u.pSrcCount = &cnt;
  73902. cnt.pSrc = pSrcList;
  73903. cnt.nThis = 0;
  73904. cnt.nOther = 0;
  73905. sqlite3WalkExprList(&w, pExpr->x.pList);
  73906. return cnt.nThis>0 || cnt.nOther==0;
  73907. }
  73908. /*
  73909. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  73910. ** the new element. Return a negative number if malloc fails.
  73911. */
  73912. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  73913. int i;
  73914. pInfo->aCol = sqlite3ArrayAllocate(
  73915. db,
  73916. pInfo->aCol,
  73917. sizeof(pInfo->aCol[0]),
  73918. &pInfo->nColumn,
  73919. &i
  73920. );
  73921. return i;
  73922. }
  73923. /*
  73924. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  73925. ** the new element. Return a negative number if malloc fails.
  73926. */
  73927. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  73928. int i;
  73929. pInfo->aFunc = sqlite3ArrayAllocate(
  73930. db,
  73931. pInfo->aFunc,
  73932. sizeof(pInfo->aFunc[0]),
  73933. &pInfo->nFunc,
  73934. &i
  73935. );
  73936. return i;
  73937. }
  73938. /*
  73939. ** This is the xExprCallback for a tree walker. It is used to
  73940. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  73941. ** for additional information.
  73942. */
  73943. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  73944. int i;
  73945. NameContext *pNC = pWalker->u.pNC;
  73946. Parse *pParse = pNC->pParse;
  73947. SrcList *pSrcList = pNC->pSrcList;
  73948. AggInfo *pAggInfo = pNC->pAggInfo;
  73949. switch( pExpr->op ){
  73950. case TK_AGG_COLUMN:
  73951. case TK_COLUMN: {
  73952. testcase( pExpr->op==TK_AGG_COLUMN );
  73953. testcase( pExpr->op==TK_COLUMN );
  73954. /* Check to see if the column is in one of the tables in the FROM
  73955. ** clause of the aggregate query */
  73956. if( ALWAYS(pSrcList!=0) ){
  73957. struct SrcList_item *pItem = pSrcList->a;
  73958. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  73959. struct AggInfo_col *pCol;
  73960. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  73961. if( pExpr->iTable==pItem->iCursor ){
  73962. /* If we reach this point, it means that pExpr refers to a table
  73963. ** that is in the FROM clause of the aggregate query.
  73964. **
  73965. ** Make an entry for the column in pAggInfo->aCol[] if there
  73966. ** is not an entry there already.
  73967. */
  73968. int k;
  73969. pCol = pAggInfo->aCol;
  73970. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  73971. if( pCol->iTable==pExpr->iTable &&
  73972. pCol->iColumn==pExpr->iColumn ){
  73973. break;
  73974. }
  73975. }
  73976. if( (k>=pAggInfo->nColumn)
  73977. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  73978. ){
  73979. pCol = &pAggInfo->aCol[k];
  73980. pCol->pTab = pExpr->pTab;
  73981. pCol->iTable = pExpr->iTable;
  73982. pCol->iColumn = pExpr->iColumn;
  73983. pCol->iMem = ++pParse->nMem;
  73984. pCol->iSorterColumn = -1;
  73985. pCol->pExpr = pExpr;
  73986. if( pAggInfo->pGroupBy ){
  73987. int j, n;
  73988. ExprList *pGB = pAggInfo->pGroupBy;
  73989. struct ExprList_item *pTerm = pGB->a;
  73990. n = pGB->nExpr;
  73991. for(j=0; j<n; j++, pTerm++){
  73992. Expr *pE = pTerm->pExpr;
  73993. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  73994. pE->iColumn==pExpr->iColumn ){
  73995. pCol->iSorterColumn = j;
  73996. break;
  73997. }
  73998. }
  73999. }
  74000. if( pCol->iSorterColumn<0 ){
  74001. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  74002. }
  74003. }
  74004. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  74005. ** because it was there before or because we just created it).
  74006. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  74007. ** pAggInfo->aCol[] entry.
  74008. */
  74009. ExprSetIrreducible(pExpr);
  74010. pExpr->pAggInfo = pAggInfo;
  74011. pExpr->op = TK_AGG_COLUMN;
  74012. pExpr->iAgg = (i16)k;
  74013. break;
  74014. } /* endif pExpr->iTable==pItem->iCursor */
  74015. } /* end loop over pSrcList */
  74016. }
  74017. return WRC_Prune;
  74018. }
  74019. case TK_AGG_FUNCTION: {
  74020. if( (pNC->ncFlags & NC_InAggFunc)==0
  74021. && pWalker->walkerDepth==pExpr->op2
  74022. ){
  74023. /* Check to see if pExpr is a duplicate of another aggregate
  74024. ** function that is already in the pAggInfo structure
  74025. */
  74026. struct AggInfo_func *pItem = pAggInfo->aFunc;
  74027. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  74028. if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
  74029. break;
  74030. }
  74031. }
  74032. if( i>=pAggInfo->nFunc ){
  74033. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  74034. */
  74035. u8 enc = ENC(pParse->db);
  74036. i = addAggInfoFunc(pParse->db, pAggInfo);
  74037. if( i>=0 ){
  74038. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74039. pItem = &pAggInfo->aFunc[i];
  74040. pItem->pExpr = pExpr;
  74041. pItem->iMem = ++pParse->nMem;
  74042. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  74043. pItem->pFunc = sqlite3FindFunction(pParse->db,
  74044. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  74045. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  74046. if( pExpr->flags & EP_Distinct ){
  74047. pItem->iDistinct = pParse->nTab++;
  74048. }else{
  74049. pItem->iDistinct = -1;
  74050. }
  74051. }
  74052. }
  74053. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  74054. */
  74055. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  74056. ExprSetIrreducible(pExpr);
  74057. pExpr->iAgg = (i16)i;
  74058. pExpr->pAggInfo = pAggInfo;
  74059. return WRC_Prune;
  74060. }else{
  74061. return WRC_Continue;
  74062. }
  74063. }
  74064. }
  74065. return WRC_Continue;
  74066. }
  74067. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  74068. UNUSED_PARAMETER(pWalker);
  74069. UNUSED_PARAMETER(pSelect);
  74070. return WRC_Continue;
  74071. }
  74072. /*
  74073. ** Analyze the pExpr expression looking for aggregate functions and
  74074. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  74075. ** points to. Additional entries are made on the AggInfo object as
  74076. ** necessary.
  74077. **
  74078. ** This routine should only be called after the expression has been
  74079. ** analyzed by sqlite3ResolveExprNames().
  74080. */
  74081. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  74082. Walker w;
  74083. memset(&w, 0, sizeof(w));
  74084. w.xExprCallback = analyzeAggregate;
  74085. w.xSelectCallback = analyzeAggregatesInSelect;
  74086. w.u.pNC = pNC;
  74087. assert( pNC->pSrcList!=0 );
  74088. sqlite3WalkExpr(&w, pExpr);
  74089. }
  74090. /*
  74091. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  74092. ** expression list. Return the number of errors.
  74093. **
  74094. ** If an error is found, the analysis is cut short.
  74095. */
  74096. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  74097. struct ExprList_item *pItem;
  74098. int i;
  74099. if( pList ){
  74100. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  74101. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  74102. }
  74103. }
  74104. }
  74105. /*
  74106. ** Allocate a single new register for use to hold some intermediate result.
  74107. */
  74108. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  74109. if( pParse->nTempReg==0 ){
  74110. return ++pParse->nMem;
  74111. }
  74112. return pParse->aTempReg[--pParse->nTempReg];
  74113. }
  74114. /*
  74115. ** Deallocate a register, making available for reuse for some other
  74116. ** purpose.
  74117. **
  74118. ** If a register is currently being used by the column cache, then
  74119. ** the dallocation is deferred until the column cache line that uses
  74120. ** the register becomes stale.
  74121. */
  74122. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  74123. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  74124. int i;
  74125. struct yColCache *p;
  74126. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  74127. if( p->iReg==iReg ){
  74128. p->tempReg = 1;
  74129. return;
  74130. }
  74131. }
  74132. pParse->aTempReg[pParse->nTempReg++] = iReg;
  74133. }
  74134. }
  74135. /*
  74136. ** Allocate or deallocate a block of nReg consecutive registers
  74137. */
  74138. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  74139. int i, n;
  74140. i = pParse->iRangeReg;
  74141. n = pParse->nRangeReg;
  74142. if( nReg<=n ){
  74143. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  74144. pParse->iRangeReg += nReg;
  74145. pParse->nRangeReg -= nReg;
  74146. }else{
  74147. i = pParse->nMem+1;
  74148. pParse->nMem += nReg;
  74149. }
  74150. return i;
  74151. }
  74152. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  74153. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  74154. if( nReg>pParse->nRangeReg ){
  74155. pParse->nRangeReg = nReg;
  74156. pParse->iRangeReg = iReg;
  74157. }
  74158. }
  74159. /*
  74160. ** Mark all temporary registers as being unavailable for reuse.
  74161. */
  74162. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  74163. pParse->nTempReg = 0;
  74164. pParse->nRangeReg = 0;
  74165. }
  74166. /************** End of expr.c ************************************************/
  74167. /************** Begin file alter.c *******************************************/
  74168. /*
  74169. ** 2005 February 15
  74170. **
  74171. ** The author disclaims copyright to this source code. In place of
  74172. ** a legal notice, here is a blessing:
  74173. **
  74174. ** May you do good and not evil.
  74175. ** May you find forgiveness for yourself and forgive others.
  74176. ** May you share freely, never taking more than you give.
  74177. **
  74178. *************************************************************************
  74179. ** This file contains C code routines that used to generate VDBE code
  74180. ** that implements the ALTER TABLE command.
  74181. */
  74182. /*
  74183. ** The code in this file only exists if we are not omitting the
  74184. ** ALTER TABLE logic from the build.
  74185. */
  74186. #ifndef SQLITE_OMIT_ALTERTABLE
  74187. /*
  74188. ** This function is used by SQL generated to implement the
  74189. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  74190. ** CREATE INDEX command. The second is a table name. The table name in
  74191. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  74192. ** argument and the result returned. Examples:
  74193. **
  74194. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  74195. ** -> 'CREATE TABLE def(a, b, c)'
  74196. **
  74197. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  74198. ** -> 'CREATE INDEX i ON def(a, b, c)'
  74199. */
  74200. static void renameTableFunc(
  74201. sqlite3_context *context,
  74202. int NotUsed,
  74203. sqlite3_value **argv
  74204. ){
  74205. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  74206. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  74207. int token;
  74208. Token tname;
  74209. unsigned char const *zCsr = zSql;
  74210. int len = 0;
  74211. char *zRet;
  74212. sqlite3 *db = sqlite3_context_db_handle(context);
  74213. UNUSED_PARAMETER(NotUsed);
  74214. /* The principle used to locate the table name in the CREATE TABLE
  74215. ** statement is that the table name is the first non-space token that
  74216. ** is immediately followed by a TK_LP or TK_USING token.
  74217. */
  74218. if( zSql ){
  74219. do {
  74220. if( !*zCsr ){
  74221. /* Ran out of input before finding an opening bracket. Return NULL. */
  74222. return;
  74223. }
  74224. /* Store the token that zCsr points to in tname. */
  74225. tname.z = (char*)zCsr;
  74226. tname.n = len;
  74227. /* Advance zCsr to the next token. Store that token type in 'token',
  74228. ** and its length in 'len' (to be used next iteration of this loop).
  74229. */
  74230. do {
  74231. zCsr += len;
  74232. len = sqlite3GetToken(zCsr, &token);
  74233. } while( token==TK_SPACE );
  74234. assert( len>0 );
  74235. } while( token!=TK_LP && token!=TK_USING );
  74236. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  74237. zTableName, tname.z+tname.n);
  74238. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  74239. }
  74240. }
  74241. /*
  74242. ** This C function implements an SQL user function that is used by SQL code
  74243. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  74244. ** of any foreign key constraints that use the table being renamed as the
  74245. ** parent table. It is passed three arguments:
  74246. **
  74247. ** 1) The complete text of the CREATE TABLE statement being modified,
  74248. ** 2) The old name of the table being renamed, and
  74249. ** 3) The new name of the table being renamed.
  74250. **
  74251. ** It returns the new CREATE TABLE statement. For example:
  74252. **
  74253. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  74254. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  74255. */
  74256. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74257. static void renameParentFunc(
  74258. sqlite3_context *context,
  74259. int NotUsed,
  74260. sqlite3_value **argv
  74261. ){
  74262. sqlite3 *db = sqlite3_context_db_handle(context);
  74263. char *zOutput = 0;
  74264. char *zResult;
  74265. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  74266. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  74267. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  74268. unsigned const char *z; /* Pointer to token */
  74269. int n; /* Length of token z */
  74270. int token; /* Type of token */
  74271. UNUSED_PARAMETER(NotUsed);
  74272. for(z=zInput; *z; z=z+n){
  74273. n = sqlite3GetToken(z, &token);
  74274. if( token==TK_REFERENCES ){
  74275. char *zParent;
  74276. do {
  74277. z += n;
  74278. n = sqlite3GetToken(z, &token);
  74279. }while( token==TK_SPACE );
  74280. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  74281. if( zParent==0 ) break;
  74282. sqlite3Dequote(zParent);
  74283. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  74284. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  74285. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  74286. );
  74287. sqlite3DbFree(db, zOutput);
  74288. zOutput = zOut;
  74289. zInput = &z[n];
  74290. }
  74291. sqlite3DbFree(db, zParent);
  74292. }
  74293. }
  74294. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  74295. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  74296. sqlite3DbFree(db, zOutput);
  74297. }
  74298. #endif
  74299. #ifndef SQLITE_OMIT_TRIGGER
  74300. /* This function is used by SQL generated to implement the
  74301. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  74302. ** statement. The second is a table name. The table name in the CREATE
  74303. ** TRIGGER statement is replaced with the third argument and the result
  74304. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  74305. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  74306. */
  74307. static void renameTriggerFunc(
  74308. sqlite3_context *context,
  74309. int NotUsed,
  74310. sqlite3_value **argv
  74311. ){
  74312. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  74313. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  74314. int token;
  74315. Token tname;
  74316. int dist = 3;
  74317. unsigned char const *zCsr = zSql;
  74318. int len = 0;
  74319. char *zRet;
  74320. sqlite3 *db = sqlite3_context_db_handle(context);
  74321. UNUSED_PARAMETER(NotUsed);
  74322. /* The principle used to locate the table name in the CREATE TRIGGER
  74323. ** statement is that the table name is the first token that is immediatedly
  74324. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  74325. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  74326. */
  74327. if( zSql ){
  74328. do {
  74329. if( !*zCsr ){
  74330. /* Ran out of input before finding the table name. Return NULL. */
  74331. return;
  74332. }
  74333. /* Store the token that zCsr points to in tname. */
  74334. tname.z = (char*)zCsr;
  74335. tname.n = len;
  74336. /* Advance zCsr to the next token. Store that token type in 'token',
  74337. ** and its length in 'len' (to be used next iteration of this loop).
  74338. */
  74339. do {
  74340. zCsr += len;
  74341. len = sqlite3GetToken(zCsr, &token);
  74342. }while( token==TK_SPACE );
  74343. assert( len>0 );
  74344. /* Variable 'dist' stores the number of tokens read since the most
  74345. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  74346. ** token is read and 'dist' equals 2, the condition stated above
  74347. ** to be met.
  74348. **
  74349. ** Note that ON cannot be a database, table or column name, so
  74350. ** there is no need to worry about syntax like
  74351. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  74352. */
  74353. dist++;
  74354. if( token==TK_DOT || token==TK_ON ){
  74355. dist = 0;
  74356. }
  74357. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  74358. /* Variable tname now contains the token that is the old table-name
  74359. ** in the CREATE TRIGGER statement.
  74360. */
  74361. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  74362. zTableName, tname.z+tname.n);
  74363. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  74364. }
  74365. }
  74366. #endif /* !SQLITE_OMIT_TRIGGER */
  74367. /*
  74368. ** Register built-in functions used to help implement ALTER TABLE
  74369. */
  74370. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  74371. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  74372. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  74373. #ifndef SQLITE_OMIT_TRIGGER
  74374. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  74375. #endif
  74376. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74377. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  74378. #endif
  74379. };
  74380. int i;
  74381. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  74382. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  74383. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  74384. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  74385. }
  74386. }
  74387. /*
  74388. ** This function is used to create the text of expressions of the form:
  74389. **
  74390. ** name=<constant1> OR name=<constant2> OR ...
  74391. **
  74392. ** If argument zWhere is NULL, then a pointer string containing the text
  74393. ** "name=<constant>" is returned, where <constant> is the quoted version
  74394. ** of the string passed as argument zConstant. The returned buffer is
  74395. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  74396. ** caller to ensure that it is eventually freed.
  74397. **
  74398. ** If argument zWhere is not NULL, then the string returned is
  74399. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  74400. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  74401. **
  74402. */
  74403. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  74404. char *zNew;
  74405. if( !zWhere ){
  74406. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  74407. }else{
  74408. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  74409. sqlite3DbFree(db, zWhere);
  74410. }
  74411. return zNew;
  74412. }
  74413. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  74414. /*
  74415. ** Generate the text of a WHERE expression which can be used to select all
  74416. ** tables that have foreign key constraints that refer to table pTab (i.e.
  74417. ** constraints for which pTab is the parent table) from the sqlite_master
  74418. ** table.
  74419. */
  74420. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  74421. FKey *p;
  74422. char *zWhere = 0;
  74423. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  74424. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  74425. }
  74426. return zWhere;
  74427. }
  74428. #endif
  74429. /*
  74430. ** Generate the text of a WHERE expression which can be used to select all
  74431. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  74432. ** table pTab has no temporary triggers, or is itself stored in the
  74433. ** temporary database, NULL is returned.
  74434. */
  74435. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  74436. Trigger *pTrig;
  74437. char *zWhere = 0;
  74438. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  74439. /* If the table is not located in the temp-db (in which case NULL is
  74440. ** returned, loop through the tables list of triggers. For each trigger
  74441. ** that is not part of the temp-db schema, add a clause to the WHERE
  74442. ** expression being built up in zWhere.
  74443. */
  74444. if( pTab->pSchema!=pTempSchema ){
  74445. sqlite3 *db = pParse->db;
  74446. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  74447. if( pTrig->pSchema==pTempSchema ){
  74448. zWhere = whereOrName(db, zWhere, pTrig->zName);
  74449. }
  74450. }
  74451. }
  74452. if( zWhere ){
  74453. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  74454. sqlite3DbFree(pParse->db, zWhere);
  74455. zWhere = zNew;
  74456. }
  74457. return zWhere;
  74458. }
  74459. /*
  74460. ** Generate code to drop and reload the internal representation of table
  74461. ** pTab from the database, including triggers and temporary triggers.
  74462. ** Argument zName is the name of the table in the database schema at
  74463. ** the time the generated code is executed. This can be different from
  74464. ** pTab->zName if this function is being called to code part of an
  74465. ** "ALTER TABLE RENAME TO" statement.
  74466. */
  74467. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  74468. Vdbe *v;
  74469. char *zWhere;
  74470. int iDb; /* Index of database containing pTab */
  74471. #ifndef SQLITE_OMIT_TRIGGER
  74472. Trigger *pTrig;
  74473. #endif
  74474. v = sqlite3GetVdbe(pParse);
  74475. if( NEVER(v==0) ) return;
  74476. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  74477. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  74478. assert( iDb>=0 );
  74479. #ifndef SQLITE_OMIT_TRIGGER
  74480. /* Drop any table triggers from the internal schema. */
  74481. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  74482. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  74483. assert( iTrigDb==iDb || iTrigDb==1 );
  74484. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  74485. }
  74486. #endif
  74487. /* Drop the table and index from the internal schema. */
  74488. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  74489. /* Reload the table, index and permanent trigger schemas. */
  74490. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  74491. if( !zWhere ) return;
  74492. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  74493. #ifndef SQLITE_OMIT_TRIGGER
  74494. /* Now, if the table is not stored in the temp database, reload any temp
  74495. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  74496. */
  74497. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  74498. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  74499. }
  74500. #endif
  74501. }
  74502. /*
  74503. ** Parameter zName is the name of a table that is about to be altered
  74504. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  74505. ** If the table is a system table, this function leaves an error message
  74506. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  74507. **
  74508. ** Or, if zName is not a system table, zero is returned.
  74509. */
  74510. static int isSystemTable(Parse *pParse, const char *zName){
  74511. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  74512. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  74513. return 1;
  74514. }
  74515. return 0;
  74516. }
  74517. /*
  74518. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  74519. ** command.
  74520. */
  74521. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  74522. Parse *pParse, /* Parser context. */
  74523. SrcList *pSrc, /* The table to rename. */
  74524. Token *pName /* The new table name. */
  74525. ){
  74526. int iDb; /* Database that contains the table */
  74527. char *zDb; /* Name of database iDb */
  74528. Table *pTab; /* Table being renamed */
  74529. char *zName = 0; /* NULL-terminated version of pName */
  74530. sqlite3 *db = pParse->db; /* Database connection */
  74531. int nTabName; /* Number of UTF-8 characters in zTabName */
  74532. const char *zTabName; /* Original name of the table */
  74533. Vdbe *v;
  74534. #ifndef SQLITE_OMIT_TRIGGER
  74535. char *zWhere = 0; /* Where clause to locate temp triggers */
  74536. #endif
  74537. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  74538. int savedDbFlags; /* Saved value of db->flags */
  74539. savedDbFlags = db->flags;
  74540. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  74541. assert( pSrc->nSrc==1 );
  74542. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  74543. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  74544. if( !pTab ) goto exit_rename_table;
  74545. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  74546. zDb = db->aDb[iDb].zName;
  74547. db->flags |= SQLITE_PreferBuiltin;
  74548. /* Get a NULL terminated version of the new table name. */
  74549. zName = sqlite3NameFromToken(db, pName);
  74550. if( !zName ) goto exit_rename_table;
  74551. /* Check that a table or index named 'zName' does not already exist
  74552. ** in database iDb. If so, this is an error.
  74553. */
  74554. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  74555. sqlite3ErrorMsg(pParse,
  74556. "there is already another table or index with this name: %s", zName);
  74557. goto exit_rename_table;
  74558. }
  74559. /* Make sure it is not a system table being altered, or a reserved name
  74560. ** that the table is being renamed to.
  74561. */
  74562. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  74563. goto exit_rename_table;
  74564. }
  74565. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  74566. exit_rename_table;
  74567. }
  74568. #ifndef SQLITE_OMIT_VIEW
  74569. if( pTab->pSelect ){
  74570. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  74571. goto exit_rename_table;
  74572. }
  74573. #endif
  74574. #ifndef SQLITE_OMIT_AUTHORIZATION
  74575. /* Invoke the authorization callback. */
  74576. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  74577. goto exit_rename_table;
  74578. }
  74579. #endif
  74580. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74581. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  74582. goto exit_rename_table;
  74583. }
  74584. if( IsVirtual(pTab) ){
  74585. pVTab = sqlite3GetVTable(db, pTab);
  74586. if( pVTab->pVtab->pModule->xRename==0 ){
  74587. pVTab = 0;
  74588. }
  74589. }
  74590. #endif
  74591. /* Begin a transaction and code the VerifyCookie for database iDb.
  74592. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  74593. ** schema). Open a statement transaction if the table is a virtual
  74594. ** table.
  74595. */
  74596. v = sqlite3GetVdbe(pParse);
  74597. if( v==0 ){
  74598. goto exit_rename_table;
  74599. }
  74600. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  74601. sqlite3ChangeCookie(pParse, iDb);
  74602. /* If this is a virtual table, invoke the xRename() function if
  74603. ** one is defined. The xRename() callback will modify the names
  74604. ** of any resources used by the v-table implementation (including other
  74605. ** SQLite tables) that are identified by the name of the virtual table.
  74606. */
  74607. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74608. if( pVTab ){
  74609. int i = ++pParse->nMem;
  74610. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  74611. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  74612. sqlite3MayAbort(pParse);
  74613. }
  74614. #endif
  74615. /* figure out how many UTF-8 characters are in zName */
  74616. zTabName = pTab->zName;
  74617. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  74618. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  74619. if( db->flags&SQLITE_ForeignKeys ){
  74620. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  74621. ** statements corresponding to all child tables of foreign key constraints
  74622. ** for which the renamed table is the parent table. */
  74623. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  74624. sqlite3NestedParse(pParse,
  74625. "UPDATE \"%w\".%s SET "
  74626. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  74627. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  74628. sqlite3DbFree(db, zWhere);
  74629. }
  74630. }
  74631. #endif
  74632. /* Modify the sqlite_master table to use the new table name. */
  74633. sqlite3NestedParse(pParse,
  74634. "UPDATE %Q.%s SET "
  74635. #ifdef SQLITE_OMIT_TRIGGER
  74636. "sql = sqlite_rename_table(sql, %Q), "
  74637. #else
  74638. "sql = CASE "
  74639. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  74640. "ELSE sqlite_rename_table(sql, %Q) END, "
  74641. #endif
  74642. "tbl_name = %Q, "
  74643. "name = CASE "
  74644. "WHEN type='table' THEN %Q "
  74645. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  74646. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  74647. "ELSE name END "
  74648. "WHERE tbl_name=%Q COLLATE nocase AND "
  74649. "(type='table' OR type='index' OR type='trigger');",
  74650. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  74651. #ifndef SQLITE_OMIT_TRIGGER
  74652. zName,
  74653. #endif
  74654. zName, nTabName, zTabName
  74655. );
  74656. #ifndef SQLITE_OMIT_AUTOINCREMENT
  74657. /* If the sqlite_sequence table exists in this database, then update
  74658. ** it with the new table name.
  74659. */
  74660. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  74661. sqlite3NestedParse(pParse,
  74662. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  74663. zDb, zName, pTab->zName);
  74664. }
  74665. #endif
  74666. #ifndef SQLITE_OMIT_TRIGGER
  74667. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  74668. ** table. Don't do this if the table being ALTERed is itself located in
  74669. ** the temp database.
  74670. */
  74671. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  74672. sqlite3NestedParse(pParse,
  74673. "UPDATE sqlite_temp_master SET "
  74674. "sql = sqlite_rename_trigger(sql, %Q), "
  74675. "tbl_name = %Q "
  74676. "WHERE %s;", zName, zName, zWhere);
  74677. sqlite3DbFree(db, zWhere);
  74678. }
  74679. #endif
  74680. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  74681. if( db->flags&SQLITE_ForeignKeys ){
  74682. FKey *p;
  74683. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  74684. Table *pFrom = p->pFrom;
  74685. if( pFrom!=pTab ){
  74686. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  74687. }
  74688. }
  74689. }
  74690. #endif
  74691. /* Drop and reload the internal table schema. */
  74692. reloadTableSchema(pParse, pTab, zName);
  74693. exit_rename_table:
  74694. sqlite3SrcListDelete(db, pSrc);
  74695. sqlite3DbFree(db, zName);
  74696. db->flags = savedDbFlags;
  74697. }
  74698. /*
  74699. ** Generate code to make sure the file format number is at least minFormat.
  74700. ** The generated code will increase the file format number if necessary.
  74701. */
  74702. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  74703. Vdbe *v;
  74704. v = sqlite3GetVdbe(pParse);
  74705. /* The VDBE should have been allocated before this routine is called.
  74706. ** If that allocation failed, we would have quit before reaching this
  74707. ** point */
  74708. if( ALWAYS(v) ){
  74709. int r1 = sqlite3GetTempReg(pParse);
  74710. int r2 = sqlite3GetTempReg(pParse);
  74711. int j1;
  74712. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  74713. sqlite3VdbeUsesBtree(v, iDb);
  74714. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  74715. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  74716. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  74717. sqlite3VdbeJumpHere(v, j1);
  74718. sqlite3ReleaseTempReg(pParse, r1);
  74719. sqlite3ReleaseTempReg(pParse, r2);
  74720. }
  74721. }
  74722. /*
  74723. ** This function is called after an "ALTER TABLE ... ADD" statement
  74724. ** has been parsed. Argument pColDef contains the text of the new
  74725. ** column definition.
  74726. **
  74727. ** The Table structure pParse->pNewTable was extended to include
  74728. ** the new column during parsing.
  74729. */
  74730. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  74731. Table *pNew; /* Copy of pParse->pNewTable */
  74732. Table *pTab; /* Table being altered */
  74733. int iDb; /* Database number */
  74734. const char *zDb; /* Database name */
  74735. const char *zTab; /* Table name */
  74736. char *zCol; /* Null-terminated column definition */
  74737. Column *pCol; /* The new column */
  74738. Expr *pDflt; /* Default value for the new column */
  74739. sqlite3 *db; /* The database connection; */
  74740. db = pParse->db;
  74741. if( pParse->nErr || db->mallocFailed ) return;
  74742. pNew = pParse->pNewTable;
  74743. assert( pNew );
  74744. assert( sqlite3BtreeHoldsAllMutexes(db) );
  74745. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  74746. zDb = db->aDb[iDb].zName;
  74747. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  74748. pCol = &pNew->aCol[pNew->nCol-1];
  74749. pDflt = pCol->pDflt;
  74750. pTab = sqlite3FindTable(db, zTab, zDb);
  74751. assert( pTab );
  74752. #ifndef SQLITE_OMIT_AUTHORIZATION
  74753. /* Invoke the authorization callback. */
  74754. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  74755. return;
  74756. }
  74757. #endif
  74758. /* If the default value for the new column was specified with a
  74759. ** literal NULL, then set pDflt to 0. This simplifies checking
  74760. ** for an SQL NULL default below.
  74761. */
  74762. if( pDflt && pDflt->op==TK_NULL ){
  74763. pDflt = 0;
  74764. }
  74765. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  74766. ** If there is a NOT NULL constraint, then the default value for the
  74767. ** column must not be NULL.
  74768. */
  74769. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  74770. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  74771. return;
  74772. }
  74773. if( pNew->pIndex ){
  74774. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  74775. return;
  74776. }
  74777. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  74778. sqlite3ErrorMsg(pParse,
  74779. "Cannot add a REFERENCES column with non-NULL default value");
  74780. return;
  74781. }
  74782. if( pCol->notNull && !pDflt ){
  74783. sqlite3ErrorMsg(pParse,
  74784. "Cannot add a NOT NULL column with default value NULL");
  74785. return;
  74786. }
  74787. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  74788. ** can handle (i.e. not CURRENT_TIME etc.)
  74789. */
  74790. if( pDflt ){
  74791. sqlite3_value *pVal;
  74792. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  74793. db->mallocFailed = 1;
  74794. return;
  74795. }
  74796. if( !pVal ){
  74797. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  74798. return;
  74799. }
  74800. sqlite3ValueFree(pVal);
  74801. }
  74802. /* Modify the CREATE TABLE statement. */
  74803. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  74804. if( zCol ){
  74805. char *zEnd = &zCol[pColDef->n-1];
  74806. int savedDbFlags = db->flags;
  74807. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  74808. *zEnd-- = '\0';
  74809. }
  74810. db->flags |= SQLITE_PreferBuiltin;
  74811. sqlite3NestedParse(pParse,
  74812. "UPDATE \"%w\".%s SET "
  74813. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  74814. "WHERE type = 'table' AND name = %Q",
  74815. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  74816. zTab
  74817. );
  74818. sqlite3DbFree(db, zCol);
  74819. db->flags = savedDbFlags;
  74820. }
  74821. /* If the default value of the new column is NULL, then set the file
  74822. ** format to 2. If the default value of the new column is not NULL,
  74823. ** the file format becomes 3.
  74824. */
  74825. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  74826. /* Reload the schema of the modified table. */
  74827. reloadTableSchema(pParse, pTab, pTab->zName);
  74828. }
  74829. /*
  74830. ** This function is called by the parser after the table-name in
  74831. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  74832. ** pSrc is the full-name of the table being altered.
  74833. **
  74834. ** This routine makes a (partial) copy of the Table structure
  74835. ** for the table being altered and sets Parse.pNewTable to point
  74836. ** to it. Routines called by the parser as the column definition
  74837. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  74838. ** the copy. The copy of the Table structure is deleted by tokenize.c
  74839. ** after parsing is finished.
  74840. **
  74841. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  74842. ** coding the "ALTER TABLE ... ADD" statement.
  74843. */
  74844. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  74845. Table *pNew;
  74846. Table *pTab;
  74847. Vdbe *v;
  74848. int iDb;
  74849. int i;
  74850. int nAlloc;
  74851. sqlite3 *db = pParse->db;
  74852. /* Look up the table being altered. */
  74853. assert( pParse->pNewTable==0 );
  74854. assert( sqlite3BtreeHoldsAllMutexes(db) );
  74855. if( db->mallocFailed ) goto exit_begin_add_column;
  74856. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  74857. if( !pTab ) goto exit_begin_add_column;
  74858. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74859. if( IsVirtual(pTab) ){
  74860. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  74861. goto exit_begin_add_column;
  74862. }
  74863. #endif
  74864. /* Make sure this is not an attempt to ALTER a view. */
  74865. if( pTab->pSelect ){
  74866. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  74867. goto exit_begin_add_column;
  74868. }
  74869. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  74870. goto exit_begin_add_column;
  74871. }
  74872. assert( pTab->addColOffset>0 );
  74873. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  74874. /* Put a copy of the Table struct in Parse.pNewTable for the
  74875. ** sqlite3AddColumn() function and friends to modify. But modify
  74876. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  74877. ** prefix, we insure that the name will not collide with an existing
  74878. ** table because user table are not allowed to have the "sqlite_"
  74879. ** prefix on their name.
  74880. */
  74881. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  74882. if( !pNew ) goto exit_begin_add_column;
  74883. pParse->pNewTable = pNew;
  74884. pNew->nRef = 1;
  74885. pNew->nCol = pTab->nCol;
  74886. assert( pNew->nCol>0 );
  74887. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  74888. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  74889. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  74890. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  74891. if( !pNew->aCol || !pNew->zName ){
  74892. db->mallocFailed = 1;
  74893. goto exit_begin_add_column;
  74894. }
  74895. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  74896. for(i=0; i<pNew->nCol; i++){
  74897. Column *pCol = &pNew->aCol[i];
  74898. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  74899. pCol->zColl = 0;
  74900. pCol->zType = 0;
  74901. pCol->pDflt = 0;
  74902. pCol->zDflt = 0;
  74903. }
  74904. pNew->pSchema = db->aDb[iDb].pSchema;
  74905. pNew->addColOffset = pTab->addColOffset;
  74906. pNew->nRef = 1;
  74907. /* Begin a transaction and increment the schema cookie. */
  74908. sqlite3BeginWriteOperation(pParse, 0, iDb);
  74909. v = sqlite3GetVdbe(pParse);
  74910. if( !v ) goto exit_begin_add_column;
  74911. sqlite3ChangeCookie(pParse, iDb);
  74912. exit_begin_add_column:
  74913. sqlite3SrcListDelete(db, pSrc);
  74914. return;
  74915. }
  74916. #endif /* SQLITE_ALTER_TABLE */
  74917. /************** End of alter.c ***********************************************/
  74918. /************** Begin file analyze.c *****************************************/
  74919. /*
  74920. ** 2005 July 8
  74921. **
  74922. ** The author disclaims copyright to this source code. In place of
  74923. ** a legal notice, here is a blessing:
  74924. **
  74925. ** May you do good and not evil.
  74926. ** May you find forgiveness for yourself and forgive others.
  74927. ** May you share freely, never taking more than you give.
  74928. **
  74929. *************************************************************************
  74930. ** This file contains code associated with the ANALYZE command.
  74931. **
  74932. ** The ANALYZE command gather statistics about the content of tables
  74933. ** and indices. These statistics are made available to the query planner
  74934. ** to help it make better decisions about how to perform queries.
  74935. **
  74936. ** The following system tables are or have been supported:
  74937. **
  74938. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  74939. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  74940. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  74941. **
  74942. ** Additional tables might be added in future releases of SQLite.
  74943. ** The sqlite_stat2 table is not created or used unless the SQLite version
  74944. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  74945. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  74946. ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
  74947. ** created and used by SQLite versions 3.7.9 and later and with
  74948. ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
  74949. ** is a superset of sqlite_stat2.
  74950. **
  74951. ** Format of sqlite_stat1:
  74952. **
  74953. ** There is normally one row per index, with the index identified by the
  74954. ** name in the idx column. The tbl column is the name of the table to
  74955. ** which the index belongs. In each such row, the stat column will be
  74956. ** a string consisting of a list of integers. The first integer in this
  74957. ** list is the number of rows in the index and in the table. The second
  74958. ** integer is the average number of rows in the index that have the same
  74959. ** value in the first column of the index. The third integer is the average
  74960. ** number of rows in the index that have the same value for the first two
  74961. ** columns. The N-th integer (for N>1) is the average number of rows in
  74962. ** the index which have the same value for the first N-1 columns. For
  74963. ** a K-column index, there will be K+1 integers in the stat column. If
  74964. ** the index is unique, then the last integer will be 1.
  74965. **
  74966. ** The list of integers in the stat column can optionally be followed
  74967. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  74968. ** must be separated from the last integer by a single space. If the
  74969. ** "unordered" keyword is present, then the query planner assumes that
  74970. ** the index is unordered and will not use the index for a range query.
  74971. **
  74972. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  74973. ** column contains a single integer which is the (estimated) number of
  74974. ** rows in the table identified by sqlite_stat1.tbl.
  74975. **
  74976. ** Format of sqlite_stat2:
  74977. **
  74978. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  74979. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  74980. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  74981. ** about the distribution of keys within an index. The index is identified by
  74982. ** the "idx" column and the "tbl" column is the name of the table to which
  74983. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  74984. ** table for each index.
  74985. **
  74986. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  74987. ** inclusive are samples of the left-most key value in the index taken at
  74988. ** evenly spaced points along the index. Let the number of samples be S
  74989. ** (10 in the standard build) and let C be the number of rows in the index.
  74990. ** Then the sampled rows are given by:
  74991. **
  74992. ** rownumber = (i*C*2 + C)/(S*2)
  74993. **
  74994. ** For i between 0 and S-1. Conceptually, the index space is divided into
  74995. ** S uniform buckets and the samples are the middle row from each bucket.
  74996. **
  74997. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  74998. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  74999. ** writes the sqlite_stat2 table. This version of SQLite only supports
  75000. ** sqlite_stat3.
  75001. **
  75002. ** Format for sqlite_stat3:
  75003. **
  75004. ** The sqlite_stat3 is an enhancement to sqlite_stat2. A new name is
  75005. ** used to avoid compatibility problems.
  75006. **
  75007. ** The format of the sqlite_stat3 table is similar to the format of
  75008. ** the sqlite_stat2 table. There are multiple entries for each index.
  75009. ** The idx column names the index and the tbl column is the table of the
  75010. ** index. If the idx and tbl columns are the same, then the sample is
  75011. ** of the INTEGER PRIMARY KEY. The sample column is a value taken from
  75012. ** the left-most column of the index. The nEq column is the approximate
  75013. ** number of entires in the index whose left-most column exactly matches
  75014. ** the sample. nLt is the approximate number of entires whose left-most
  75015. ** column is less than the sample. The nDLt column is the approximate
  75016. ** number of distinct left-most entries in the index that are less than
  75017. ** the sample.
  75018. **
  75019. ** Future versions of SQLite might change to store a string containing
  75020. ** multiple integers values in the nDLt column of sqlite_stat3. The first
  75021. ** integer will be the number of prior index entires that are distinct in
  75022. ** the left-most column. The second integer will be the number of prior index
  75023. ** entries that are distinct in the first two columns. The third integer
  75024. ** will be the number of prior index entries that are distinct in the first
  75025. ** three columns. And so forth. With that extension, the nDLt field is
  75026. ** similar in function to the sqlite_stat1.stat field.
  75027. **
  75028. ** There can be an arbitrary number of sqlite_stat3 entries per index.
  75029. ** The ANALYZE command will typically generate sqlite_stat3 tables
  75030. ** that contain between 10 and 40 samples which are distributed across
  75031. ** the key space, though not uniformly, and which include samples with
  75032. ** largest possible nEq values.
  75033. */
  75034. #ifndef SQLITE_OMIT_ANALYZE
  75035. /*
  75036. ** This routine generates code that opens the sqlite_stat1 table for
  75037. ** writing with cursor iStatCur. If the library was built with the
  75038. ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
  75039. ** opened for writing using cursor (iStatCur+1)
  75040. **
  75041. ** If the sqlite_stat1 tables does not previously exist, it is created.
  75042. ** Similarly, if the sqlite_stat3 table does not exist and the library
  75043. ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
  75044. **
  75045. ** Argument zWhere may be a pointer to a buffer containing a table name,
  75046. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  75047. ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
  75048. ** with the named table are deleted. If zWhere==0, then code is generated
  75049. ** to delete all stat table entries.
  75050. */
  75051. static void openStatTable(
  75052. Parse *pParse, /* Parsing context */
  75053. int iDb, /* The database we are looking in */
  75054. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  75055. const char *zWhere, /* Delete entries for this table or index */
  75056. const char *zWhereType /* Either "tbl" or "idx" */
  75057. ){
  75058. static const struct {
  75059. const char *zName;
  75060. const char *zCols;
  75061. } aTable[] = {
  75062. { "sqlite_stat1", "tbl,idx,stat" },
  75063. #ifdef SQLITE_ENABLE_STAT3
  75064. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  75065. #endif
  75066. };
  75067. int aRoot[] = {0, 0};
  75068. u8 aCreateTbl[] = {0, 0};
  75069. int i;
  75070. sqlite3 *db = pParse->db;
  75071. Db *pDb;
  75072. Vdbe *v = sqlite3GetVdbe(pParse);
  75073. if( v==0 ) return;
  75074. assert( sqlite3BtreeHoldsAllMutexes(db) );
  75075. assert( sqlite3VdbeDb(v)==db );
  75076. pDb = &db->aDb[iDb];
  75077. /* Create new statistic tables if they do not exist, or clear them
  75078. ** if they do already exist.
  75079. */
  75080. for(i=0; i<ArraySize(aTable); i++){
  75081. const char *zTab = aTable[i].zName;
  75082. Table *pStat;
  75083. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  75084. /* The sqlite_stat[12] table does not exist. Create it. Note that a
  75085. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  75086. ** of the new table in register pParse->regRoot. This is important
  75087. ** because the OpenWrite opcode below will be needing it. */
  75088. sqlite3NestedParse(pParse,
  75089. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  75090. );
  75091. aRoot[i] = pParse->regRoot;
  75092. aCreateTbl[i] = OPFLAG_P2ISREG;
  75093. }else{
  75094. /* The table already exists. If zWhere is not NULL, delete all entries
  75095. ** associated with the table zWhere. If zWhere is NULL, delete the
  75096. ** entire contents of the table. */
  75097. aRoot[i] = pStat->tnum;
  75098. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  75099. if( zWhere ){
  75100. sqlite3NestedParse(pParse,
  75101. "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
  75102. );
  75103. }else{
  75104. /* The sqlite_stat[12] table already exists. Delete all rows. */
  75105. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  75106. }
  75107. }
  75108. }
  75109. /* Open the sqlite_stat[13] tables for writing. */
  75110. for(i=0; i<ArraySize(aTable); i++){
  75111. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  75112. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  75113. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  75114. }
  75115. }
  75116. /*
  75117. ** Recommended number of samples for sqlite_stat3
  75118. */
  75119. #ifndef SQLITE_STAT3_SAMPLES
  75120. # define SQLITE_STAT3_SAMPLES 24
  75121. #endif
  75122. /*
  75123. ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
  75124. ** share an instance of the following structure to hold their state
  75125. ** information.
  75126. */
  75127. typedef struct Stat3Accum Stat3Accum;
  75128. struct Stat3Accum {
  75129. tRowcnt nRow; /* Number of rows in the entire table */
  75130. tRowcnt nPSample; /* How often to do a periodic sample */
  75131. int iMin; /* Index of entry with minimum nEq and hash */
  75132. int mxSample; /* Maximum number of samples to accumulate */
  75133. int nSample; /* Current number of samples */
  75134. u32 iPrn; /* Pseudo-random number used for sampling */
  75135. struct Stat3Sample {
  75136. i64 iRowid; /* Rowid in main table of the key */
  75137. tRowcnt nEq; /* sqlite_stat3.nEq */
  75138. tRowcnt nLt; /* sqlite_stat3.nLt */
  75139. tRowcnt nDLt; /* sqlite_stat3.nDLt */
  75140. u8 isPSample; /* True if a periodic sample */
  75141. u32 iHash; /* Tiebreaker hash */
  75142. } *a; /* An array of samples */
  75143. };
  75144. #ifdef SQLITE_ENABLE_STAT3
  75145. /*
  75146. ** Implementation of the stat3_init(C,S) SQL function. The two parameters
  75147. ** are the number of rows in the table or index (C) and the number of samples
  75148. ** to accumulate (S).
  75149. **
  75150. ** This routine allocates the Stat3Accum object.
  75151. **
  75152. ** The return value is the Stat3Accum object (P).
  75153. */
  75154. static void stat3Init(
  75155. sqlite3_context *context,
  75156. int argc,
  75157. sqlite3_value **argv
  75158. ){
  75159. Stat3Accum *p;
  75160. tRowcnt nRow;
  75161. int mxSample;
  75162. int n;
  75163. UNUSED_PARAMETER(argc);
  75164. nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
  75165. mxSample = sqlite3_value_int(argv[1]);
  75166. n = sizeof(*p) + sizeof(p->a[0])*mxSample;
  75167. p = sqlite3MallocZero( n );
  75168. if( p==0 ){
  75169. sqlite3_result_error_nomem(context);
  75170. return;
  75171. }
  75172. p->a = (struct Stat3Sample*)&p[1];
  75173. p->nRow = nRow;
  75174. p->mxSample = mxSample;
  75175. p->nPSample = p->nRow/(mxSample/3+1) + 1;
  75176. sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
  75177. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  75178. }
  75179. static const FuncDef stat3InitFuncdef = {
  75180. 2, /* nArg */
  75181. SQLITE_UTF8, /* iPrefEnc */
  75182. 0, /* flags */
  75183. 0, /* pUserData */
  75184. 0, /* pNext */
  75185. stat3Init, /* xFunc */
  75186. 0, /* xStep */
  75187. 0, /* xFinalize */
  75188. "stat3_init", /* zName */
  75189. 0, /* pHash */
  75190. 0 /* pDestructor */
  75191. };
  75192. /*
  75193. ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function. The
  75194. ** arguments describe a single key instance. This routine makes the
  75195. ** decision about whether or not to retain this key for the sqlite_stat3
  75196. ** table.
  75197. **
  75198. ** The return value is NULL.
  75199. */
  75200. static void stat3Push(
  75201. sqlite3_context *context,
  75202. int argc,
  75203. sqlite3_value **argv
  75204. ){
  75205. Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
  75206. tRowcnt nEq = sqlite3_value_int64(argv[0]);
  75207. tRowcnt nLt = sqlite3_value_int64(argv[1]);
  75208. tRowcnt nDLt = sqlite3_value_int64(argv[2]);
  75209. i64 rowid = sqlite3_value_int64(argv[3]);
  75210. u8 isPSample = 0;
  75211. u8 doInsert = 0;
  75212. int iMin = p->iMin;
  75213. struct Stat3Sample *pSample;
  75214. int i;
  75215. u32 h;
  75216. UNUSED_PARAMETER(context);
  75217. UNUSED_PARAMETER(argc);
  75218. if( nEq==0 ) return;
  75219. h = p->iPrn = p->iPrn*1103515245 + 12345;
  75220. if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
  75221. doInsert = isPSample = 1;
  75222. }else if( p->nSample<p->mxSample ){
  75223. doInsert = 1;
  75224. }else{
  75225. if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
  75226. doInsert = 1;
  75227. }
  75228. }
  75229. if( !doInsert ) return;
  75230. if( p->nSample==p->mxSample ){
  75231. assert( p->nSample - iMin - 1 >= 0 );
  75232. memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
  75233. pSample = &p->a[p->nSample-1];
  75234. }else{
  75235. pSample = &p->a[p->nSample++];
  75236. }
  75237. pSample->iRowid = rowid;
  75238. pSample->nEq = nEq;
  75239. pSample->nLt = nLt;
  75240. pSample->nDLt = nDLt;
  75241. pSample->iHash = h;
  75242. pSample->isPSample = isPSample;
  75243. /* Find the new minimum */
  75244. if( p->nSample==p->mxSample ){
  75245. pSample = p->a;
  75246. i = 0;
  75247. while( pSample->isPSample ){
  75248. i++;
  75249. pSample++;
  75250. assert( i<p->nSample );
  75251. }
  75252. nEq = pSample->nEq;
  75253. h = pSample->iHash;
  75254. iMin = i;
  75255. for(i++, pSample++; i<p->nSample; i++, pSample++){
  75256. if( pSample->isPSample ) continue;
  75257. if( pSample->nEq<nEq
  75258. || (pSample->nEq==nEq && pSample->iHash<h)
  75259. ){
  75260. iMin = i;
  75261. nEq = pSample->nEq;
  75262. h = pSample->iHash;
  75263. }
  75264. }
  75265. p->iMin = iMin;
  75266. }
  75267. }
  75268. static const FuncDef stat3PushFuncdef = {
  75269. 5, /* nArg */
  75270. SQLITE_UTF8, /* iPrefEnc */
  75271. 0, /* flags */
  75272. 0, /* pUserData */
  75273. 0, /* pNext */
  75274. stat3Push, /* xFunc */
  75275. 0, /* xStep */
  75276. 0, /* xFinalize */
  75277. "stat3_push", /* zName */
  75278. 0, /* pHash */
  75279. 0 /* pDestructor */
  75280. };
  75281. /*
  75282. ** Implementation of the stat3_get(P,N,...) SQL function. This routine is
  75283. ** used to query the results. Content is returned for the Nth sqlite_stat3
  75284. ** row where N is between 0 and S-1 and S is the number of samples. The
  75285. ** value returned depends on the number of arguments.
  75286. **
  75287. ** argc==2 result: rowid
  75288. ** argc==3 result: nEq
  75289. ** argc==4 result: nLt
  75290. ** argc==5 result: nDLt
  75291. */
  75292. static void stat3Get(
  75293. sqlite3_context *context,
  75294. int argc,
  75295. sqlite3_value **argv
  75296. ){
  75297. int n = sqlite3_value_int(argv[1]);
  75298. Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
  75299. assert( p!=0 );
  75300. if( p->nSample<=n ) return;
  75301. switch( argc ){
  75302. case 2: sqlite3_result_int64(context, p->a[n].iRowid); break;
  75303. case 3: sqlite3_result_int64(context, p->a[n].nEq); break;
  75304. case 4: sqlite3_result_int64(context, p->a[n].nLt); break;
  75305. default: sqlite3_result_int64(context, p->a[n].nDLt); break;
  75306. }
  75307. }
  75308. static const FuncDef stat3GetFuncdef = {
  75309. -1, /* nArg */
  75310. SQLITE_UTF8, /* iPrefEnc */
  75311. 0, /* flags */
  75312. 0, /* pUserData */
  75313. 0, /* pNext */
  75314. stat3Get, /* xFunc */
  75315. 0, /* xStep */
  75316. 0, /* xFinalize */
  75317. "stat3_get", /* zName */
  75318. 0, /* pHash */
  75319. 0 /* pDestructor */
  75320. };
  75321. #endif /* SQLITE_ENABLE_STAT3 */
  75322. /*
  75323. ** Generate code to do an analysis of all indices associated with
  75324. ** a single table.
  75325. */
  75326. static void analyzeOneTable(
  75327. Parse *pParse, /* Parser context */
  75328. Table *pTab, /* Table whose indices are to be analyzed */
  75329. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  75330. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  75331. int iMem /* Available memory locations begin here */
  75332. ){
  75333. sqlite3 *db = pParse->db; /* Database handle */
  75334. Index *pIdx; /* An index to being analyzed */
  75335. int iIdxCur; /* Cursor open on index being analyzed */
  75336. Vdbe *v; /* The virtual machine being built up */
  75337. int i; /* Loop counter */
  75338. int topOfLoop; /* The top of the loop */
  75339. int endOfLoop; /* The end of the loop */
  75340. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  75341. int iDb; /* Index of database containing pTab */
  75342. int regTabname = iMem++; /* Register containing table name */
  75343. int regIdxname = iMem++; /* Register containing index name */
  75344. int regStat1 = iMem++; /* The stat column of sqlite_stat1 */
  75345. #ifdef SQLITE_ENABLE_STAT3
  75346. int regNumEq = regStat1; /* Number of instances. Same as regStat1 */
  75347. int regNumLt = iMem++; /* Number of keys less than regSample */
  75348. int regNumDLt = iMem++; /* Number of distinct keys less than regSample */
  75349. int regSample = iMem++; /* The next sample value */
  75350. int regRowid = regSample; /* Rowid of a sample */
  75351. int regAccum = iMem++; /* Register to hold Stat3Accum object */
  75352. int regLoop = iMem++; /* Loop counter */
  75353. int regCount = iMem++; /* Number of rows in the table or index */
  75354. int regTemp1 = iMem++; /* Intermediate register */
  75355. int regTemp2 = iMem++; /* Intermediate register */
  75356. int once = 1; /* One-time initialization */
  75357. int shortJump = 0; /* Instruction address */
  75358. int iTabCur = pParse->nTab++; /* Table cursor */
  75359. #endif
  75360. int regCol = iMem++; /* Content of a column in analyzed table */
  75361. int regRec = iMem++; /* Register holding completed record */
  75362. int regTemp = iMem++; /* Temporary use register */
  75363. int regNewRowid = iMem++; /* Rowid for the inserted record */
  75364. v = sqlite3GetVdbe(pParse);
  75365. if( v==0 || NEVER(pTab==0) ){
  75366. return;
  75367. }
  75368. if( pTab->tnum==0 ){
  75369. /* Do not gather statistics on views or virtual tables */
  75370. return;
  75371. }
  75372. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  75373. /* Do not gather statistics on system tables */
  75374. return;
  75375. }
  75376. assert( sqlite3BtreeHoldsAllMutexes(db) );
  75377. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75378. assert( iDb>=0 );
  75379. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75380. #ifndef SQLITE_OMIT_AUTHORIZATION
  75381. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  75382. db->aDb[iDb].zName ) ){
  75383. return;
  75384. }
  75385. #endif
  75386. /* Establish a read-lock on the table at the shared-cache level. */
  75387. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  75388. iIdxCur = pParse->nTab++;
  75389. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  75390. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  75391. int nCol;
  75392. KeyInfo *pKey;
  75393. int addrIfNot = 0; /* address of OP_IfNot */
  75394. int *aChngAddr; /* Array of jump instruction addresses */
  75395. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  75396. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  75397. nCol = pIdx->nColumn;
  75398. aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
  75399. if( aChngAddr==0 ) continue;
  75400. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  75401. if( iMem+1+(nCol*2)>pParse->nMem ){
  75402. pParse->nMem = iMem+1+(nCol*2);
  75403. }
  75404. /* Open a cursor to the index to be analyzed. */
  75405. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  75406. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
  75407. (char *)pKey, P4_KEYINFO_HANDOFF);
  75408. VdbeComment((v, "%s", pIdx->zName));
  75409. /* Populate the register containing the index name. */
  75410. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  75411. #ifdef SQLITE_ENABLE_STAT3
  75412. if( once ){
  75413. once = 0;
  75414. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  75415. }
  75416. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
  75417. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
  75418. sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
  75419. sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
  75420. sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
  75421. sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
  75422. sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
  75423. (char*)&stat3InitFuncdef, P4_FUNCDEF);
  75424. sqlite3VdbeChangeP5(v, 2);
  75425. #endif /* SQLITE_ENABLE_STAT3 */
  75426. /* The block of memory cells initialized here is used as follows.
  75427. **
  75428. ** iMem:
  75429. ** The total number of rows in the table.
  75430. **
  75431. ** iMem+1 .. iMem+nCol:
  75432. ** Number of distinct entries in index considering the
  75433. ** left-most N columns only, where N is between 1 and nCol,
  75434. ** inclusive.
  75435. **
  75436. ** iMem+nCol+1 .. Mem+2*nCol:
  75437. ** Previous value of indexed columns, from left to right.
  75438. **
  75439. ** Cells iMem through iMem+nCol are initialized to 0. The others are
  75440. ** initialized to contain an SQL NULL.
  75441. */
  75442. for(i=0; i<=nCol; i++){
  75443. sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
  75444. }
  75445. for(i=0; i<nCol; i++){
  75446. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
  75447. }
  75448. /* Start the analysis loop. This loop runs through all the entries in
  75449. ** the index b-tree. */
  75450. endOfLoop = sqlite3VdbeMakeLabel(v);
  75451. sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
  75452. topOfLoop = sqlite3VdbeCurrentAddr(v);
  75453. sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1); /* Increment row counter */
  75454. for(i=0; i<nCol; i++){
  75455. CollSeq *pColl;
  75456. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
  75457. if( i==0 ){
  75458. /* Always record the very first row */
  75459. addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
  75460. }
  75461. assert( pIdx->azColl!=0 );
  75462. assert( pIdx->azColl[i]!=0 );
  75463. pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  75464. aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
  75465. (char*)pColl, P4_COLLSEQ);
  75466. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  75467. VdbeComment((v, "jump if column %d changed", i));
  75468. #ifdef SQLITE_ENABLE_STAT3
  75469. if( i==0 ){
  75470. sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
  75471. VdbeComment((v, "incr repeat count"));
  75472. }
  75473. #endif
  75474. }
  75475. sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
  75476. for(i=0; i<nCol; i++){
  75477. sqlite3VdbeJumpHere(v, aChngAddr[i]); /* Set jump dest for the OP_Ne */
  75478. if( i==0 ){
  75479. sqlite3VdbeJumpHere(v, addrIfNot); /* Jump dest for OP_IfNot */
  75480. #ifdef SQLITE_ENABLE_STAT3
  75481. sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
  75482. (char*)&stat3PushFuncdef, P4_FUNCDEF);
  75483. sqlite3VdbeChangeP5(v, 5);
  75484. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
  75485. sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
  75486. sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
  75487. sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
  75488. #endif
  75489. }
  75490. sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
  75491. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
  75492. }
  75493. sqlite3DbFree(db, aChngAddr);
  75494. /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
  75495. sqlite3VdbeResolveLabel(v, endOfLoop);
  75496. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
  75497. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  75498. #ifdef SQLITE_ENABLE_STAT3
  75499. sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
  75500. (char*)&stat3PushFuncdef, P4_FUNCDEF);
  75501. sqlite3VdbeChangeP5(v, 5);
  75502. sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
  75503. shortJump =
  75504. sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
  75505. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
  75506. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  75507. sqlite3VdbeChangeP5(v, 2);
  75508. sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
  75509. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
  75510. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
  75511. sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
  75512. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
  75513. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  75514. sqlite3VdbeChangeP5(v, 3);
  75515. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
  75516. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  75517. sqlite3VdbeChangeP5(v, 4);
  75518. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
  75519. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  75520. sqlite3VdbeChangeP5(v, 5);
  75521. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
  75522. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  75523. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
  75524. sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
  75525. sqlite3VdbeJumpHere(v, shortJump+2);
  75526. #endif
  75527. /* Store the results in sqlite_stat1.
  75528. **
  75529. ** The result is a single row of the sqlite_stat1 table. The first
  75530. ** two columns are the names of the table and index. The third column
  75531. ** is a string composed of a list of integer statistics about the
  75532. ** index. The first integer in the list is the total number of entries
  75533. ** in the index. There is one additional integer in the list for each
  75534. ** column of the table. This additional integer is a guess of how many
  75535. ** rows of the table the index will select. If D is the count of distinct
  75536. ** values and K is the total number of rows, then the integer is computed
  75537. ** as:
  75538. **
  75539. ** I = (K+D-1)/D
  75540. **
  75541. ** If K==0 then no entry is made into the sqlite_stat1 table.
  75542. ** If K>0 then it is always the case the D>0 so division by zero
  75543. ** is never possible.
  75544. */
  75545. sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
  75546. if( jZeroRows<0 ){
  75547. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
  75548. }
  75549. for(i=0; i<nCol; i++){
  75550. sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
  75551. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
  75552. sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
  75553. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  75554. sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
  75555. sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
  75556. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
  75557. }
  75558. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  75559. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  75560. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
  75561. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  75562. }
  75563. /* If the table has no indices, create a single sqlite_stat1 entry
  75564. ** containing NULL as the index name and the row count as the content.
  75565. */
  75566. if( pTab->pIndex==0 ){
  75567. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
  75568. VdbeComment((v, "%s", pTab->zName));
  75569. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
  75570. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  75571. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  75572. }else{
  75573. sqlite3VdbeJumpHere(v, jZeroRows);
  75574. jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
  75575. }
  75576. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  75577. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  75578. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  75579. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
  75580. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  75581. if( pParse->nMem<regRec ) pParse->nMem = regRec;
  75582. sqlite3VdbeJumpHere(v, jZeroRows);
  75583. }
  75584. /*
  75585. ** Generate code that will cause the most recent index analysis to
  75586. ** be loaded into internal hash tables where is can be used.
  75587. */
  75588. static void loadAnalysis(Parse *pParse, int iDb){
  75589. Vdbe *v = sqlite3GetVdbe(pParse);
  75590. if( v ){
  75591. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  75592. }
  75593. }
  75594. /*
  75595. ** Generate code that will do an analysis of an entire database
  75596. */
  75597. static void analyzeDatabase(Parse *pParse, int iDb){
  75598. sqlite3 *db = pParse->db;
  75599. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  75600. HashElem *k;
  75601. int iStatCur;
  75602. int iMem;
  75603. sqlite3BeginWriteOperation(pParse, 0, iDb);
  75604. iStatCur = pParse->nTab;
  75605. pParse->nTab += 3;
  75606. openStatTable(pParse, iDb, iStatCur, 0, 0);
  75607. iMem = pParse->nMem+1;
  75608. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75609. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  75610. Table *pTab = (Table*)sqliteHashData(k);
  75611. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
  75612. }
  75613. loadAnalysis(pParse, iDb);
  75614. }
  75615. /*
  75616. ** Generate code that will do an analysis of a single table in
  75617. ** a database. If pOnlyIdx is not NULL then it is a single index
  75618. ** in pTab that should be analyzed.
  75619. */
  75620. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  75621. int iDb;
  75622. int iStatCur;
  75623. assert( pTab!=0 );
  75624. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  75625. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  75626. sqlite3BeginWriteOperation(pParse, 0, iDb);
  75627. iStatCur = pParse->nTab;
  75628. pParse->nTab += 3;
  75629. if( pOnlyIdx ){
  75630. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  75631. }else{
  75632. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  75633. }
  75634. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
  75635. loadAnalysis(pParse, iDb);
  75636. }
  75637. /*
  75638. ** Generate code for the ANALYZE command. The parser calls this routine
  75639. ** when it recognizes an ANALYZE command.
  75640. **
  75641. ** ANALYZE -- 1
  75642. ** ANALYZE <database> -- 2
  75643. ** ANALYZE ?<database>.?<tablename> -- 3
  75644. **
  75645. ** Form 1 causes all indices in all attached databases to be analyzed.
  75646. ** Form 2 analyzes all indices the single database named.
  75647. ** Form 3 analyzes all indices associated with the named table.
  75648. */
  75649. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  75650. sqlite3 *db = pParse->db;
  75651. int iDb;
  75652. int i;
  75653. char *z, *zDb;
  75654. Table *pTab;
  75655. Index *pIdx;
  75656. Token *pTableName;
  75657. /* Read the database schema. If an error occurs, leave an error message
  75658. ** and code in pParse and return NULL. */
  75659. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  75660. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  75661. return;
  75662. }
  75663. assert( pName2!=0 || pName1==0 );
  75664. if( pName1==0 ){
  75665. /* Form 1: Analyze everything */
  75666. for(i=0; i<db->nDb; i++){
  75667. if( i==1 ) continue; /* Do not analyze the TEMP database */
  75668. analyzeDatabase(pParse, i);
  75669. }
  75670. }else if( pName2->n==0 ){
  75671. /* Form 2: Analyze the database or table named */
  75672. iDb = sqlite3FindDb(db, pName1);
  75673. if( iDb>=0 ){
  75674. analyzeDatabase(pParse, iDb);
  75675. }else{
  75676. z = sqlite3NameFromToken(db, pName1);
  75677. if( z ){
  75678. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  75679. analyzeTable(pParse, pIdx->pTable, pIdx);
  75680. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  75681. analyzeTable(pParse, pTab, 0);
  75682. }
  75683. sqlite3DbFree(db, z);
  75684. }
  75685. }
  75686. }else{
  75687. /* Form 3: Analyze the fully qualified table name */
  75688. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  75689. if( iDb>=0 ){
  75690. zDb = db->aDb[iDb].zName;
  75691. z = sqlite3NameFromToken(db, pTableName);
  75692. if( z ){
  75693. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  75694. analyzeTable(pParse, pIdx->pTable, pIdx);
  75695. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  75696. analyzeTable(pParse, pTab, 0);
  75697. }
  75698. sqlite3DbFree(db, z);
  75699. }
  75700. }
  75701. }
  75702. }
  75703. /*
  75704. ** Used to pass information from the analyzer reader through to the
  75705. ** callback routine.
  75706. */
  75707. typedef struct analysisInfo analysisInfo;
  75708. struct analysisInfo {
  75709. sqlite3 *db;
  75710. const char *zDatabase;
  75711. };
  75712. /*
  75713. ** This callback is invoked once for each index when reading the
  75714. ** sqlite_stat1 table.
  75715. **
  75716. ** argv[0] = name of the table
  75717. ** argv[1] = name of the index (might be NULL)
  75718. ** argv[2] = results of analysis - on integer for each column
  75719. **
  75720. ** Entries for which argv[1]==NULL simply record the number of rows in
  75721. ** the table.
  75722. */
  75723. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  75724. analysisInfo *pInfo = (analysisInfo*)pData;
  75725. Index *pIndex;
  75726. Table *pTable;
  75727. int i, c, n;
  75728. tRowcnt v;
  75729. const char *z;
  75730. assert( argc==3 );
  75731. UNUSED_PARAMETER2(NotUsed, argc);
  75732. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  75733. return 0;
  75734. }
  75735. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  75736. if( pTable==0 ){
  75737. return 0;
  75738. }
  75739. if( argv[1] ){
  75740. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  75741. }else{
  75742. pIndex = 0;
  75743. }
  75744. n = pIndex ? pIndex->nColumn : 0;
  75745. z = argv[2];
  75746. for(i=0; *z && i<=n; i++){
  75747. v = 0;
  75748. while( (c=z[0])>='0' && c<='9' ){
  75749. v = v*10 + c - '0';
  75750. z++;
  75751. }
  75752. if( i==0 ) pTable->nRowEst = v;
  75753. if( pIndex==0 ) break;
  75754. pIndex->aiRowEst[i] = v;
  75755. if( *z==' ' ) z++;
  75756. if( strcmp(z, "unordered")==0 ){
  75757. pIndex->bUnordered = 1;
  75758. break;
  75759. }
  75760. }
  75761. return 0;
  75762. }
  75763. /*
  75764. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  75765. ** and its contents.
  75766. */
  75767. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  75768. #ifdef SQLITE_ENABLE_STAT3
  75769. if( pIdx->aSample ){
  75770. int j;
  75771. for(j=0; j<pIdx->nSample; j++){
  75772. IndexSample *p = &pIdx->aSample[j];
  75773. if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
  75774. sqlite3DbFree(db, p->u.z);
  75775. }
  75776. }
  75777. sqlite3DbFree(db, pIdx->aSample);
  75778. }
  75779. if( db && db->pnBytesFreed==0 ){
  75780. pIdx->nSample = 0;
  75781. pIdx->aSample = 0;
  75782. }
  75783. #else
  75784. UNUSED_PARAMETER(db);
  75785. UNUSED_PARAMETER(pIdx);
  75786. #endif
  75787. }
  75788. #ifdef SQLITE_ENABLE_STAT3
  75789. /*
  75790. ** Load content from the sqlite_stat3 table into the Index.aSample[]
  75791. ** arrays of all indices.
  75792. */
  75793. static int loadStat3(sqlite3 *db, const char *zDb){
  75794. int rc; /* Result codes from subroutines */
  75795. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  75796. char *zSql; /* Text of the SQL statement */
  75797. Index *pPrevIdx = 0; /* Previous index in the loop */
  75798. int idx = 0; /* slot in pIdx->aSample[] for next sample */
  75799. int eType; /* Datatype of a sample */
  75800. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  75801. assert( db->lookaside.bEnabled==0 );
  75802. if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  75803. return SQLITE_OK;
  75804. }
  75805. zSql = sqlite3MPrintf(db,
  75806. "SELECT idx,count(*) FROM %Q.sqlite_stat3"
  75807. " GROUP BY idx", zDb);
  75808. if( !zSql ){
  75809. return SQLITE_NOMEM;
  75810. }
  75811. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  75812. sqlite3DbFree(db, zSql);
  75813. if( rc ) return rc;
  75814. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  75815. char *zIndex; /* Index name */
  75816. Index *pIdx; /* Pointer to the index object */
  75817. int nSample; /* Number of samples */
  75818. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  75819. if( zIndex==0 ) continue;
  75820. nSample = sqlite3_column_int(pStmt, 1);
  75821. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  75822. if( pIdx==0 ) continue;
  75823. assert( pIdx->nSample==0 );
  75824. pIdx->nSample = nSample;
  75825. pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
  75826. pIdx->avgEq = pIdx->aiRowEst[1];
  75827. if( pIdx->aSample==0 ){
  75828. db->mallocFailed = 1;
  75829. sqlite3_finalize(pStmt);
  75830. return SQLITE_NOMEM;
  75831. }
  75832. }
  75833. rc = sqlite3_finalize(pStmt);
  75834. if( rc ) return rc;
  75835. zSql = sqlite3MPrintf(db,
  75836. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
  75837. if( !zSql ){
  75838. return SQLITE_NOMEM;
  75839. }
  75840. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  75841. sqlite3DbFree(db, zSql);
  75842. if( rc ) return rc;
  75843. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  75844. char *zIndex; /* Index name */
  75845. Index *pIdx; /* Pointer to the index object */
  75846. int i; /* Loop counter */
  75847. tRowcnt sumEq; /* Sum of the nEq values */
  75848. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  75849. if( zIndex==0 ) continue;
  75850. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  75851. if( pIdx==0 ) continue;
  75852. if( pIdx==pPrevIdx ){
  75853. idx++;
  75854. }else{
  75855. pPrevIdx = pIdx;
  75856. idx = 0;
  75857. }
  75858. assert( idx<pIdx->nSample );
  75859. pSample = &pIdx->aSample[idx];
  75860. pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
  75861. pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
  75862. pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
  75863. if( idx==pIdx->nSample-1 ){
  75864. if( pSample->nDLt>0 ){
  75865. for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
  75866. pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
  75867. }
  75868. if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
  75869. }
  75870. eType = sqlite3_column_type(pStmt, 4);
  75871. pSample->eType = (u8)eType;
  75872. switch( eType ){
  75873. case SQLITE_INTEGER: {
  75874. pSample->u.i = sqlite3_column_int64(pStmt, 4);
  75875. break;
  75876. }
  75877. case SQLITE_FLOAT: {
  75878. pSample->u.r = sqlite3_column_double(pStmt, 4);
  75879. break;
  75880. }
  75881. case SQLITE_NULL: {
  75882. break;
  75883. }
  75884. default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
  75885. const char *z = (const char *)(
  75886. (eType==SQLITE_BLOB) ?
  75887. sqlite3_column_blob(pStmt, 4):
  75888. sqlite3_column_text(pStmt, 4)
  75889. );
  75890. int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
  75891. pSample->nByte = n;
  75892. if( n < 1){
  75893. pSample->u.z = 0;
  75894. }else{
  75895. pSample->u.z = sqlite3DbMallocRaw(db, n);
  75896. if( pSample->u.z==0 ){
  75897. db->mallocFailed = 1;
  75898. sqlite3_finalize(pStmt);
  75899. return SQLITE_NOMEM;
  75900. }
  75901. memcpy(pSample->u.z, z, n);
  75902. }
  75903. }
  75904. }
  75905. }
  75906. return sqlite3_finalize(pStmt);
  75907. }
  75908. #endif /* SQLITE_ENABLE_STAT3 */
  75909. /*
  75910. ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
  75911. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  75912. ** arrays. The contents of sqlite_stat3 are used to populate the
  75913. ** Index.aSample[] arrays.
  75914. **
  75915. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  75916. ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
  75917. ** during compilation and the sqlite_stat3 table is present, no data is
  75918. ** read from it.
  75919. **
  75920. ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
  75921. ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
  75922. ** returned. However, in this case, data is read from the sqlite_stat1
  75923. ** table (if it is present) before returning.
  75924. **
  75925. ** If an OOM error occurs, this function always sets db->mallocFailed.
  75926. ** This means if the caller does not care about other errors, the return
  75927. ** code may be ignored.
  75928. */
  75929. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  75930. analysisInfo sInfo;
  75931. HashElem *i;
  75932. char *zSql;
  75933. int rc;
  75934. assert( iDb>=0 && iDb<db->nDb );
  75935. assert( db->aDb[iDb].pBt!=0 );
  75936. /* Clear any prior statistics */
  75937. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75938. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  75939. Index *pIdx = sqliteHashData(i);
  75940. sqlite3DefaultRowEst(pIdx);
  75941. #ifdef SQLITE_ENABLE_STAT3
  75942. sqlite3DeleteIndexSamples(db, pIdx);
  75943. pIdx->aSample = 0;
  75944. #endif
  75945. }
  75946. /* Check to make sure the sqlite_stat1 table exists */
  75947. sInfo.db = db;
  75948. sInfo.zDatabase = db->aDb[iDb].zName;
  75949. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  75950. return SQLITE_ERROR;
  75951. }
  75952. /* Load new statistics out of the sqlite_stat1 table */
  75953. zSql = sqlite3MPrintf(db,
  75954. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  75955. if( zSql==0 ){
  75956. rc = SQLITE_NOMEM;
  75957. }else{
  75958. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  75959. sqlite3DbFree(db, zSql);
  75960. }
  75961. /* Load the statistics from the sqlite_stat3 table. */
  75962. #ifdef SQLITE_ENABLE_STAT3
  75963. if( rc==SQLITE_OK ){
  75964. int lookasideEnabled = db->lookaside.bEnabled;
  75965. db->lookaside.bEnabled = 0;
  75966. rc = loadStat3(db, sInfo.zDatabase);
  75967. db->lookaside.bEnabled = lookasideEnabled;
  75968. }
  75969. #endif
  75970. if( rc==SQLITE_NOMEM ){
  75971. db->mallocFailed = 1;
  75972. }
  75973. return rc;
  75974. }
  75975. #endif /* SQLITE_OMIT_ANALYZE */
  75976. /************** End of analyze.c *********************************************/
  75977. /************** Begin file attach.c ******************************************/
  75978. /*
  75979. ** 2003 April 6
  75980. **
  75981. ** The author disclaims copyright to this source code. In place of
  75982. ** a legal notice, here is a blessing:
  75983. **
  75984. ** May you do good and not evil.
  75985. ** May you find forgiveness for yourself and forgive others.
  75986. ** May you share freely, never taking more than you give.
  75987. **
  75988. *************************************************************************
  75989. ** This file contains code used to implement the ATTACH and DETACH commands.
  75990. */
  75991. #ifndef SQLITE_OMIT_ATTACH
  75992. /*
  75993. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  75994. ** is slightly different from resolving a normal SQL expression, because simple
  75995. ** identifiers are treated as strings, not possible column names or aliases.
  75996. **
  75997. ** i.e. if the parser sees:
  75998. **
  75999. ** ATTACH DATABASE abc AS def
  76000. **
  76001. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  76002. ** looking for columns of the same name.
  76003. **
  76004. ** This only applies to the root node of pExpr, so the statement:
  76005. **
  76006. ** ATTACH DATABASE abc||def AS 'db2'
  76007. **
  76008. ** will fail because neither abc or def can be resolved.
  76009. */
  76010. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  76011. {
  76012. int rc = SQLITE_OK;
  76013. if( pExpr ){
  76014. if( pExpr->op!=TK_ID ){
  76015. rc = sqlite3ResolveExprNames(pName, pExpr);
  76016. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  76017. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  76018. return SQLITE_ERROR;
  76019. }
  76020. }else{
  76021. pExpr->op = TK_STRING;
  76022. }
  76023. }
  76024. return rc;
  76025. }
  76026. /*
  76027. ** An SQL user-function registered to do the work of an ATTACH statement. The
  76028. ** three arguments to the function come directly from an attach statement:
  76029. **
  76030. ** ATTACH DATABASE x AS y KEY z
  76031. **
  76032. ** SELECT sqlite_attach(x, y, z)
  76033. **
  76034. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  76035. ** third argument.
  76036. */
  76037. static void attachFunc(
  76038. sqlite3_context *context,
  76039. int NotUsed,
  76040. sqlite3_value **argv
  76041. ){
  76042. int i;
  76043. int rc = 0;
  76044. sqlite3 *db = sqlite3_context_db_handle(context);
  76045. const char *zName;
  76046. const char *zFile;
  76047. char *zPath = 0;
  76048. char *zErr = 0;
  76049. unsigned int flags;
  76050. Db *aNew;
  76051. char *zErrDyn = 0;
  76052. sqlite3_vfs *pVfs;
  76053. UNUSED_PARAMETER(NotUsed);
  76054. zFile = (const char *)sqlite3_value_text(argv[0]);
  76055. zName = (const char *)sqlite3_value_text(argv[1]);
  76056. if( zFile==0 ) zFile = "";
  76057. if( zName==0 ) zName = "";
  76058. /* Check for the following errors:
  76059. **
  76060. ** * Too many attached databases,
  76061. ** * Transaction currently open
  76062. ** * Specified database name already being used.
  76063. */
  76064. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  76065. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  76066. db->aLimit[SQLITE_LIMIT_ATTACHED]
  76067. );
  76068. goto attach_error;
  76069. }
  76070. if( !db->autoCommit ){
  76071. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  76072. goto attach_error;
  76073. }
  76074. for(i=0; i<db->nDb; i++){
  76075. char *z = db->aDb[i].zName;
  76076. assert( z && zName );
  76077. if( sqlite3StrICmp(z, zName)==0 ){
  76078. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  76079. goto attach_error;
  76080. }
  76081. }
  76082. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  76083. ** hash tables.
  76084. */
  76085. if( db->aDb==db->aDbStatic ){
  76086. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  76087. if( aNew==0 ) return;
  76088. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  76089. }else{
  76090. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  76091. if( aNew==0 ) return;
  76092. }
  76093. db->aDb = aNew;
  76094. aNew = &db->aDb[db->nDb];
  76095. memset(aNew, 0, sizeof(*aNew));
  76096. /* Open the database file. If the btree is successfully opened, use
  76097. ** it to obtain the database schema. At this point the schema may
  76098. ** or may not be initialized.
  76099. */
  76100. flags = db->openFlags;
  76101. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  76102. if( rc!=SQLITE_OK ){
  76103. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  76104. sqlite3_result_error(context, zErr, -1);
  76105. sqlite3_free(zErr);
  76106. return;
  76107. }
  76108. assert( pVfs );
  76109. flags |= SQLITE_OPEN_MAIN_DB;
  76110. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  76111. sqlite3_free( zPath );
  76112. db->nDb++;
  76113. if( rc==SQLITE_CONSTRAINT ){
  76114. rc = SQLITE_ERROR;
  76115. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  76116. }else if( rc==SQLITE_OK ){
  76117. Pager *pPager;
  76118. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  76119. if( !aNew->pSchema ){
  76120. rc = SQLITE_NOMEM;
  76121. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  76122. zErrDyn = sqlite3MPrintf(db,
  76123. "attached databases must use the same text encoding as main database");
  76124. rc = SQLITE_ERROR;
  76125. }
  76126. pPager = sqlite3BtreePager(aNew->pBt);
  76127. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  76128. sqlite3BtreeSecureDelete(aNew->pBt,
  76129. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  76130. }
  76131. aNew->safety_level = 3;
  76132. aNew->zName = sqlite3DbStrDup(db, zName);
  76133. if( rc==SQLITE_OK && aNew->zName==0 ){
  76134. rc = SQLITE_NOMEM;
  76135. }
  76136. #ifdef SQLITE_HAS_CODEC
  76137. if( rc==SQLITE_OK ){
  76138. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  76139. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  76140. int nKey;
  76141. char *zKey;
  76142. int t = sqlite3_value_type(argv[2]);
  76143. switch( t ){
  76144. case SQLITE_INTEGER:
  76145. case SQLITE_FLOAT:
  76146. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  76147. rc = SQLITE_ERROR;
  76148. break;
  76149. case SQLITE_TEXT:
  76150. case SQLITE_BLOB:
  76151. nKey = sqlite3_value_bytes(argv[2]);
  76152. zKey = (char *)sqlite3_value_blob(argv[2]);
  76153. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  76154. break;
  76155. case SQLITE_NULL:
  76156. /* No key specified. Use the key from the main database */
  76157. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  76158. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  76159. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  76160. }
  76161. break;
  76162. }
  76163. }
  76164. #endif
  76165. /* If the file was opened successfully, read the schema for the new database.
  76166. ** If this fails, or if opening the file failed, then close the file and
  76167. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  76168. ** we found it.
  76169. */
  76170. if( rc==SQLITE_OK ){
  76171. sqlite3BtreeEnterAll(db);
  76172. rc = sqlite3Init(db, &zErrDyn);
  76173. sqlite3BtreeLeaveAll(db);
  76174. }
  76175. if( rc ){
  76176. int iDb = db->nDb - 1;
  76177. assert( iDb>=2 );
  76178. if( db->aDb[iDb].pBt ){
  76179. sqlite3BtreeClose(db->aDb[iDb].pBt);
  76180. db->aDb[iDb].pBt = 0;
  76181. db->aDb[iDb].pSchema = 0;
  76182. }
  76183. sqlite3ResetAllSchemasOfConnection(db);
  76184. db->nDb = iDb;
  76185. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  76186. db->mallocFailed = 1;
  76187. sqlite3DbFree(db, zErrDyn);
  76188. zErrDyn = sqlite3MPrintf(db, "out of memory");
  76189. }else if( zErrDyn==0 ){
  76190. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  76191. }
  76192. goto attach_error;
  76193. }
  76194. return;
  76195. attach_error:
  76196. /* Return an error if we get here */
  76197. if( zErrDyn ){
  76198. sqlite3_result_error(context, zErrDyn, -1);
  76199. sqlite3DbFree(db, zErrDyn);
  76200. }
  76201. if( rc ) sqlite3_result_error_code(context, rc);
  76202. }
  76203. /*
  76204. ** An SQL user-function registered to do the work of an DETACH statement. The
  76205. ** three arguments to the function come directly from a detach statement:
  76206. **
  76207. ** DETACH DATABASE x
  76208. **
  76209. ** SELECT sqlite_detach(x)
  76210. */
  76211. static void detachFunc(
  76212. sqlite3_context *context,
  76213. int NotUsed,
  76214. sqlite3_value **argv
  76215. ){
  76216. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  76217. sqlite3 *db = sqlite3_context_db_handle(context);
  76218. int i;
  76219. Db *pDb = 0;
  76220. char zErr[128];
  76221. UNUSED_PARAMETER(NotUsed);
  76222. if( zName==0 ) zName = "";
  76223. for(i=0; i<db->nDb; i++){
  76224. pDb = &db->aDb[i];
  76225. if( pDb->pBt==0 ) continue;
  76226. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  76227. }
  76228. if( i>=db->nDb ){
  76229. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  76230. goto detach_error;
  76231. }
  76232. if( i<2 ){
  76233. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  76234. goto detach_error;
  76235. }
  76236. if( !db->autoCommit ){
  76237. sqlite3_snprintf(sizeof(zErr), zErr,
  76238. "cannot DETACH database within transaction");
  76239. goto detach_error;
  76240. }
  76241. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  76242. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  76243. goto detach_error;
  76244. }
  76245. sqlite3BtreeClose(pDb->pBt);
  76246. pDb->pBt = 0;
  76247. pDb->pSchema = 0;
  76248. sqlite3ResetAllSchemasOfConnection(db);
  76249. return;
  76250. detach_error:
  76251. sqlite3_result_error(context, zErr, -1);
  76252. }
  76253. /*
  76254. ** This procedure generates VDBE code for a single invocation of either the
  76255. ** sqlite_detach() or sqlite_attach() SQL user functions.
  76256. */
  76257. static void codeAttach(
  76258. Parse *pParse, /* The parser context */
  76259. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  76260. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  76261. Expr *pAuthArg, /* Expression to pass to authorization callback */
  76262. Expr *pFilename, /* Name of database file */
  76263. Expr *pDbname, /* Name of the database to use internally */
  76264. Expr *pKey /* Database key for encryption extension */
  76265. ){
  76266. int rc;
  76267. NameContext sName;
  76268. Vdbe *v;
  76269. sqlite3* db = pParse->db;
  76270. int regArgs;
  76271. memset(&sName, 0, sizeof(NameContext));
  76272. sName.pParse = pParse;
  76273. if(
  76274. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  76275. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  76276. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  76277. ){
  76278. pParse->nErr++;
  76279. goto attach_end;
  76280. }
  76281. #ifndef SQLITE_OMIT_AUTHORIZATION
  76282. if( pAuthArg ){
  76283. char *zAuthArg;
  76284. if( pAuthArg->op==TK_STRING ){
  76285. zAuthArg = pAuthArg->u.zToken;
  76286. }else{
  76287. zAuthArg = 0;
  76288. }
  76289. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  76290. if(rc!=SQLITE_OK ){
  76291. goto attach_end;
  76292. }
  76293. }
  76294. #endif /* SQLITE_OMIT_AUTHORIZATION */
  76295. v = sqlite3GetVdbe(pParse);
  76296. regArgs = sqlite3GetTempRange(pParse, 4);
  76297. sqlite3ExprCode(pParse, pFilename, regArgs);
  76298. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  76299. sqlite3ExprCode(pParse, pKey, regArgs+2);
  76300. assert( v || db->mallocFailed );
  76301. if( v ){
  76302. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  76303. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  76304. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  76305. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  76306. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  76307. ** statement only). For DETACH, set it to false (expire all existing
  76308. ** statements).
  76309. */
  76310. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  76311. }
  76312. attach_end:
  76313. sqlite3ExprDelete(db, pFilename);
  76314. sqlite3ExprDelete(db, pDbname);
  76315. sqlite3ExprDelete(db, pKey);
  76316. }
  76317. /*
  76318. ** Called by the parser to compile a DETACH statement.
  76319. **
  76320. ** DETACH pDbname
  76321. */
  76322. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  76323. static const FuncDef detach_func = {
  76324. 1, /* nArg */
  76325. SQLITE_UTF8, /* iPrefEnc */
  76326. 0, /* flags */
  76327. 0, /* pUserData */
  76328. 0, /* pNext */
  76329. detachFunc, /* xFunc */
  76330. 0, /* xStep */
  76331. 0, /* xFinalize */
  76332. "sqlite_detach", /* zName */
  76333. 0, /* pHash */
  76334. 0 /* pDestructor */
  76335. };
  76336. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  76337. }
  76338. /*
  76339. ** Called by the parser to compile an ATTACH statement.
  76340. **
  76341. ** ATTACH p AS pDbname KEY pKey
  76342. */
  76343. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  76344. static const FuncDef attach_func = {
  76345. 3, /* nArg */
  76346. SQLITE_UTF8, /* iPrefEnc */
  76347. 0, /* flags */
  76348. 0, /* pUserData */
  76349. 0, /* pNext */
  76350. attachFunc, /* xFunc */
  76351. 0, /* xStep */
  76352. 0, /* xFinalize */
  76353. "sqlite_attach", /* zName */
  76354. 0, /* pHash */
  76355. 0 /* pDestructor */
  76356. };
  76357. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  76358. }
  76359. #endif /* SQLITE_OMIT_ATTACH */
  76360. /*
  76361. ** Initialize a DbFixer structure. This routine must be called prior
  76362. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  76363. **
  76364. ** The return value indicates whether or not fixation is required. TRUE
  76365. ** means we do need to fix the database references, FALSE means we do not.
  76366. */
  76367. SQLITE_PRIVATE int sqlite3FixInit(
  76368. DbFixer *pFix, /* The fixer to be initialized */
  76369. Parse *pParse, /* Error messages will be written here */
  76370. int iDb, /* This is the database that must be used */
  76371. const char *zType, /* "view", "trigger", or "index" */
  76372. const Token *pName /* Name of the view, trigger, or index */
  76373. ){
  76374. sqlite3 *db;
  76375. if( NEVER(iDb<0) || iDb==1 ) return 0;
  76376. db = pParse->db;
  76377. assert( db->nDb>iDb );
  76378. pFix->pParse = pParse;
  76379. pFix->zDb = db->aDb[iDb].zName;
  76380. pFix->pSchema = db->aDb[iDb].pSchema;
  76381. pFix->zType = zType;
  76382. pFix->pName = pName;
  76383. return 1;
  76384. }
  76385. /*
  76386. ** The following set of routines walk through the parse tree and assign
  76387. ** a specific database to all table references where the database name
  76388. ** was left unspecified in the original SQL statement. The pFix structure
  76389. ** must have been initialized by a prior call to sqlite3FixInit().
  76390. **
  76391. ** These routines are used to make sure that an index, trigger, or
  76392. ** view in one database does not refer to objects in a different database.
  76393. ** (Exception: indices, triggers, and views in the TEMP database are
  76394. ** allowed to refer to anything.) If a reference is explicitly made
  76395. ** to an object in a different database, an error message is added to
  76396. ** pParse->zErrMsg and these routines return non-zero. If everything
  76397. ** checks out, these routines return 0.
  76398. */
  76399. SQLITE_PRIVATE int sqlite3FixSrcList(
  76400. DbFixer *pFix, /* Context of the fixation */
  76401. SrcList *pList /* The Source list to check and modify */
  76402. ){
  76403. int i;
  76404. const char *zDb;
  76405. struct SrcList_item *pItem;
  76406. if( NEVER(pList==0) ) return 0;
  76407. zDb = pFix->zDb;
  76408. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  76409. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  76410. sqlite3ErrorMsg(pFix->pParse,
  76411. "%s %T cannot reference objects in database %s",
  76412. pFix->zType, pFix->pName, pItem->zDatabase);
  76413. return 1;
  76414. }
  76415. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  76416. pItem->zDatabase = 0;
  76417. pItem->pSchema = pFix->pSchema;
  76418. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  76419. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  76420. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  76421. #endif
  76422. }
  76423. return 0;
  76424. }
  76425. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  76426. SQLITE_PRIVATE int sqlite3FixSelect(
  76427. DbFixer *pFix, /* Context of the fixation */
  76428. Select *pSelect /* The SELECT statement to be fixed to one database */
  76429. ){
  76430. while( pSelect ){
  76431. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  76432. return 1;
  76433. }
  76434. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  76435. return 1;
  76436. }
  76437. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  76438. return 1;
  76439. }
  76440. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  76441. return 1;
  76442. }
  76443. pSelect = pSelect->pPrior;
  76444. }
  76445. return 0;
  76446. }
  76447. SQLITE_PRIVATE int sqlite3FixExpr(
  76448. DbFixer *pFix, /* Context of the fixation */
  76449. Expr *pExpr /* The expression to be fixed to one database */
  76450. ){
  76451. while( pExpr ){
  76452. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
  76453. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  76454. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  76455. }else{
  76456. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  76457. }
  76458. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  76459. return 1;
  76460. }
  76461. pExpr = pExpr->pLeft;
  76462. }
  76463. return 0;
  76464. }
  76465. SQLITE_PRIVATE int sqlite3FixExprList(
  76466. DbFixer *pFix, /* Context of the fixation */
  76467. ExprList *pList /* The expression to be fixed to one database */
  76468. ){
  76469. int i;
  76470. struct ExprList_item *pItem;
  76471. if( pList==0 ) return 0;
  76472. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  76473. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  76474. return 1;
  76475. }
  76476. }
  76477. return 0;
  76478. }
  76479. #endif
  76480. #ifndef SQLITE_OMIT_TRIGGER
  76481. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  76482. DbFixer *pFix, /* Context of the fixation */
  76483. TriggerStep *pStep /* The trigger step be fixed to one database */
  76484. ){
  76485. while( pStep ){
  76486. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  76487. return 1;
  76488. }
  76489. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  76490. return 1;
  76491. }
  76492. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  76493. return 1;
  76494. }
  76495. pStep = pStep->pNext;
  76496. }
  76497. return 0;
  76498. }
  76499. #endif
  76500. /************** End of attach.c **********************************************/
  76501. /************** Begin file auth.c ********************************************/
  76502. /*
  76503. ** 2003 January 11
  76504. **
  76505. ** The author disclaims copyright to this source code. In place of
  76506. ** a legal notice, here is a blessing:
  76507. **
  76508. ** May you do good and not evil.
  76509. ** May you find forgiveness for yourself and forgive others.
  76510. ** May you share freely, never taking more than you give.
  76511. **
  76512. *************************************************************************
  76513. ** This file contains code used to implement the sqlite3_set_authorizer()
  76514. ** API. This facility is an optional feature of the library. Embedded
  76515. ** systems that do not need this facility may omit it by recompiling
  76516. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  76517. */
  76518. /*
  76519. ** All of the code in this file may be omitted by defining a single
  76520. ** macro.
  76521. */
  76522. #ifndef SQLITE_OMIT_AUTHORIZATION
  76523. /*
  76524. ** Set or clear the access authorization function.
  76525. **
  76526. ** The access authorization function is be called during the compilation
  76527. ** phase to verify that the user has read and/or write access permission on
  76528. ** various fields of the database. The first argument to the auth function
  76529. ** is a copy of the 3rd argument to this routine. The second argument
  76530. ** to the auth function is one of these constants:
  76531. **
  76532. ** SQLITE_CREATE_INDEX
  76533. ** SQLITE_CREATE_TABLE
  76534. ** SQLITE_CREATE_TEMP_INDEX
  76535. ** SQLITE_CREATE_TEMP_TABLE
  76536. ** SQLITE_CREATE_TEMP_TRIGGER
  76537. ** SQLITE_CREATE_TEMP_VIEW
  76538. ** SQLITE_CREATE_TRIGGER
  76539. ** SQLITE_CREATE_VIEW
  76540. ** SQLITE_DELETE
  76541. ** SQLITE_DROP_INDEX
  76542. ** SQLITE_DROP_TABLE
  76543. ** SQLITE_DROP_TEMP_INDEX
  76544. ** SQLITE_DROP_TEMP_TABLE
  76545. ** SQLITE_DROP_TEMP_TRIGGER
  76546. ** SQLITE_DROP_TEMP_VIEW
  76547. ** SQLITE_DROP_TRIGGER
  76548. ** SQLITE_DROP_VIEW
  76549. ** SQLITE_INSERT
  76550. ** SQLITE_PRAGMA
  76551. ** SQLITE_READ
  76552. ** SQLITE_SELECT
  76553. ** SQLITE_TRANSACTION
  76554. ** SQLITE_UPDATE
  76555. **
  76556. ** The third and fourth arguments to the auth function are the name of
  76557. ** the table and the column that are being accessed. The auth function
  76558. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  76559. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  76560. ** means that the SQL statement will never-run - the sqlite3_exec() call
  76561. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  76562. ** should run but attempts to read the specified column will return NULL
  76563. ** and attempts to write the column will be ignored.
  76564. **
  76565. ** Setting the auth function to NULL disables this hook. The default
  76566. ** setting of the auth function is NULL.
  76567. */
  76568. SQLITE_API int sqlite3_set_authorizer(
  76569. sqlite3 *db,
  76570. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  76571. void *pArg
  76572. ){
  76573. sqlite3_mutex_enter(db->mutex);
  76574. db->xAuth = xAuth;
  76575. db->pAuthArg = pArg;
  76576. sqlite3ExpirePreparedStatements(db);
  76577. sqlite3_mutex_leave(db->mutex);
  76578. return SQLITE_OK;
  76579. }
  76580. /*
  76581. ** Write an error message into pParse->zErrMsg that explains that the
  76582. ** user-supplied authorization function returned an illegal value.
  76583. */
  76584. static void sqliteAuthBadReturnCode(Parse *pParse){
  76585. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  76586. pParse->rc = SQLITE_ERROR;
  76587. }
  76588. /*
  76589. ** Invoke the authorization callback for permission to read column zCol from
  76590. ** table zTab in database zDb. This function assumes that an authorization
  76591. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  76592. **
  76593. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  76594. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  76595. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  76596. */
  76597. SQLITE_PRIVATE int sqlite3AuthReadCol(
  76598. Parse *pParse, /* The parser context */
  76599. const char *zTab, /* Table name */
  76600. const char *zCol, /* Column name */
  76601. int iDb /* Index of containing database. */
  76602. ){
  76603. sqlite3 *db = pParse->db; /* Database handle */
  76604. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  76605. int rc; /* Auth callback return code */
  76606. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  76607. if( rc==SQLITE_DENY ){
  76608. if( db->nDb>2 || iDb!=0 ){
  76609. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  76610. }else{
  76611. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  76612. }
  76613. pParse->rc = SQLITE_AUTH;
  76614. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  76615. sqliteAuthBadReturnCode(pParse);
  76616. }
  76617. return rc;
  76618. }
  76619. /*
  76620. ** The pExpr should be a TK_COLUMN expression. The table referred to
  76621. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  76622. ** Check to see if it is OK to read this particular column.
  76623. **
  76624. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  76625. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  76626. ** then generate an error.
  76627. */
  76628. SQLITE_PRIVATE void sqlite3AuthRead(
  76629. Parse *pParse, /* The parser context */
  76630. Expr *pExpr, /* The expression to check authorization on */
  76631. Schema *pSchema, /* The schema of the expression */
  76632. SrcList *pTabList /* All table that pExpr might refer to */
  76633. ){
  76634. sqlite3 *db = pParse->db;
  76635. Table *pTab = 0; /* The table being read */
  76636. const char *zCol; /* Name of the column of the table */
  76637. int iSrc; /* Index in pTabList->a[] of table being read */
  76638. int iDb; /* The index of the database the expression refers to */
  76639. int iCol; /* Index of column in table */
  76640. if( db->xAuth==0 ) return;
  76641. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  76642. if( iDb<0 ){
  76643. /* An attempt to read a column out of a subquery or other
  76644. ** temporary table. */
  76645. return;
  76646. }
  76647. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  76648. if( pExpr->op==TK_TRIGGER ){
  76649. pTab = pParse->pTriggerTab;
  76650. }else{
  76651. assert( pTabList );
  76652. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  76653. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  76654. pTab = pTabList->a[iSrc].pTab;
  76655. break;
  76656. }
  76657. }
  76658. }
  76659. iCol = pExpr->iColumn;
  76660. if( NEVER(pTab==0) ) return;
  76661. if( iCol>=0 ){
  76662. assert( iCol<pTab->nCol );
  76663. zCol = pTab->aCol[iCol].zName;
  76664. }else if( pTab->iPKey>=0 ){
  76665. assert( pTab->iPKey<pTab->nCol );
  76666. zCol = pTab->aCol[pTab->iPKey].zName;
  76667. }else{
  76668. zCol = "ROWID";
  76669. }
  76670. assert( iDb>=0 && iDb<db->nDb );
  76671. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  76672. pExpr->op = TK_NULL;
  76673. }
  76674. }
  76675. /*
  76676. ** Do an authorization check using the code and arguments given. Return
  76677. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  76678. ** is returned, then the error count and error message in pParse are
  76679. ** modified appropriately.
  76680. */
  76681. SQLITE_PRIVATE int sqlite3AuthCheck(
  76682. Parse *pParse,
  76683. int code,
  76684. const char *zArg1,
  76685. const char *zArg2,
  76686. const char *zArg3
  76687. ){
  76688. sqlite3 *db = pParse->db;
  76689. int rc;
  76690. /* Don't do any authorization checks if the database is initialising
  76691. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  76692. */
  76693. if( db->init.busy || IN_DECLARE_VTAB ){
  76694. return SQLITE_OK;
  76695. }
  76696. if( db->xAuth==0 ){
  76697. return SQLITE_OK;
  76698. }
  76699. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  76700. if( rc==SQLITE_DENY ){
  76701. sqlite3ErrorMsg(pParse, "not authorized");
  76702. pParse->rc = SQLITE_AUTH;
  76703. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  76704. rc = SQLITE_DENY;
  76705. sqliteAuthBadReturnCode(pParse);
  76706. }
  76707. return rc;
  76708. }
  76709. /*
  76710. ** Push an authorization context. After this routine is called, the
  76711. ** zArg3 argument to authorization callbacks will be zContext until
  76712. ** popped. Or if pParse==0, this routine is a no-op.
  76713. */
  76714. SQLITE_PRIVATE void sqlite3AuthContextPush(
  76715. Parse *pParse,
  76716. AuthContext *pContext,
  76717. const char *zContext
  76718. ){
  76719. assert( pParse );
  76720. pContext->pParse = pParse;
  76721. pContext->zAuthContext = pParse->zAuthContext;
  76722. pParse->zAuthContext = zContext;
  76723. }
  76724. /*
  76725. ** Pop an authorization context that was previously pushed
  76726. ** by sqlite3AuthContextPush
  76727. */
  76728. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  76729. if( pContext->pParse ){
  76730. pContext->pParse->zAuthContext = pContext->zAuthContext;
  76731. pContext->pParse = 0;
  76732. }
  76733. }
  76734. #endif /* SQLITE_OMIT_AUTHORIZATION */
  76735. /************** End of auth.c ************************************************/
  76736. /************** Begin file build.c *******************************************/
  76737. /*
  76738. ** 2001 September 15
  76739. **
  76740. ** The author disclaims copyright to this source code. In place of
  76741. ** a legal notice, here is a blessing:
  76742. **
  76743. ** May you do good and not evil.
  76744. ** May you find forgiveness for yourself and forgive others.
  76745. ** May you share freely, never taking more than you give.
  76746. **
  76747. *************************************************************************
  76748. ** This file contains C code routines that are called by the SQLite parser
  76749. ** when syntax rules are reduced. The routines in this file handle the
  76750. ** following kinds of SQL syntax:
  76751. **
  76752. ** CREATE TABLE
  76753. ** DROP TABLE
  76754. ** CREATE INDEX
  76755. ** DROP INDEX
  76756. ** creating ID lists
  76757. ** BEGIN TRANSACTION
  76758. ** COMMIT
  76759. ** ROLLBACK
  76760. */
  76761. /*
  76762. ** This routine is called when a new SQL statement is beginning to
  76763. ** be parsed. Initialize the pParse structure as needed.
  76764. */
  76765. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  76766. pParse->explain = (u8)explainFlag;
  76767. pParse->nVar = 0;
  76768. }
  76769. #ifndef SQLITE_OMIT_SHARED_CACHE
  76770. /*
  76771. ** The TableLock structure is only used by the sqlite3TableLock() and
  76772. ** codeTableLocks() functions.
  76773. */
  76774. struct TableLock {
  76775. int iDb; /* The database containing the table to be locked */
  76776. int iTab; /* The root page of the table to be locked */
  76777. u8 isWriteLock; /* True for write lock. False for a read lock */
  76778. const char *zName; /* Name of the table */
  76779. };
  76780. /*
  76781. ** Record the fact that we want to lock a table at run-time.
  76782. **
  76783. ** The table to be locked has root page iTab and is found in database iDb.
  76784. ** A read or a write lock can be taken depending on isWritelock.
  76785. **
  76786. ** This routine just records the fact that the lock is desired. The
  76787. ** code to make the lock occur is generated by a later call to
  76788. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  76789. */
  76790. SQLITE_PRIVATE void sqlite3TableLock(
  76791. Parse *pParse, /* Parsing context */
  76792. int iDb, /* Index of the database containing the table to lock */
  76793. int iTab, /* Root page number of the table to be locked */
  76794. u8 isWriteLock, /* True for a write lock */
  76795. const char *zName /* Name of the table to be locked */
  76796. ){
  76797. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  76798. int i;
  76799. int nBytes;
  76800. TableLock *p;
  76801. assert( iDb>=0 );
  76802. for(i=0; i<pToplevel->nTableLock; i++){
  76803. p = &pToplevel->aTableLock[i];
  76804. if( p->iDb==iDb && p->iTab==iTab ){
  76805. p->isWriteLock = (p->isWriteLock || isWriteLock);
  76806. return;
  76807. }
  76808. }
  76809. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  76810. pToplevel->aTableLock =
  76811. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  76812. if( pToplevel->aTableLock ){
  76813. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  76814. p->iDb = iDb;
  76815. p->iTab = iTab;
  76816. p->isWriteLock = isWriteLock;
  76817. p->zName = zName;
  76818. }else{
  76819. pToplevel->nTableLock = 0;
  76820. pToplevel->db->mallocFailed = 1;
  76821. }
  76822. }
  76823. /*
  76824. ** Code an OP_TableLock instruction for each table locked by the
  76825. ** statement (configured by calls to sqlite3TableLock()).
  76826. */
  76827. static void codeTableLocks(Parse *pParse){
  76828. int i;
  76829. Vdbe *pVdbe;
  76830. pVdbe = sqlite3GetVdbe(pParse);
  76831. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  76832. for(i=0; i<pParse->nTableLock; i++){
  76833. TableLock *p = &pParse->aTableLock[i];
  76834. int p1 = p->iDb;
  76835. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  76836. p->zName, P4_STATIC);
  76837. }
  76838. }
  76839. #else
  76840. #define codeTableLocks(x)
  76841. #endif
  76842. /*
  76843. ** This routine is called after a single SQL statement has been
  76844. ** parsed and a VDBE program to execute that statement has been
  76845. ** prepared. This routine puts the finishing touches on the
  76846. ** VDBE program and resets the pParse structure for the next
  76847. ** parse.
  76848. **
  76849. ** Note that if an error occurred, it might be the case that
  76850. ** no VDBE code was generated.
  76851. */
  76852. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  76853. sqlite3 *db;
  76854. Vdbe *v;
  76855. assert( pParse->pToplevel==0 );
  76856. db = pParse->db;
  76857. if( db->mallocFailed ) return;
  76858. if( pParse->nested ) return;
  76859. if( pParse->nErr ) return;
  76860. /* Begin by generating some termination code at the end of the
  76861. ** vdbe program
  76862. */
  76863. v = sqlite3GetVdbe(pParse);
  76864. assert( !pParse->isMultiWrite
  76865. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  76866. if( v ){
  76867. sqlite3VdbeAddOp0(v, OP_Halt);
  76868. /* The cookie mask contains one bit for each database file open.
  76869. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  76870. ** set for each database that is used. Generate code to start a
  76871. ** transaction on each used database and to verify the schema cookie
  76872. ** on each used database.
  76873. */
  76874. if( pParse->cookieGoto>0 ){
  76875. yDbMask mask;
  76876. int iDb;
  76877. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  76878. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  76879. if( (mask & pParse->cookieMask)==0 ) continue;
  76880. sqlite3VdbeUsesBtree(v, iDb);
  76881. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  76882. if( db->init.busy==0 ){
  76883. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76884. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  76885. iDb, pParse->cookieValue[iDb],
  76886. db->aDb[iDb].pSchema->iGeneration);
  76887. }
  76888. }
  76889. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76890. {
  76891. int i;
  76892. for(i=0; i<pParse->nVtabLock; i++){
  76893. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  76894. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  76895. }
  76896. pParse->nVtabLock = 0;
  76897. }
  76898. #endif
  76899. /* Once all the cookies have been verified and transactions opened,
  76900. ** obtain the required table-locks. This is a no-op unless the
  76901. ** shared-cache feature is enabled.
  76902. */
  76903. codeTableLocks(pParse);
  76904. /* Initialize any AUTOINCREMENT data structures required.
  76905. */
  76906. sqlite3AutoincrementBegin(pParse);
  76907. /* Finally, jump back to the beginning of the executable code. */
  76908. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  76909. }
  76910. }
  76911. /* Get the VDBE program ready for execution
  76912. */
  76913. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  76914. #ifdef SQLITE_DEBUG
  76915. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  76916. sqlite3VdbeTrace(v, trace);
  76917. #endif
  76918. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  76919. /* A minimum of one cursor is required if autoincrement is used
  76920. * See ticket [a696379c1f08866] */
  76921. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  76922. sqlite3VdbeMakeReady(v, pParse);
  76923. pParse->rc = SQLITE_DONE;
  76924. pParse->colNamesSet = 0;
  76925. }else{
  76926. pParse->rc = SQLITE_ERROR;
  76927. }
  76928. pParse->nTab = 0;
  76929. pParse->nMem = 0;
  76930. pParse->nSet = 0;
  76931. pParse->nVar = 0;
  76932. pParse->cookieMask = 0;
  76933. pParse->cookieGoto = 0;
  76934. }
  76935. /*
  76936. ** Run the parser and code generator recursively in order to generate
  76937. ** code for the SQL statement given onto the end of the pParse context
  76938. ** currently under construction. When the parser is run recursively
  76939. ** this way, the final OP_Halt is not appended and other initialization
  76940. ** and finalization steps are omitted because those are handling by the
  76941. ** outermost parser.
  76942. **
  76943. ** Not everything is nestable. This facility is designed to permit
  76944. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  76945. ** care if you decide to try to use this routine for some other purposes.
  76946. */
  76947. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  76948. va_list ap;
  76949. char *zSql;
  76950. char *zErrMsg = 0;
  76951. sqlite3 *db = pParse->db;
  76952. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  76953. char saveBuf[SAVE_SZ];
  76954. if( pParse->nErr ) return;
  76955. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  76956. va_start(ap, zFormat);
  76957. zSql = sqlite3VMPrintf(db, zFormat, ap);
  76958. va_end(ap);
  76959. if( zSql==0 ){
  76960. return; /* A malloc must have failed */
  76961. }
  76962. pParse->nested++;
  76963. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  76964. memset(&pParse->nVar, 0, SAVE_SZ);
  76965. sqlite3RunParser(pParse, zSql, &zErrMsg);
  76966. sqlite3DbFree(db, zErrMsg);
  76967. sqlite3DbFree(db, zSql);
  76968. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  76969. pParse->nested--;
  76970. }
  76971. /*
  76972. ** Locate the in-memory structure that describes a particular database
  76973. ** table given the name of that table and (optionally) the name of the
  76974. ** database containing the table. Return NULL if not found.
  76975. **
  76976. ** If zDatabase is 0, all databases are searched for the table and the
  76977. ** first matching table is returned. (No checking for duplicate table
  76978. ** names is done.) The search order is TEMP first, then MAIN, then any
  76979. ** auxiliary databases added using the ATTACH command.
  76980. **
  76981. ** See also sqlite3LocateTable().
  76982. */
  76983. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  76984. Table *p = 0;
  76985. int i;
  76986. int nName;
  76987. assert( zName!=0 );
  76988. nName = sqlite3Strlen30(zName);
  76989. /* All mutexes are required for schema access. Make sure we hold them. */
  76990. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  76991. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  76992. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  76993. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  76994. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  76995. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  76996. if( p ) break;
  76997. }
  76998. return p;
  76999. }
  77000. /*
  77001. ** Locate the in-memory structure that describes a particular database
  77002. ** table given the name of that table and (optionally) the name of the
  77003. ** database containing the table. Return NULL if not found. Also leave an
  77004. ** error message in pParse->zErrMsg.
  77005. **
  77006. ** The difference between this routine and sqlite3FindTable() is that this
  77007. ** routine leaves an error message in pParse->zErrMsg where
  77008. ** sqlite3FindTable() does not.
  77009. */
  77010. SQLITE_PRIVATE Table *sqlite3LocateTable(
  77011. Parse *pParse, /* context in which to report errors */
  77012. int isView, /* True if looking for a VIEW rather than a TABLE */
  77013. const char *zName, /* Name of the table we are looking for */
  77014. const char *zDbase /* Name of the database. Might be NULL */
  77015. ){
  77016. Table *p;
  77017. /* Read the database schema. If an error occurs, leave an error message
  77018. ** and code in pParse and return NULL. */
  77019. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  77020. return 0;
  77021. }
  77022. p = sqlite3FindTable(pParse->db, zName, zDbase);
  77023. if( p==0 ){
  77024. const char *zMsg = isView ? "no such view" : "no such table";
  77025. if( zDbase ){
  77026. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  77027. }else{
  77028. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  77029. }
  77030. pParse->checkSchema = 1;
  77031. }
  77032. return p;
  77033. }
  77034. /*
  77035. ** Locate the table identified by *p.
  77036. **
  77037. ** This is a wrapper around sqlite3LocateTable(). The difference between
  77038. ** sqlite3LocateTable() and this function is that this function restricts
  77039. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  77040. ** non-NULL if it is part of a view or trigger program definition. See
  77041. ** sqlite3FixSrcList() for details.
  77042. */
  77043. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  77044. Parse *pParse,
  77045. int isView,
  77046. struct SrcList_item *p
  77047. ){
  77048. const char *zDb;
  77049. assert( p->pSchema==0 || p->zDatabase==0 );
  77050. if( p->pSchema ){
  77051. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  77052. zDb = pParse->db->aDb[iDb].zName;
  77053. }else{
  77054. zDb = p->zDatabase;
  77055. }
  77056. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  77057. }
  77058. /*
  77059. ** Locate the in-memory structure that describes
  77060. ** a particular index given the name of that index
  77061. ** and the name of the database that contains the index.
  77062. ** Return NULL if not found.
  77063. **
  77064. ** If zDatabase is 0, all databases are searched for the
  77065. ** table and the first matching index is returned. (No checking
  77066. ** for duplicate index names is done.) The search order is
  77067. ** TEMP first, then MAIN, then any auxiliary databases added
  77068. ** using the ATTACH command.
  77069. */
  77070. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  77071. Index *p = 0;
  77072. int i;
  77073. int nName = sqlite3Strlen30(zName);
  77074. /* All mutexes are required for schema access. Make sure we hold them. */
  77075. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  77076. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  77077. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  77078. Schema *pSchema = db->aDb[j].pSchema;
  77079. assert( pSchema );
  77080. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  77081. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  77082. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  77083. if( p ) break;
  77084. }
  77085. return p;
  77086. }
  77087. /*
  77088. ** Reclaim the memory used by an index
  77089. */
  77090. static void freeIndex(sqlite3 *db, Index *p){
  77091. #ifndef SQLITE_OMIT_ANALYZE
  77092. sqlite3DeleteIndexSamples(db, p);
  77093. #endif
  77094. sqlite3DbFree(db, p->zColAff);
  77095. sqlite3DbFree(db, p);
  77096. }
  77097. /*
  77098. ** For the index called zIdxName which is found in the database iDb,
  77099. ** unlike that index from its Table then remove the index from
  77100. ** the index hash table and free all memory structures associated
  77101. ** with the index.
  77102. */
  77103. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  77104. Index *pIndex;
  77105. int len;
  77106. Hash *pHash;
  77107. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77108. pHash = &db->aDb[iDb].pSchema->idxHash;
  77109. len = sqlite3Strlen30(zIdxName);
  77110. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  77111. if( ALWAYS(pIndex) ){
  77112. if( pIndex->pTable->pIndex==pIndex ){
  77113. pIndex->pTable->pIndex = pIndex->pNext;
  77114. }else{
  77115. Index *p;
  77116. /* Justification of ALWAYS(); The index must be on the list of
  77117. ** indices. */
  77118. p = pIndex->pTable->pIndex;
  77119. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  77120. if( ALWAYS(p && p->pNext==pIndex) ){
  77121. p->pNext = pIndex->pNext;
  77122. }
  77123. }
  77124. freeIndex(db, pIndex);
  77125. }
  77126. db->flags |= SQLITE_InternChanges;
  77127. }
  77128. /*
  77129. ** Look through the list of open database files in db->aDb[] and if
  77130. ** any have been closed, remove them from the list. Reallocate the
  77131. ** db->aDb[] structure to a smaller size, if possible.
  77132. **
  77133. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  77134. ** are never candidates for being collapsed.
  77135. */
  77136. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  77137. int i, j;
  77138. for(i=j=2; i<db->nDb; i++){
  77139. struct Db *pDb = &db->aDb[i];
  77140. if( pDb->pBt==0 ){
  77141. sqlite3DbFree(db, pDb->zName);
  77142. pDb->zName = 0;
  77143. continue;
  77144. }
  77145. if( j<i ){
  77146. db->aDb[j] = db->aDb[i];
  77147. }
  77148. j++;
  77149. }
  77150. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  77151. db->nDb = j;
  77152. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  77153. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  77154. sqlite3DbFree(db, db->aDb);
  77155. db->aDb = db->aDbStatic;
  77156. }
  77157. }
  77158. /*
  77159. ** Reset the schema for the database at index iDb. Also reset the
  77160. ** TEMP schema.
  77161. */
  77162. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  77163. Db *pDb;
  77164. assert( iDb<db->nDb );
  77165. /* Case 1: Reset the single schema identified by iDb */
  77166. pDb = &db->aDb[iDb];
  77167. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77168. assert( pDb->pSchema!=0 );
  77169. sqlite3SchemaClear(pDb->pSchema);
  77170. /* If any database other than TEMP is reset, then also reset TEMP
  77171. ** since TEMP might be holding triggers that reference tables in the
  77172. ** other database.
  77173. */
  77174. if( iDb!=1 ){
  77175. pDb = &db->aDb[1];
  77176. assert( pDb->pSchema!=0 );
  77177. sqlite3SchemaClear(pDb->pSchema);
  77178. }
  77179. return;
  77180. }
  77181. /*
  77182. ** Erase all schema information from all attached databases (including
  77183. ** "main" and "temp") for a single database connection.
  77184. */
  77185. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  77186. int i;
  77187. sqlite3BtreeEnterAll(db);
  77188. for(i=0; i<db->nDb; i++){
  77189. Db *pDb = &db->aDb[i];
  77190. if( pDb->pSchema ){
  77191. sqlite3SchemaClear(pDb->pSchema);
  77192. }
  77193. }
  77194. db->flags &= ~SQLITE_InternChanges;
  77195. sqlite3VtabUnlockList(db);
  77196. sqlite3BtreeLeaveAll(db);
  77197. sqlite3CollapseDatabaseArray(db);
  77198. }
  77199. /*
  77200. ** This routine is called when a commit occurs.
  77201. */
  77202. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  77203. db->flags &= ~SQLITE_InternChanges;
  77204. }
  77205. /*
  77206. ** Delete memory allocated for the column names of a table or view (the
  77207. ** Table.aCol[] array).
  77208. */
  77209. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  77210. int i;
  77211. Column *pCol;
  77212. assert( pTable!=0 );
  77213. if( (pCol = pTable->aCol)!=0 ){
  77214. for(i=0; i<pTable->nCol; i++, pCol++){
  77215. sqlite3DbFree(db, pCol->zName);
  77216. sqlite3ExprDelete(db, pCol->pDflt);
  77217. sqlite3DbFree(db, pCol->zDflt);
  77218. sqlite3DbFree(db, pCol->zType);
  77219. sqlite3DbFree(db, pCol->zColl);
  77220. }
  77221. sqlite3DbFree(db, pTable->aCol);
  77222. }
  77223. }
  77224. /*
  77225. ** Remove the memory data structures associated with the given
  77226. ** Table. No changes are made to disk by this routine.
  77227. **
  77228. ** This routine just deletes the data structure. It does not unlink
  77229. ** the table data structure from the hash table. But it does destroy
  77230. ** memory structures of the indices and foreign keys associated with
  77231. ** the table.
  77232. **
  77233. ** The db parameter is optional. It is needed if the Table object
  77234. ** contains lookaside memory. (Table objects in the schema do not use
  77235. ** lookaside memory, but some ephemeral Table objects do.) Or the
  77236. ** db parameter can be used with db->pnBytesFreed to measure the memory
  77237. ** used by the Table object.
  77238. */
  77239. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  77240. Index *pIndex, *pNext;
  77241. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  77242. assert( !pTable || pTable->nRef>0 );
  77243. /* Do not delete the table until the reference count reaches zero. */
  77244. if( !pTable ) return;
  77245. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  77246. /* Record the number of outstanding lookaside allocations in schema Tables
  77247. ** prior to doing any free() operations. Since schema Tables do not use
  77248. ** lookaside, this number should not change. */
  77249. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  77250. db->lookaside.nOut : 0 );
  77251. /* Delete all indices associated with this table. */
  77252. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  77253. pNext = pIndex->pNext;
  77254. assert( pIndex->pSchema==pTable->pSchema );
  77255. if( !db || db->pnBytesFreed==0 ){
  77256. char *zName = pIndex->zName;
  77257. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  77258. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  77259. );
  77260. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  77261. assert( pOld==pIndex || pOld==0 );
  77262. }
  77263. freeIndex(db, pIndex);
  77264. }
  77265. /* Delete any foreign keys attached to this table. */
  77266. sqlite3FkDelete(db, pTable);
  77267. /* Delete the Table structure itself.
  77268. */
  77269. sqliteDeleteColumnNames(db, pTable);
  77270. sqlite3DbFree(db, pTable->zName);
  77271. sqlite3DbFree(db, pTable->zColAff);
  77272. sqlite3SelectDelete(db, pTable->pSelect);
  77273. #ifndef SQLITE_OMIT_CHECK
  77274. sqlite3ExprListDelete(db, pTable->pCheck);
  77275. #endif
  77276. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77277. sqlite3VtabClear(db, pTable);
  77278. #endif
  77279. sqlite3DbFree(db, pTable);
  77280. /* Verify that no lookaside memory was used by schema tables */
  77281. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  77282. }
  77283. /*
  77284. ** Unlink the given table from the hash tables and the delete the
  77285. ** table structure with all its indices and foreign keys.
  77286. */
  77287. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  77288. Table *p;
  77289. Db *pDb;
  77290. assert( db!=0 );
  77291. assert( iDb>=0 && iDb<db->nDb );
  77292. assert( zTabName );
  77293. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77294. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  77295. pDb = &db->aDb[iDb];
  77296. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  77297. sqlite3Strlen30(zTabName),0);
  77298. sqlite3DeleteTable(db, p);
  77299. db->flags |= SQLITE_InternChanges;
  77300. }
  77301. /*
  77302. ** Given a token, return a string that consists of the text of that
  77303. ** token. Space to hold the returned string
  77304. ** is obtained from sqliteMalloc() and must be freed by the calling
  77305. ** function.
  77306. **
  77307. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  77308. ** surround the body of the token are removed.
  77309. **
  77310. ** Tokens are often just pointers into the original SQL text and so
  77311. ** are not \000 terminated and are not persistent. The returned string
  77312. ** is \000 terminated and is persistent.
  77313. */
  77314. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  77315. char *zName;
  77316. if( pName ){
  77317. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  77318. sqlite3Dequote(zName);
  77319. }else{
  77320. zName = 0;
  77321. }
  77322. return zName;
  77323. }
  77324. /*
  77325. ** Open the sqlite_master table stored in database number iDb for
  77326. ** writing. The table is opened using cursor 0.
  77327. */
  77328. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  77329. Vdbe *v = sqlite3GetVdbe(p);
  77330. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  77331. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  77332. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  77333. if( p->nTab==0 ){
  77334. p->nTab = 1;
  77335. }
  77336. }
  77337. /*
  77338. ** Parameter zName points to a nul-terminated buffer containing the name
  77339. ** of a database ("main", "temp" or the name of an attached db). This
  77340. ** function returns the index of the named database in db->aDb[], or
  77341. ** -1 if the named db cannot be found.
  77342. */
  77343. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  77344. int i = -1; /* Database number */
  77345. if( zName ){
  77346. Db *pDb;
  77347. int n = sqlite3Strlen30(zName);
  77348. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  77349. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  77350. 0==sqlite3StrICmp(pDb->zName, zName) ){
  77351. break;
  77352. }
  77353. }
  77354. }
  77355. return i;
  77356. }
  77357. /*
  77358. ** The token *pName contains the name of a database (either "main" or
  77359. ** "temp" or the name of an attached db). This routine returns the
  77360. ** index of the named database in db->aDb[], or -1 if the named db
  77361. ** does not exist.
  77362. */
  77363. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  77364. int i; /* Database number */
  77365. char *zName; /* Name we are searching for */
  77366. zName = sqlite3NameFromToken(db, pName);
  77367. i = sqlite3FindDbName(db, zName);
  77368. sqlite3DbFree(db, zName);
  77369. return i;
  77370. }
  77371. /* The table or view or trigger name is passed to this routine via tokens
  77372. ** pName1 and pName2. If the table name was fully qualified, for example:
  77373. **
  77374. ** CREATE TABLE xxx.yyy (...);
  77375. **
  77376. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  77377. ** the table name is not fully qualified, i.e.:
  77378. **
  77379. ** CREATE TABLE yyy(...);
  77380. **
  77381. ** Then pName1 is set to "yyy" and pName2 is "".
  77382. **
  77383. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  77384. ** pName2) that stores the unqualified table name. The index of the
  77385. ** database "xxx" is returned.
  77386. */
  77387. SQLITE_PRIVATE int sqlite3TwoPartName(
  77388. Parse *pParse, /* Parsing and code generating context */
  77389. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  77390. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  77391. Token **pUnqual /* Write the unqualified object name here */
  77392. ){
  77393. int iDb; /* Database holding the object */
  77394. sqlite3 *db = pParse->db;
  77395. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  77396. if( db->init.busy ) {
  77397. sqlite3ErrorMsg(pParse, "corrupt database");
  77398. pParse->nErr++;
  77399. return -1;
  77400. }
  77401. *pUnqual = pName2;
  77402. iDb = sqlite3FindDb(db, pName1);
  77403. if( iDb<0 ){
  77404. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  77405. pParse->nErr++;
  77406. return -1;
  77407. }
  77408. }else{
  77409. assert( db->init.iDb==0 || db->init.busy );
  77410. iDb = db->init.iDb;
  77411. *pUnqual = pName1;
  77412. }
  77413. return iDb;
  77414. }
  77415. /*
  77416. ** This routine is used to check if the UTF-8 string zName is a legal
  77417. ** unqualified name for a new schema object (table, index, view or
  77418. ** trigger). All names are legal except those that begin with the string
  77419. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  77420. ** is reserved for internal use.
  77421. */
  77422. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  77423. if( !pParse->db->init.busy && pParse->nested==0
  77424. && (pParse->db->flags & SQLITE_WriteSchema)==0
  77425. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  77426. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  77427. return SQLITE_ERROR;
  77428. }
  77429. return SQLITE_OK;
  77430. }
  77431. /*
  77432. ** Begin constructing a new table representation in memory. This is
  77433. ** the first of several action routines that get called in response
  77434. ** to a CREATE TABLE statement. In particular, this routine is called
  77435. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  77436. ** flag is true if the table should be stored in the auxiliary database
  77437. ** file instead of in the main database file. This is normally the case
  77438. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  77439. ** CREATE and TABLE.
  77440. **
  77441. ** The new table record is initialized and put in pParse->pNewTable.
  77442. ** As more of the CREATE TABLE statement is parsed, additional action
  77443. ** routines will be called to add more information to this record.
  77444. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  77445. ** is called to complete the construction of the new table record.
  77446. */
  77447. SQLITE_PRIVATE void sqlite3StartTable(
  77448. Parse *pParse, /* Parser context */
  77449. Token *pName1, /* First part of the name of the table or view */
  77450. Token *pName2, /* Second part of the name of the table or view */
  77451. int isTemp, /* True if this is a TEMP table */
  77452. int isView, /* True if this is a VIEW */
  77453. int isVirtual, /* True if this is a VIRTUAL table */
  77454. int noErr /* Do nothing if table already exists */
  77455. ){
  77456. Table *pTable;
  77457. char *zName = 0; /* The name of the new table */
  77458. sqlite3 *db = pParse->db;
  77459. Vdbe *v;
  77460. int iDb; /* Database number to create the table in */
  77461. Token *pName; /* Unqualified name of the table to create */
  77462. /* The table or view name to create is passed to this routine via tokens
  77463. ** pName1 and pName2. If the table name was fully qualified, for example:
  77464. **
  77465. ** CREATE TABLE xxx.yyy (...);
  77466. **
  77467. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  77468. ** the table name is not fully qualified, i.e.:
  77469. **
  77470. ** CREATE TABLE yyy(...);
  77471. **
  77472. ** Then pName1 is set to "yyy" and pName2 is "".
  77473. **
  77474. ** The call below sets the pName pointer to point at the token (pName1 or
  77475. ** pName2) that stores the unqualified table name. The variable iDb is
  77476. ** set to the index of the database that the table or view is to be
  77477. ** created in.
  77478. */
  77479. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  77480. if( iDb<0 ) return;
  77481. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  77482. /* If creating a temp table, the name may not be qualified. Unless
  77483. ** the database name is "temp" anyway. */
  77484. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  77485. return;
  77486. }
  77487. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  77488. pParse->sNameToken = *pName;
  77489. zName = sqlite3NameFromToken(db, pName);
  77490. if( zName==0 ) return;
  77491. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  77492. goto begin_table_error;
  77493. }
  77494. if( db->init.iDb==1 ) isTemp = 1;
  77495. #ifndef SQLITE_OMIT_AUTHORIZATION
  77496. assert( (isTemp & 1)==isTemp );
  77497. {
  77498. int code;
  77499. char *zDb = db->aDb[iDb].zName;
  77500. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  77501. goto begin_table_error;
  77502. }
  77503. if( isView ){
  77504. if( !OMIT_TEMPDB && isTemp ){
  77505. code = SQLITE_CREATE_TEMP_VIEW;
  77506. }else{
  77507. code = SQLITE_CREATE_VIEW;
  77508. }
  77509. }else{
  77510. if( !OMIT_TEMPDB && isTemp ){
  77511. code = SQLITE_CREATE_TEMP_TABLE;
  77512. }else{
  77513. code = SQLITE_CREATE_TABLE;
  77514. }
  77515. }
  77516. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  77517. goto begin_table_error;
  77518. }
  77519. }
  77520. #endif
  77521. /* Make sure the new table name does not collide with an existing
  77522. ** index or table name in the same database. Issue an error message if
  77523. ** it does. The exception is if the statement being parsed was passed
  77524. ** to an sqlite3_declare_vtab() call. In that case only the column names
  77525. ** and types will be used, so there is no need to test for namespace
  77526. ** collisions.
  77527. */
  77528. if( !IN_DECLARE_VTAB ){
  77529. char *zDb = db->aDb[iDb].zName;
  77530. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  77531. goto begin_table_error;
  77532. }
  77533. pTable = sqlite3FindTable(db, zName, zDb);
  77534. if( pTable ){
  77535. if( !noErr ){
  77536. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  77537. }else{
  77538. assert( !db->init.busy );
  77539. sqlite3CodeVerifySchema(pParse, iDb);
  77540. }
  77541. goto begin_table_error;
  77542. }
  77543. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  77544. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  77545. goto begin_table_error;
  77546. }
  77547. }
  77548. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  77549. if( pTable==0 ){
  77550. db->mallocFailed = 1;
  77551. pParse->rc = SQLITE_NOMEM;
  77552. pParse->nErr++;
  77553. goto begin_table_error;
  77554. }
  77555. pTable->zName = zName;
  77556. pTable->iPKey = -1;
  77557. pTable->pSchema = db->aDb[iDb].pSchema;
  77558. pTable->nRef = 1;
  77559. pTable->nRowEst = 1000000;
  77560. assert( pParse->pNewTable==0 );
  77561. pParse->pNewTable = pTable;
  77562. /* If this is the magic sqlite_sequence table used by autoincrement,
  77563. ** then record a pointer to this table in the main database structure
  77564. ** so that INSERT can find the table easily.
  77565. */
  77566. #ifndef SQLITE_OMIT_AUTOINCREMENT
  77567. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  77568. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77569. pTable->pSchema->pSeqTab = pTable;
  77570. }
  77571. #endif
  77572. /* Begin generating the code that will insert the table record into
  77573. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  77574. ** and allocate the record number for the table entry now. Before any
  77575. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  77576. ** indices to be created and the table record must come before the
  77577. ** indices. Hence, the record number for the table must be allocated
  77578. ** now.
  77579. */
  77580. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  77581. int j1;
  77582. int fileFormat;
  77583. int reg1, reg2, reg3;
  77584. sqlite3BeginWriteOperation(pParse, 0, iDb);
  77585. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77586. if( isVirtual ){
  77587. sqlite3VdbeAddOp0(v, OP_VBegin);
  77588. }
  77589. #endif
  77590. /* If the file format and encoding in the database have not been set,
  77591. ** set them now.
  77592. */
  77593. reg1 = pParse->regRowid = ++pParse->nMem;
  77594. reg2 = pParse->regRoot = ++pParse->nMem;
  77595. reg3 = ++pParse->nMem;
  77596. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  77597. sqlite3VdbeUsesBtree(v, iDb);
  77598. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  77599. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  77600. 1 : SQLITE_MAX_FILE_FORMAT;
  77601. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  77602. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  77603. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  77604. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  77605. sqlite3VdbeJumpHere(v, j1);
  77606. /* This just creates a place-holder record in the sqlite_master table.
  77607. ** The record created does not contain anything yet. It will be replaced
  77608. ** by the real entry in code generated at sqlite3EndTable().
  77609. **
  77610. ** The rowid for the new entry is left in register pParse->regRowid.
  77611. ** The root page number of the new table is left in reg pParse->regRoot.
  77612. ** The rowid and root page number values are needed by the code that
  77613. ** sqlite3EndTable will generate.
  77614. */
  77615. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  77616. if( isView || isVirtual ){
  77617. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  77618. }else
  77619. #endif
  77620. {
  77621. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  77622. }
  77623. sqlite3OpenMasterTable(pParse, iDb);
  77624. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  77625. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  77626. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  77627. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  77628. sqlite3VdbeAddOp0(v, OP_Close);
  77629. }
  77630. /* Normal (non-error) return. */
  77631. return;
  77632. /* If an error occurs, we jump here */
  77633. begin_table_error:
  77634. sqlite3DbFree(db, zName);
  77635. return;
  77636. }
  77637. /*
  77638. ** This macro is used to compare two strings in a case-insensitive manner.
  77639. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  77640. ** produces larger code.
  77641. **
  77642. ** WARNING: This macro is not compatible with the strcmp() family. It
  77643. ** returns true if the two strings are equal, otherwise false.
  77644. */
  77645. #define STRICMP(x, y) (\
  77646. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  77647. sqlite3UpperToLower[*(unsigned char *)(y)] \
  77648. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  77649. /*
  77650. ** Add a new column to the table currently being constructed.
  77651. **
  77652. ** The parser calls this routine once for each column declaration
  77653. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  77654. ** first to get things going. Then this routine is called for each
  77655. ** column.
  77656. */
  77657. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  77658. Table *p;
  77659. int i;
  77660. char *z;
  77661. Column *pCol;
  77662. sqlite3 *db = pParse->db;
  77663. if( (p = pParse->pNewTable)==0 ) return;
  77664. #if SQLITE_MAX_COLUMN
  77665. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  77666. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  77667. return;
  77668. }
  77669. #endif
  77670. z = sqlite3NameFromToken(db, pName);
  77671. if( z==0 ) return;
  77672. for(i=0; i<p->nCol; i++){
  77673. if( STRICMP(z, p->aCol[i].zName) ){
  77674. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  77675. sqlite3DbFree(db, z);
  77676. return;
  77677. }
  77678. }
  77679. if( (p->nCol & 0x7)==0 ){
  77680. Column *aNew;
  77681. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  77682. if( aNew==0 ){
  77683. sqlite3DbFree(db, z);
  77684. return;
  77685. }
  77686. p->aCol = aNew;
  77687. }
  77688. pCol = &p->aCol[p->nCol];
  77689. memset(pCol, 0, sizeof(p->aCol[0]));
  77690. pCol->zName = z;
  77691. /* If there is no type specified, columns have the default affinity
  77692. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  77693. ** be called next to set pCol->affinity correctly.
  77694. */
  77695. pCol->affinity = SQLITE_AFF_NONE;
  77696. p->nCol++;
  77697. }
  77698. /*
  77699. ** This routine is called by the parser while in the middle of
  77700. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  77701. ** been seen on a column. This routine sets the notNull flag on
  77702. ** the column currently under construction.
  77703. */
  77704. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  77705. Table *p;
  77706. p = pParse->pNewTable;
  77707. if( p==0 || NEVER(p->nCol<1) ) return;
  77708. p->aCol[p->nCol-1].notNull = (u8)onError;
  77709. }
  77710. /*
  77711. ** Scan the column type name zType (length nType) and return the
  77712. ** associated affinity type.
  77713. **
  77714. ** This routine does a case-independent search of zType for the
  77715. ** substrings in the following table. If one of the substrings is
  77716. ** found, the corresponding affinity is returned. If zType contains
  77717. ** more than one of the substrings, entries toward the top of
  77718. ** the table take priority. For example, if zType is 'BLOBINT',
  77719. ** SQLITE_AFF_INTEGER is returned.
  77720. **
  77721. ** Substring | Affinity
  77722. ** --------------------------------
  77723. ** 'INT' | SQLITE_AFF_INTEGER
  77724. ** 'CHAR' | SQLITE_AFF_TEXT
  77725. ** 'CLOB' | SQLITE_AFF_TEXT
  77726. ** 'TEXT' | SQLITE_AFF_TEXT
  77727. ** 'BLOB' | SQLITE_AFF_NONE
  77728. ** 'REAL' | SQLITE_AFF_REAL
  77729. ** 'FLOA' | SQLITE_AFF_REAL
  77730. ** 'DOUB' | SQLITE_AFF_REAL
  77731. **
  77732. ** If none of the substrings in the above table are found,
  77733. ** SQLITE_AFF_NUMERIC is returned.
  77734. */
  77735. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
  77736. u32 h = 0;
  77737. char aff = SQLITE_AFF_NUMERIC;
  77738. if( zIn ) while( zIn[0] ){
  77739. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  77740. zIn++;
  77741. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  77742. aff = SQLITE_AFF_TEXT;
  77743. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  77744. aff = SQLITE_AFF_TEXT;
  77745. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  77746. aff = SQLITE_AFF_TEXT;
  77747. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  77748. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  77749. aff = SQLITE_AFF_NONE;
  77750. #ifndef SQLITE_OMIT_FLOATING_POINT
  77751. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  77752. && aff==SQLITE_AFF_NUMERIC ){
  77753. aff = SQLITE_AFF_REAL;
  77754. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  77755. && aff==SQLITE_AFF_NUMERIC ){
  77756. aff = SQLITE_AFF_REAL;
  77757. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  77758. && aff==SQLITE_AFF_NUMERIC ){
  77759. aff = SQLITE_AFF_REAL;
  77760. #endif
  77761. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  77762. aff = SQLITE_AFF_INTEGER;
  77763. break;
  77764. }
  77765. }
  77766. return aff;
  77767. }
  77768. /*
  77769. ** This routine is called by the parser while in the middle of
  77770. ** parsing a CREATE TABLE statement. The pFirst token is the first
  77771. ** token in the sequence of tokens that describe the type of the
  77772. ** column currently under construction. pLast is the last token
  77773. ** in the sequence. Use this information to construct a string
  77774. ** that contains the typename of the column and store that string
  77775. ** in zType.
  77776. */
  77777. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  77778. Table *p;
  77779. Column *pCol;
  77780. p = pParse->pNewTable;
  77781. if( p==0 || NEVER(p->nCol<1) ) return;
  77782. pCol = &p->aCol[p->nCol-1];
  77783. assert( pCol->zType==0 );
  77784. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  77785. pCol->affinity = sqlite3AffinityType(pCol->zType);
  77786. }
  77787. /*
  77788. ** The expression is the default value for the most recently added column
  77789. ** of the table currently under construction.
  77790. **
  77791. ** Default value expressions must be constant. Raise an exception if this
  77792. ** is not the case.
  77793. **
  77794. ** This routine is called by the parser while in the middle of
  77795. ** parsing a CREATE TABLE statement.
  77796. */
  77797. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  77798. Table *p;
  77799. Column *pCol;
  77800. sqlite3 *db = pParse->db;
  77801. p = pParse->pNewTable;
  77802. if( p!=0 ){
  77803. pCol = &(p->aCol[p->nCol-1]);
  77804. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  77805. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  77806. pCol->zName);
  77807. }else{
  77808. /* A copy of pExpr is used instead of the original, as pExpr contains
  77809. ** tokens that point to volatile memory. The 'span' of the expression
  77810. ** is required by pragma table_info.
  77811. */
  77812. sqlite3ExprDelete(db, pCol->pDflt);
  77813. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  77814. sqlite3DbFree(db, pCol->zDflt);
  77815. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  77816. (int)(pSpan->zEnd - pSpan->zStart));
  77817. }
  77818. }
  77819. sqlite3ExprDelete(db, pSpan->pExpr);
  77820. }
  77821. /*
  77822. ** Designate the PRIMARY KEY for the table. pList is a list of names
  77823. ** of columns that form the primary key. If pList is NULL, then the
  77824. ** most recently added column of the table is the primary key.
  77825. **
  77826. ** A table can have at most one primary key. If the table already has
  77827. ** a primary key (and this is the second primary key) then create an
  77828. ** error.
  77829. **
  77830. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  77831. ** then we will try to use that column as the rowid. Set the Table.iPKey
  77832. ** field of the table under construction to be the index of the
  77833. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  77834. ** no INTEGER PRIMARY KEY.
  77835. **
  77836. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  77837. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  77838. */
  77839. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  77840. Parse *pParse, /* Parsing context */
  77841. ExprList *pList, /* List of field names to be indexed */
  77842. int onError, /* What to do with a uniqueness conflict */
  77843. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  77844. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  77845. ){
  77846. Table *pTab = pParse->pNewTable;
  77847. char *zType = 0;
  77848. int iCol = -1, i;
  77849. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  77850. if( pTab->tabFlags & TF_HasPrimaryKey ){
  77851. sqlite3ErrorMsg(pParse,
  77852. "table \"%s\" has more than one primary key", pTab->zName);
  77853. goto primary_key_exit;
  77854. }
  77855. pTab->tabFlags |= TF_HasPrimaryKey;
  77856. if( pList==0 ){
  77857. iCol = pTab->nCol - 1;
  77858. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  77859. }else{
  77860. for(i=0; i<pList->nExpr; i++){
  77861. for(iCol=0; iCol<pTab->nCol; iCol++){
  77862. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  77863. break;
  77864. }
  77865. }
  77866. if( iCol<pTab->nCol ){
  77867. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  77868. }
  77869. }
  77870. if( pList->nExpr>1 ) iCol = -1;
  77871. }
  77872. if( iCol>=0 && iCol<pTab->nCol ){
  77873. zType = pTab->aCol[iCol].zType;
  77874. }
  77875. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  77876. && sortOrder==SQLITE_SO_ASC ){
  77877. pTab->iPKey = iCol;
  77878. pTab->keyConf = (u8)onError;
  77879. assert( autoInc==0 || autoInc==1 );
  77880. pTab->tabFlags |= autoInc*TF_Autoincrement;
  77881. }else if( autoInc ){
  77882. #ifndef SQLITE_OMIT_AUTOINCREMENT
  77883. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  77884. "INTEGER PRIMARY KEY");
  77885. #endif
  77886. }else{
  77887. Index *p;
  77888. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  77889. if( p ){
  77890. p->autoIndex = 2;
  77891. }
  77892. pList = 0;
  77893. }
  77894. primary_key_exit:
  77895. sqlite3ExprListDelete(pParse->db, pList);
  77896. return;
  77897. }
  77898. /*
  77899. ** Add a new CHECK constraint to the table currently under construction.
  77900. */
  77901. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  77902. Parse *pParse, /* Parsing context */
  77903. Expr *pCheckExpr /* The check expression */
  77904. ){
  77905. #ifndef SQLITE_OMIT_CHECK
  77906. Table *pTab = pParse->pNewTable;
  77907. if( pTab && !IN_DECLARE_VTAB ){
  77908. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  77909. if( pParse->constraintName.n ){
  77910. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  77911. }
  77912. }else
  77913. #endif
  77914. {
  77915. sqlite3ExprDelete(pParse->db, pCheckExpr);
  77916. }
  77917. }
  77918. /*
  77919. ** Set the collation function of the most recently parsed table column
  77920. ** to the CollSeq given.
  77921. */
  77922. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  77923. Table *p;
  77924. int i;
  77925. char *zColl; /* Dequoted name of collation sequence */
  77926. sqlite3 *db;
  77927. if( (p = pParse->pNewTable)==0 ) return;
  77928. i = p->nCol-1;
  77929. db = pParse->db;
  77930. zColl = sqlite3NameFromToken(db, pToken);
  77931. if( !zColl ) return;
  77932. if( sqlite3LocateCollSeq(pParse, zColl) ){
  77933. Index *pIdx;
  77934. p->aCol[i].zColl = zColl;
  77935. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  77936. ** then an index may have been created on this column before the
  77937. ** collation type was added. Correct this if it is the case.
  77938. */
  77939. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  77940. assert( pIdx->nColumn==1 );
  77941. if( pIdx->aiColumn[0]==i ){
  77942. pIdx->azColl[0] = p->aCol[i].zColl;
  77943. }
  77944. }
  77945. }else{
  77946. sqlite3DbFree(db, zColl);
  77947. }
  77948. }
  77949. /*
  77950. ** This function returns the collation sequence for database native text
  77951. ** encoding identified by the string zName, length nName.
  77952. **
  77953. ** If the requested collation sequence is not available, or not available
  77954. ** in the database native encoding, the collation factory is invoked to
  77955. ** request it. If the collation factory does not supply such a sequence,
  77956. ** and the sequence is available in another text encoding, then that is
  77957. ** returned instead.
  77958. **
  77959. ** If no versions of the requested collations sequence are available, or
  77960. ** another error occurs, NULL is returned and an error message written into
  77961. ** pParse.
  77962. **
  77963. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  77964. ** invokes the collation factory if the named collation cannot be found
  77965. ** and generates an error message.
  77966. **
  77967. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  77968. */
  77969. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  77970. sqlite3 *db = pParse->db;
  77971. u8 enc = ENC(db);
  77972. u8 initbusy = db->init.busy;
  77973. CollSeq *pColl;
  77974. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  77975. if( !initbusy && (!pColl || !pColl->xCmp) ){
  77976. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  77977. }
  77978. return pColl;
  77979. }
  77980. /*
  77981. ** Generate code that will increment the schema cookie.
  77982. **
  77983. ** The schema cookie is used to determine when the schema for the
  77984. ** database changes. After each schema change, the cookie value
  77985. ** changes. When a process first reads the schema it records the
  77986. ** cookie. Thereafter, whenever it goes to access the database,
  77987. ** it checks the cookie to make sure the schema has not changed
  77988. ** since it was last read.
  77989. **
  77990. ** This plan is not completely bullet-proof. It is possible for
  77991. ** the schema to change multiple times and for the cookie to be
  77992. ** set back to prior value. But schema changes are infrequent
  77993. ** and the probability of hitting the same cookie value is only
  77994. ** 1 chance in 2^32. So we're safe enough.
  77995. */
  77996. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  77997. int r1 = sqlite3GetTempReg(pParse);
  77998. sqlite3 *db = pParse->db;
  77999. Vdbe *v = pParse->pVdbe;
  78000. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78001. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  78002. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  78003. sqlite3ReleaseTempReg(pParse, r1);
  78004. }
  78005. /*
  78006. ** Measure the number of characters needed to output the given
  78007. ** identifier. The number returned includes any quotes used
  78008. ** but does not include the null terminator.
  78009. **
  78010. ** The estimate is conservative. It might be larger that what is
  78011. ** really needed.
  78012. */
  78013. static int identLength(const char *z){
  78014. int n;
  78015. for(n=0; *z; n++, z++){
  78016. if( *z=='"' ){ n++; }
  78017. }
  78018. return n + 2;
  78019. }
  78020. /*
  78021. ** The first parameter is a pointer to an output buffer. The second
  78022. ** parameter is a pointer to an integer that contains the offset at
  78023. ** which to write into the output buffer. This function copies the
  78024. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  78025. ** to the specified offset in the buffer and updates *pIdx to refer
  78026. ** to the first byte after the last byte written before returning.
  78027. **
  78028. ** If the string zSignedIdent consists entirely of alpha-numeric
  78029. ** characters, does not begin with a digit and is not an SQL keyword,
  78030. ** then it is copied to the output buffer exactly as it is. Otherwise,
  78031. ** it is quoted using double-quotes.
  78032. */
  78033. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  78034. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  78035. int i, j, needQuote;
  78036. i = *pIdx;
  78037. for(j=0; zIdent[j]; j++){
  78038. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  78039. }
  78040. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  78041. if( !needQuote ){
  78042. needQuote = zIdent[j];
  78043. }
  78044. if( needQuote ) z[i++] = '"';
  78045. for(j=0; zIdent[j]; j++){
  78046. z[i++] = zIdent[j];
  78047. if( zIdent[j]=='"' ) z[i++] = '"';
  78048. }
  78049. if( needQuote ) z[i++] = '"';
  78050. z[i] = 0;
  78051. *pIdx = i;
  78052. }
  78053. /*
  78054. ** Generate a CREATE TABLE statement appropriate for the given
  78055. ** table. Memory to hold the text of the statement is obtained
  78056. ** from sqliteMalloc() and must be freed by the calling function.
  78057. */
  78058. static char *createTableStmt(sqlite3 *db, Table *p){
  78059. int i, k, n;
  78060. char *zStmt;
  78061. char *zSep, *zSep2, *zEnd;
  78062. Column *pCol;
  78063. n = 0;
  78064. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  78065. n += identLength(pCol->zName) + 5;
  78066. }
  78067. n += identLength(p->zName);
  78068. if( n<50 ){
  78069. zSep = "";
  78070. zSep2 = ",";
  78071. zEnd = ")";
  78072. }else{
  78073. zSep = "\n ";
  78074. zSep2 = ",\n ";
  78075. zEnd = "\n)";
  78076. }
  78077. n += 35 + 6*p->nCol;
  78078. zStmt = sqlite3DbMallocRaw(0, n);
  78079. if( zStmt==0 ){
  78080. db->mallocFailed = 1;
  78081. return 0;
  78082. }
  78083. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  78084. k = sqlite3Strlen30(zStmt);
  78085. identPut(zStmt, &k, p->zName);
  78086. zStmt[k++] = '(';
  78087. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  78088. static const char * const azType[] = {
  78089. /* SQLITE_AFF_TEXT */ " TEXT",
  78090. /* SQLITE_AFF_NONE */ "",
  78091. /* SQLITE_AFF_NUMERIC */ " NUM",
  78092. /* SQLITE_AFF_INTEGER */ " INT",
  78093. /* SQLITE_AFF_REAL */ " REAL"
  78094. };
  78095. int len;
  78096. const char *zType;
  78097. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  78098. k += sqlite3Strlen30(&zStmt[k]);
  78099. zSep = zSep2;
  78100. identPut(zStmt, &k, pCol->zName);
  78101. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  78102. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  78103. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  78104. testcase( pCol->affinity==SQLITE_AFF_NONE );
  78105. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  78106. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  78107. testcase( pCol->affinity==SQLITE_AFF_REAL );
  78108. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  78109. len = sqlite3Strlen30(zType);
  78110. assert( pCol->affinity==SQLITE_AFF_NONE
  78111. || pCol->affinity==sqlite3AffinityType(zType) );
  78112. memcpy(&zStmt[k], zType, len);
  78113. k += len;
  78114. assert( k<=n );
  78115. }
  78116. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  78117. return zStmt;
  78118. }
  78119. /*
  78120. ** This routine is called to report the final ")" that terminates
  78121. ** a CREATE TABLE statement.
  78122. **
  78123. ** The table structure that other action routines have been building
  78124. ** is added to the internal hash tables, assuming no errors have
  78125. ** occurred.
  78126. **
  78127. ** An entry for the table is made in the master table on disk, unless
  78128. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  78129. ** it means we are reading the sqlite_master table because we just
  78130. ** connected to the database or because the sqlite_master table has
  78131. ** recently changed, so the entry for this table already exists in
  78132. ** the sqlite_master table. We do not want to create it again.
  78133. **
  78134. ** If the pSelect argument is not NULL, it means that this routine
  78135. ** was called to create a table generated from a
  78136. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  78137. ** the new table will match the result set of the SELECT.
  78138. */
  78139. SQLITE_PRIVATE void sqlite3EndTable(
  78140. Parse *pParse, /* Parse context */
  78141. Token *pCons, /* The ',' token after the last column defn. */
  78142. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  78143. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  78144. ){
  78145. Table *p;
  78146. sqlite3 *db = pParse->db;
  78147. int iDb;
  78148. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  78149. return;
  78150. }
  78151. p = pParse->pNewTable;
  78152. if( p==0 ) return;
  78153. assert( !db->init.busy || !pSelect );
  78154. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  78155. #ifndef SQLITE_OMIT_CHECK
  78156. /* Resolve names in all CHECK constraint expressions.
  78157. */
  78158. if( p->pCheck ){
  78159. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  78160. NameContext sNC; /* Name context for pParse->pNewTable */
  78161. ExprList *pList; /* List of all CHECK constraints */
  78162. int i; /* Loop counter */
  78163. memset(&sNC, 0, sizeof(sNC));
  78164. memset(&sSrc, 0, sizeof(sSrc));
  78165. sSrc.nSrc = 1;
  78166. sSrc.a[0].zName = p->zName;
  78167. sSrc.a[0].pTab = p;
  78168. sSrc.a[0].iCursor = -1;
  78169. sNC.pParse = pParse;
  78170. sNC.pSrcList = &sSrc;
  78171. sNC.ncFlags = NC_IsCheck;
  78172. pList = p->pCheck;
  78173. for(i=0; i<pList->nExpr; i++){
  78174. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  78175. return;
  78176. }
  78177. }
  78178. }
  78179. #endif /* !defined(SQLITE_OMIT_CHECK) */
  78180. /* If the db->init.busy is 1 it means we are reading the SQL off the
  78181. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  78182. ** So do not write to the disk again. Extract the root page number
  78183. ** for the table from the db->init.newTnum field. (The page number
  78184. ** should have been put there by the sqliteOpenCb routine.)
  78185. */
  78186. if( db->init.busy ){
  78187. p->tnum = db->init.newTnum;
  78188. }
  78189. /* If not initializing, then create a record for the new table
  78190. ** in the SQLITE_MASTER table of the database.
  78191. **
  78192. ** If this is a TEMPORARY table, write the entry into the auxiliary
  78193. ** file instead of into the main database file.
  78194. */
  78195. if( !db->init.busy ){
  78196. int n;
  78197. Vdbe *v;
  78198. char *zType; /* "view" or "table" */
  78199. char *zType2; /* "VIEW" or "TABLE" */
  78200. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  78201. v = sqlite3GetVdbe(pParse);
  78202. if( NEVER(v==0) ) return;
  78203. sqlite3VdbeAddOp1(v, OP_Close, 0);
  78204. /*
  78205. ** Initialize zType for the new view or table.
  78206. */
  78207. if( p->pSelect==0 ){
  78208. /* A regular table */
  78209. zType = "table";
  78210. zType2 = "TABLE";
  78211. #ifndef SQLITE_OMIT_VIEW
  78212. }else{
  78213. /* A view */
  78214. zType = "view";
  78215. zType2 = "VIEW";
  78216. #endif
  78217. }
  78218. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  78219. ** statement to populate the new table. The root-page number for the
  78220. ** new table is in register pParse->regRoot.
  78221. **
  78222. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  78223. ** suitable state to query for the column names and types to be used
  78224. ** by the new table.
  78225. **
  78226. ** A shared-cache write-lock is not required to write to the new table,
  78227. ** as a schema-lock must have already been obtained to create it. Since
  78228. ** a schema-lock excludes all other database users, the write-lock would
  78229. ** be redundant.
  78230. */
  78231. if( pSelect ){
  78232. SelectDest dest;
  78233. Table *pSelTab;
  78234. assert(pParse->nTab==1);
  78235. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  78236. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  78237. pParse->nTab = 2;
  78238. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  78239. sqlite3Select(pParse, pSelect, &dest);
  78240. sqlite3VdbeAddOp1(v, OP_Close, 1);
  78241. if( pParse->nErr==0 ){
  78242. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  78243. if( pSelTab==0 ) return;
  78244. assert( p->aCol==0 );
  78245. p->nCol = pSelTab->nCol;
  78246. p->aCol = pSelTab->aCol;
  78247. pSelTab->nCol = 0;
  78248. pSelTab->aCol = 0;
  78249. sqlite3DeleteTable(db, pSelTab);
  78250. }
  78251. }
  78252. /* Compute the complete text of the CREATE statement */
  78253. if( pSelect ){
  78254. zStmt = createTableStmt(db, p);
  78255. }else{
  78256. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  78257. zStmt = sqlite3MPrintf(db,
  78258. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  78259. );
  78260. }
  78261. /* A slot for the record has already been allocated in the
  78262. ** SQLITE_MASTER table. We just need to update that slot with all
  78263. ** the information we've collected.
  78264. */
  78265. sqlite3NestedParse(pParse,
  78266. "UPDATE %Q.%s "
  78267. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  78268. "WHERE rowid=#%d",
  78269. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  78270. zType,
  78271. p->zName,
  78272. p->zName,
  78273. pParse->regRoot,
  78274. zStmt,
  78275. pParse->regRowid
  78276. );
  78277. sqlite3DbFree(db, zStmt);
  78278. sqlite3ChangeCookie(pParse, iDb);
  78279. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78280. /* Check to see if we need to create an sqlite_sequence table for
  78281. ** keeping track of autoincrement keys.
  78282. */
  78283. if( p->tabFlags & TF_Autoincrement ){
  78284. Db *pDb = &db->aDb[iDb];
  78285. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78286. if( pDb->pSchema->pSeqTab==0 ){
  78287. sqlite3NestedParse(pParse,
  78288. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  78289. pDb->zName
  78290. );
  78291. }
  78292. }
  78293. #endif
  78294. /* Reparse everything to update our internal data structures */
  78295. sqlite3VdbeAddParseSchemaOp(v, iDb,
  78296. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  78297. }
  78298. /* Add the table to the in-memory representation of the database.
  78299. */
  78300. if( db->init.busy ){
  78301. Table *pOld;
  78302. Schema *pSchema = p->pSchema;
  78303. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78304. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  78305. sqlite3Strlen30(p->zName),p);
  78306. if( pOld ){
  78307. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  78308. db->mallocFailed = 1;
  78309. return;
  78310. }
  78311. pParse->pNewTable = 0;
  78312. db->flags |= SQLITE_InternChanges;
  78313. #ifndef SQLITE_OMIT_ALTERTABLE
  78314. if( !p->pSelect ){
  78315. const char *zName = (const char *)pParse->sNameToken.z;
  78316. int nName;
  78317. assert( !pSelect && pCons && pEnd );
  78318. if( pCons->z==0 ){
  78319. pCons = pEnd;
  78320. }
  78321. nName = (int)((const char *)pCons->z - zName);
  78322. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  78323. }
  78324. #endif
  78325. }
  78326. }
  78327. #ifndef SQLITE_OMIT_VIEW
  78328. /*
  78329. ** The parser calls this routine in order to create a new VIEW
  78330. */
  78331. SQLITE_PRIVATE void sqlite3CreateView(
  78332. Parse *pParse, /* The parsing context */
  78333. Token *pBegin, /* The CREATE token that begins the statement */
  78334. Token *pName1, /* The token that holds the name of the view */
  78335. Token *pName2, /* The token that holds the name of the view */
  78336. Select *pSelect, /* A SELECT statement that will become the new view */
  78337. int isTemp, /* TRUE for a TEMPORARY view */
  78338. int noErr /* Suppress error messages if VIEW already exists */
  78339. ){
  78340. Table *p;
  78341. int n;
  78342. const char *z;
  78343. Token sEnd;
  78344. DbFixer sFix;
  78345. Token *pName = 0;
  78346. int iDb;
  78347. sqlite3 *db = pParse->db;
  78348. if( pParse->nVar>0 ){
  78349. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  78350. sqlite3SelectDelete(db, pSelect);
  78351. return;
  78352. }
  78353. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  78354. p = pParse->pNewTable;
  78355. if( p==0 || pParse->nErr ){
  78356. sqlite3SelectDelete(db, pSelect);
  78357. return;
  78358. }
  78359. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  78360. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  78361. if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  78362. && sqlite3FixSelect(&sFix, pSelect)
  78363. ){
  78364. sqlite3SelectDelete(db, pSelect);
  78365. return;
  78366. }
  78367. /* Make a copy of the entire SELECT statement that defines the view.
  78368. ** This will force all the Expr.token.z values to be dynamically
  78369. ** allocated rather than point to the input string - which means that
  78370. ** they will persist after the current sqlite3_exec() call returns.
  78371. */
  78372. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  78373. sqlite3SelectDelete(db, pSelect);
  78374. if( db->mallocFailed ){
  78375. return;
  78376. }
  78377. if( !db->init.busy ){
  78378. sqlite3ViewGetColumnNames(pParse, p);
  78379. }
  78380. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  78381. ** the end.
  78382. */
  78383. sEnd = pParse->sLastToken;
  78384. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  78385. sEnd.z += sEnd.n;
  78386. }
  78387. sEnd.n = 0;
  78388. n = (int)(sEnd.z - pBegin->z);
  78389. z = pBegin->z;
  78390. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  78391. sEnd.z = &z[n-1];
  78392. sEnd.n = 1;
  78393. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  78394. sqlite3EndTable(pParse, 0, &sEnd, 0);
  78395. return;
  78396. }
  78397. #endif /* SQLITE_OMIT_VIEW */
  78398. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  78399. /*
  78400. ** The Table structure pTable is really a VIEW. Fill in the names of
  78401. ** the columns of the view in the pTable structure. Return the number
  78402. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  78403. */
  78404. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  78405. Table *pSelTab; /* A fake table from which we get the result set */
  78406. Select *pSel; /* Copy of the SELECT that implements the view */
  78407. int nErr = 0; /* Number of errors encountered */
  78408. int n; /* Temporarily holds the number of cursors assigned */
  78409. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  78410. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  78411. assert( pTable );
  78412. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78413. if( sqlite3VtabCallConnect(pParse, pTable) ){
  78414. return SQLITE_ERROR;
  78415. }
  78416. if( IsVirtual(pTable) ) return 0;
  78417. #endif
  78418. #ifndef SQLITE_OMIT_VIEW
  78419. /* A positive nCol means the columns names for this view are
  78420. ** already known.
  78421. */
  78422. if( pTable->nCol>0 ) return 0;
  78423. /* A negative nCol is a special marker meaning that we are currently
  78424. ** trying to compute the column names. If we enter this routine with
  78425. ** a negative nCol, it means two or more views form a loop, like this:
  78426. **
  78427. ** CREATE VIEW one AS SELECT * FROM two;
  78428. ** CREATE VIEW two AS SELECT * FROM one;
  78429. **
  78430. ** Actually, the error above is now caught prior to reaching this point.
  78431. ** But the following test is still important as it does come up
  78432. ** in the following:
  78433. **
  78434. ** CREATE TABLE main.ex1(a);
  78435. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  78436. ** SELECT * FROM temp.ex1;
  78437. */
  78438. if( pTable->nCol<0 ){
  78439. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  78440. return 1;
  78441. }
  78442. assert( pTable->nCol>=0 );
  78443. /* If we get this far, it means we need to compute the table names.
  78444. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  78445. ** "*" elements in the results set of the view and will assign cursors
  78446. ** to the elements of the FROM clause. But we do not want these changes
  78447. ** to be permanent. So the computation is done on a copy of the SELECT
  78448. ** statement that defines the view.
  78449. */
  78450. assert( pTable->pSelect );
  78451. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  78452. if( pSel ){
  78453. u8 enableLookaside = db->lookaside.bEnabled;
  78454. n = pParse->nTab;
  78455. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  78456. pTable->nCol = -1;
  78457. db->lookaside.bEnabled = 0;
  78458. #ifndef SQLITE_OMIT_AUTHORIZATION
  78459. xAuth = db->xAuth;
  78460. db->xAuth = 0;
  78461. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  78462. db->xAuth = xAuth;
  78463. #else
  78464. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  78465. #endif
  78466. db->lookaside.bEnabled = enableLookaside;
  78467. pParse->nTab = n;
  78468. if( pSelTab ){
  78469. assert( pTable->aCol==0 );
  78470. pTable->nCol = pSelTab->nCol;
  78471. pTable->aCol = pSelTab->aCol;
  78472. pSelTab->nCol = 0;
  78473. pSelTab->aCol = 0;
  78474. sqlite3DeleteTable(db, pSelTab);
  78475. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  78476. pTable->pSchema->flags |= DB_UnresetViews;
  78477. }else{
  78478. pTable->nCol = 0;
  78479. nErr++;
  78480. }
  78481. sqlite3SelectDelete(db, pSel);
  78482. } else {
  78483. nErr++;
  78484. }
  78485. #endif /* SQLITE_OMIT_VIEW */
  78486. return nErr;
  78487. }
  78488. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  78489. #ifndef SQLITE_OMIT_VIEW
  78490. /*
  78491. ** Clear the column names from every VIEW in database idx.
  78492. */
  78493. static void sqliteViewResetAll(sqlite3 *db, int idx){
  78494. HashElem *i;
  78495. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  78496. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  78497. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  78498. Table *pTab = sqliteHashData(i);
  78499. if( pTab->pSelect ){
  78500. sqliteDeleteColumnNames(db, pTab);
  78501. pTab->aCol = 0;
  78502. pTab->nCol = 0;
  78503. }
  78504. }
  78505. DbClearProperty(db, idx, DB_UnresetViews);
  78506. }
  78507. #else
  78508. # define sqliteViewResetAll(A,B)
  78509. #endif /* SQLITE_OMIT_VIEW */
  78510. /*
  78511. ** This function is called by the VDBE to adjust the internal schema
  78512. ** used by SQLite when the btree layer moves a table root page. The
  78513. ** root-page of a table or index in database iDb has changed from iFrom
  78514. ** to iTo.
  78515. **
  78516. ** Ticket #1728: The symbol table might still contain information
  78517. ** on tables and/or indices that are the process of being deleted.
  78518. ** If you are unlucky, one of those deleted indices or tables might
  78519. ** have the same rootpage number as the real table or index that is
  78520. ** being moved. So we cannot stop searching after the first match
  78521. ** because the first match might be for one of the deleted indices
  78522. ** or tables and not the table/index that is actually being moved.
  78523. ** We must continue looping until all tables and indices with
  78524. ** rootpage==iFrom have been converted to have a rootpage of iTo
  78525. ** in order to be certain that we got the right one.
  78526. */
  78527. #ifndef SQLITE_OMIT_AUTOVACUUM
  78528. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  78529. HashElem *pElem;
  78530. Hash *pHash;
  78531. Db *pDb;
  78532. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78533. pDb = &db->aDb[iDb];
  78534. pHash = &pDb->pSchema->tblHash;
  78535. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  78536. Table *pTab = sqliteHashData(pElem);
  78537. if( pTab->tnum==iFrom ){
  78538. pTab->tnum = iTo;
  78539. }
  78540. }
  78541. pHash = &pDb->pSchema->idxHash;
  78542. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  78543. Index *pIdx = sqliteHashData(pElem);
  78544. if( pIdx->tnum==iFrom ){
  78545. pIdx->tnum = iTo;
  78546. }
  78547. }
  78548. }
  78549. #endif
  78550. /*
  78551. ** Write code to erase the table with root-page iTable from database iDb.
  78552. ** Also write code to modify the sqlite_master table and internal schema
  78553. ** if a root-page of another table is moved by the btree-layer whilst
  78554. ** erasing iTable (this can happen with an auto-vacuum database).
  78555. */
  78556. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  78557. Vdbe *v = sqlite3GetVdbe(pParse);
  78558. int r1 = sqlite3GetTempReg(pParse);
  78559. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  78560. sqlite3MayAbort(pParse);
  78561. #ifndef SQLITE_OMIT_AUTOVACUUM
  78562. /* OP_Destroy stores an in integer r1. If this integer
  78563. ** is non-zero, then it is the root page number of a table moved to
  78564. ** location iTable. The following code modifies the sqlite_master table to
  78565. ** reflect this.
  78566. **
  78567. ** The "#NNN" in the SQL is a special constant that means whatever value
  78568. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  78569. ** token for additional information.
  78570. */
  78571. sqlite3NestedParse(pParse,
  78572. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  78573. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  78574. #endif
  78575. sqlite3ReleaseTempReg(pParse, r1);
  78576. }
  78577. /*
  78578. ** Write VDBE code to erase table pTab and all associated indices on disk.
  78579. ** Code to update the sqlite_master tables and internal schema definitions
  78580. ** in case a root-page belonging to another table is moved by the btree layer
  78581. ** is also added (this can happen with an auto-vacuum database).
  78582. */
  78583. static void destroyTable(Parse *pParse, Table *pTab){
  78584. #ifdef SQLITE_OMIT_AUTOVACUUM
  78585. Index *pIdx;
  78586. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78587. destroyRootPage(pParse, pTab->tnum, iDb);
  78588. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  78589. destroyRootPage(pParse, pIdx->tnum, iDb);
  78590. }
  78591. #else
  78592. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  78593. ** is not defined), then it is important to call OP_Destroy on the
  78594. ** table and index root-pages in order, starting with the numerically
  78595. ** largest root-page number. This guarantees that none of the root-pages
  78596. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  78597. ** following were coded:
  78598. **
  78599. ** OP_Destroy 4 0
  78600. ** ...
  78601. ** OP_Destroy 5 0
  78602. **
  78603. ** and root page 5 happened to be the largest root-page number in the
  78604. ** database, then root page 5 would be moved to page 4 by the
  78605. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  78606. ** a free-list page.
  78607. */
  78608. int iTab = pTab->tnum;
  78609. int iDestroyed = 0;
  78610. while( 1 ){
  78611. Index *pIdx;
  78612. int iLargest = 0;
  78613. if( iDestroyed==0 || iTab<iDestroyed ){
  78614. iLargest = iTab;
  78615. }
  78616. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  78617. int iIdx = pIdx->tnum;
  78618. assert( pIdx->pSchema==pTab->pSchema );
  78619. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  78620. iLargest = iIdx;
  78621. }
  78622. }
  78623. if( iLargest==0 ){
  78624. return;
  78625. }else{
  78626. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78627. assert( iDb>=0 && iDb<pParse->db->nDb );
  78628. destroyRootPage(pParse, iLargest, iDb);
  78629. iDestroyed = iLargest;
  78630. }
  78631. }
  78632. #endif
  78633. }
  78634. /*
  78635. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  78636. ** after a DROP INDEX or DROP TABLE command.
  78637. */
  78638. static void sqlite3ClearStatTables(
  78639. Parse *pParse, /* The parsing context */
  78640. int iDb, /* The database number */
  78641. const char *zType, /* "idx" or "tbl" */
  78642. const char *zName /* Name of index or table */
  78643. ){
  78644. int i;
  78645. const char *zDbName = pParse->db->aDb[iDb].zName;
  78646. for(i=1; i<=3; i++){
  78647. char zTab[24];
  78648. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  78649. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  78650. sqlite3NestedParse(pParse,
  78651. "DELETE FROM %Q.%s WHERE %s=%Q",
  78652. zDbName, zTab, zType, zName
  78653. );
  78654. }
  78655. }
  78656. }
  78657. /*
  78658. ** Generate code to drop a table.
  78659. */
  78660. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  78661. Vdbe *v;
  78662. sqlite3 *db = pParse->db;
  78663. Trigger *pTrigger;
  78664. Db *pDb = &db->aDb[iDb];
  78665. v = sqlite3GetVdbe(pParse);
  78666. assert( v!=0 );
  78667. sqlite3BeginWriteOperation(pParse, 1, iDb);
  78668. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78669. if( IsVirtual(pTab) ){
  78670. sqlite3VdbeAddOp0(v, OP_VBegin);
  78671. }
  78672. #endif
  78673. /* Drop all triggers associated with the table being dropped. Code
  78674. ** is generated to remove entries from sqlite_master and/or
  78675. ** sqlite_temp_master if required.
  78676. */
  78677. pTrigger = sqlite3TriggerList(pParse, pTab);
  78678. while( pTrigger ){
  78679. assert( pTrigger->pSchema==pTab->pSchema ||
  78680. pTrigger->pSchema==db->aDb[1].pSchema );
  78681. sqlite3DropTriggerPtr(pParse, pTrigger);
  78682. pTrigger = pTrigger->pNext;
  78683. }
  78684. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78685. /* Remove any entries of the sqlite_sequence table associated with
  78686. ** the table being dropped. This is done before the table is dropped
  78687. ** at the btree level, in case the sqlite_sequence table needs to
  78688. ** move as a result of the drop (can happen in auto-vacuum mode).
  78689. */
  78690. if( pTab->tabFlags & TF_Autoincrement ){
  78691. sqlite3NestedParse(pParse,
  78692. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  78693. pDb->zName, pTab->zName
  78694. );
  78695. }
  78696. #endif
  78697. /* Drop all SQLITE_MASTER table and index entries that refer to the
  78698. ** table. The program name loops through the master table and deletes
  78699. ** every row that refers to a table of the same name as the one being
  78700. ** dropped. Triggers are handled separately because a trigger can be
  78701. ** created in the temp database that refers to a table in another
  78702. ** database.
  78703. */
  78704. sqlite3NestedParse(pParse,
  78705. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  78706. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  78707. if( !isView && !IsVirtual(pTab) ){
  78708. destroyTable(pParse, pTab);
  78709. }
  78710. /* Remove the table entry from SQLite's internal schema and modify
  78711. ** the schema cookie.
  78712. */
  78713. if( IsVirtual(pTab) ){
  78714. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  78715. }
  78716. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  78717. sqlite3ChangeCookie(pParse, iDb);
  78718. sqliteViewResetAll(db, iDb);
  78719. }
  78720. /*
  78721. ** This routine is called to do the work of a DROP TABLE statement.
  78722. ** pName is the name of the table to be dropped.
  78723. */
  78724. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  78725. Table *pTab;
  78726. Vdbe *v;
  78727. sqlite3 *db = pParse->db;
  78728. int iDb;
  78729. if( db->mallocFailed ){
  78730. goto exit_drop_table;
  78731. }
  78732. assert( pParse->nErr==0 );
  78733. assert( pName->nSrc==1 );
  78734. if( noErr ) db->suppressErr++;
  78735. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  78736. if( noErr ) db->suppressErr--;
  78737. if( pTab==0 ){
  78738. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  78739. goto exit_drop_table;
  78740. }
  78741. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  78742. assert( iDb>=0 && iDb<db->nDb );
  78743. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  78744. ** it is initialized.
  78745. */
  78746. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  78747. goto exit_drop_table;
  78748. }
  78749. #ifndef SQLITE_OMIT_AUTHORIZATION
  78750. {
  78751. int code;
  78752. const char *zTab = SCHEMA_TABLE(iDb);
  78753. const char *zDb = db->aDb[iDb].zName;
  78754. const char *zArg2 = 0;
  78755. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  78756. goto exit_drop_table;
  78757. }
  78758. if( isView ){
  78759. if( !OMIT_TEMPDB && iDb==1 ){
  78760. code = SQLITE_DROP_TEMP_VIEW;
  78761. }else{
  78762. code = SQLITE_DROP_VIEW;
  78763. }
  78764. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78765. }else if( IsVirtual(pTab) ){
  78766. code = SQLITE_DROP_VTABLE;
  78767. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  78768. #endif
  78769. }else{
  78770. if( !OMIT_TEMPDB && iDb==1 ){
  78771. code = SQLITE_DROP_TEMP_TABLE;
  78772. }else{
  78773. code = SQLITE_DROP_TABLE;
  78774. }
  78775. }
  78776. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  78777. goto exit_drop_table;
  78778. }
  78779. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  78780. goto exit_drop_table;
  78781. }
  78782. }
  78783. #endif
  78784. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  78785. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  78786. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  78787. goto exit_drop_table;
  78788. }
  78789. #ifndef SQLITE_OMIT_VIEW
  78790. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  78791. ** on a table.
  78792. */
  78793. if( isView && pTab->pSelect==0 ){
  78794. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  78795. goto exit_drop_table;
  78796. }
  78797. if( !isView && pTab->pSelect ){
  78798. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  78799. goto exit_drop_table;
  78800. }
  78801. #endif
  78802. /* Generate code to remove the table from the master table
  78803. ** on disk.
  78804. */
  78805. v = sqlite3GetVdbe(pParse);
  78806. if( v ){
  78807. sqlite3BeginWriteOperation(pParse, 1, iDb);
  78808. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  78809. sqlite3FkDropTable(pParse, pName, pTab);
  78810. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  78811. }
  78812. exit_drop_table:
  78813. sqlite3SrcListDelete(db, pName);
  78814. }
  78815. /*
  78816. ** This routine is called to create a new foreign key on the table
  78817. ** currently under construction. pFromCol determines which columns
  78818. ** in the current table point to the foreign key. If pFromCol==0 then
  78819. ** connect the key to the last column inserted. pTo is the name of
  78820. ** the table referred to. pToCol is a list of tables in the other
  78821. ** pTo table that the foreign key points to. flags contains all
  78822. ** information about the conflict resolution algorithms specified
  78823. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  78824. **
  78825. ** An FKey structure is created and added to the table currently
  78826. ** under construction in the pParse->pNewTable field.
  78827. **
  78828. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  78829. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  78830. */
  78831. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  78832. Parse *pParse, /* Parsing context */
  78833. ExprList *pFromCol, /* Columns in this table that point to other table */
  78834. Token *pTo, /* Name of the other table */
  78835. ExprList *pToCol, /* Columns in the other table */
  78836. int flags /* Conflict resolution algorithms. */
  78837. ){
  78838. sqlite3 *db = pParse->db;
  78839. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78840. FKey *pFKey = 0;
  78841. FKey *pNextTo;
  78842. Table *p = pParse->pNewTable;
  78843. int nByte;
  78844. int i;
  78845. int nCol;
  78846. char *z;
  78847. assert( pTo!=0 );
  78848. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  78849. if( pFromCol==0 ){
  78850. int iCol = p->nCol-1;
  78851. if( NEVER(iCol<0) ) goto fk_end;
  78852. if( pToCol && pToCol->nExpr!=1 ){
  78853. sqlite3ErrorMsg(pParse, "foreign key on %s"
  78854. " should reference only one column of table %T",
  78855. p->aCol[iCol].zName, pTo);
  78856. goto fk_end;
  78857. }
  78858. nCol = 1;
  78859. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  78860. sqlite3ErrorMsg(pParse,
  78861. "number of columns in foreign key does not match the number of "
  78862. "columns in the referenced table");
  78863. goto fk_end;
  78864. }else{
  78865. nCol = pFromCol->nExpr;
  78866. }
  78867. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  78868. if( pToCol ){
  78869. for(i=0; i<pToCol->nExpr; i++){
  78870. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  78871. }
  78872. }
  78873. pFKey = sqlite3DbMallocZero(db, nByte );
  78874. if( pFKey==0 ){
  78875. goto fk_end;
  78876. }
  78877. pFKey->pFrom = p;
  78878. pFKey->pNextFrom = p->pFKey;
  78879. z = (char*)&pFKey->aCol[nCol];
  78880. pFKey->zTo = z;
  78881. memcpy(z, pTo->z, pTo->n);
  78882. z[pTo->n] = 0;
  78883. sqlite3Dequote(z);
  78884. z += pTo->n+1;
  78885. pFKey->nCol = nCol;
  78886. if( pFromCol==0 ){
  78887. pFKey->aCol[0].iFrom = p->nCol-1;
  78888. }else{
  78889. for(i=0; i<nCol; i++){
  78890. int j;
  78891. for(j=0; j<p->nCol; j++){
  78892. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  78893. pFKey->aCol[i].iFrom = j;
  78894. break;
  78895. }
  78896. }
  78897. if( j>=p->nCol ){
  78898. sqlite3ErrorMsg(pParse,
  78899. "unknown column \"%s\" in foreign key definition",
  78900. pFromCol->a[i].zName);
  78901. goto fk_end;
  78902. }
  78903. }
  78904. }
  78905. if( pToCol ){
  78906. for(i=0; i<nCol; i++){
  78907. int n = sqlite3Strlen30(pToCol->a[i].zName);
  78908. pFKey->aCol[i].zCol = z;
  78909. memcpy(z, pToCol->a[i].zName, n);
  78910. z[n] = 0;
  78911. z += n+1;
  78912. }
  78913. }
  78914. pFKey->isDeferred = 0;
  78915. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  78916. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  78917. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  78918. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  78919. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  78920. );
  78921. if( pNextTo==pFKey ){
  78922. db->mallocFailed = 1;
  78923. goto fk_end;
  78924. }
  78925. if( pNextTo ){
  78926. assert( pNextTo->pPrevTo==0 );
  78927. pFKey->pNextTo = pNextTo;
  78928. pNextTo->pPrevTo = pFKey;
  78929. }
  78930. /* Link the foreign key to the table as the last step.
  78931. */
  78932. p->pFKey = pFKey;
  78933. pFKey = 0;
  78934. fk_end:
  78935. sqlite3DbFree(db, pFKey);
  78936. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  78937. sqlite3ExprListDelete(db, pFromCol);
  78938. sqlite3ExprListDelete(db, pToCol);
  78939. }
  78940. /*
  78941. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  78942. ** clause is seen as part of a foreign key definition. The isDeferred
  78943. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  78944. ** The behavior of the most recently created foreign key is adjusted
  78945. ** accordingly.
  78946. */
  78947. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  78948. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78949. Table *pTab;
  78950. FKey *pFKey;
  78951. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  78952. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  78953. pFKey->isDeferred = (u8)isDeferred;
  78954. #endif
  78955. }
  78956. /*
  78957. ** Generate code that will erase and refill index *pIdx. This is
  78958. ** used to initialize a newly created index or to recompute the
  78959. ** content of an index in response to a REINDEX command.
  78960. **
  78961. ** if memRootPage is not negative, it means that the index is newly
  78962. ** created. The register specified by memRootPage contains the
  78963. ** root page number of the index. If memRootPage is negative, then
  78964. ** the index already exists and must be cleared before being refilled and
  78965. ** the root page number of the index is taken from pIndex->tnum.
  78966. */
  78967. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  78968. Table *pTab = pIndex->pTable; /* The table that is indexed */
  78969. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  78970. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  78971. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  78972. int addr1; /* Address of top of loop */
  78973. int addr2; /* Address to jump to for next iteration */
  78974. int tnum; /* Root page of index */
  78975. Vdbe *v; /* Generate code into this virtual machine */
  78976. KeyInfo *pKey; /* KeyInfo for index */
  78977. int regRecord; /* Register holding assemblied index record */
  78978. sqlite3 *db = pParse->db; /* The database connection */
  78979. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  78980. #ifndef SQLITE_OMIT_AUTHORIZATION
  78981. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  78982. db->aDb[iDb].zName ) ){
  78983. return;
  78984. }
  78985. #endif
  78986. /* Require a write-lock on the table to perform this operation */
  78987. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  78988. v = sqlite3GetVdbe(pParse);
  78989. if( v==0 ) return;
  78990. if( memRootPage>=0 ){
  78991. tnum = memRootPage;
  78992. }else{
  78993. tnum = pIndex->tnum;
  78994. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  78995. }
  78996. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  78997. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  78998. (char *)pKey, P4_KEYINFO_HANDOFF);
  78999. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  79000. /* Open the sorter cursor if we are to use one. */
  79001. iSorter = pParse->nTab++;
  79002. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  79003. /* Open the table. Loop through all rows of the table, inserting index
  79004. ** records into the sorter. */
  79005. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  79006. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  79007. regRecord = sqlite3GetTempReg(pParse);
  79008. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  79009. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  79010. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  79011. sqlite3VdbeJumpHere(v, addr1);
  79012. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  79013. if( pIndex->onError!=OE_None ){
  79014. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  79015. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  79016. addr2 = sqlite3VdbeCurrentAddr(v);
  79017. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  79018. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  79019. OE_Abort, "indexed columns are not unique", P4_STATIC
  79020. );
  79021. }else{
  79022. addr2 = sqlite3VdbeCurrentAddr(v);
  79023. }
  79024. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  79025. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  79026. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  79027. sqlite3ReleaseTempReg(pParse, regRecord);
  79028. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  79029. sqlite3VdbeJumpHere(v, addr1);
  79030. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  79031. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  79032. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  79033. }
  79034. /*
  79035. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  79036. ** and pTblList is the name of the table that is to be indexed. Both will
  79037. ** be NULL for a primary key or an index that is created to satisfy a
  79038. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  79039. ** as the table to be indexed. pParse->pNewTable is a table that is
  79040. ** currently being constructed by a CREATE TABLE statement.
  79041. **
  79042. ** pList is a list of columns to be indexed. pList will be NULL if this
  79043. ** is a primary key or unique-constraint on the most recent column added
  79044. ** to the table currently under construction.
  79045. **
  79046. ** If the index is created successfully, return a pointer to the new Index
  79047. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  79048. ** as the tables primary key (Index.autoIndex==2).
  79049. */
  79050. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  79051. Parse *pParse, /* All information about this parse */
  79052. Token *pName1, /* First part of index name. May be NULL */
  79053. Token *pName2, /* Second part of index name. May be NULL */
  79054. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  79055. ExprList *pList, /* A list of columns to be indexed */
  79056. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  79057. Token *pStart, /* The CREATE token that begins this statement */
  79058. Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
  79059. int sortOrder, /* Sort order of primary key when pList==NULL */
  79060. int ifNotExist /* Omit error if index already exists */
  79061. ){
  79062. Index *pRet = 0; /* Pointer to return */
  79063. Table *pTab = 0; /* Table to be indexed */
  79064. Index *pIndex = 0; /* The index to be created */
  79065. char *zName = 0; /* Name of the index */
  79066. int nName; /* Number of characters in zName */
  79067. int i, j;
  79068. Token nullId; /* Fake token for an empty ID list */
  79069. DbFixer sFix; /* For assigning database names to pTable */
  79070. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  79071. sqlite3 *db = pParse->db;
  79072. Db *pDb; /* The specific table containing the indexed database */
  79073. int iDb; /* Index of the database that is being written */
  79074. Token *pName = 0; /* Unqualified name of the index to create */
  79075. struct ExprList_item *pListItem; /* For looping over pList */
  79076. int nCol;
  79077. int nExtra = 0;
  79078. char *zExtra;
  79079. assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
  79080. assert( pParse->nErr==0 ); /* Never called with prior errors */
  79081. if( db->mallocFailed || IN_DECLARE_VTAB ){
  79082. goto exit_create_index;
  79083. }
  79084. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  79085. goto exit_create_index;
  79086. }
  79087. /*
  79088. ** Find the table that is to be indexed. Return early if not found.
  79089. */
  79090. if( pTblName!=0 ){
  79091. /* Use the two-part index name to determine the database
  79092. ** to search for the table. 'Fix' the table name to this db
  79093. ** before looking up the table.
  79094. */
  79095. assert( pName1 && pName2 );
  79096. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  79097. if( iDb<0 ) goto exit_create_index;
  79098. assert( pName && pName->z );
  79099. #ifndef SQLITE_OMIT_TEMPDB
  79100. /* If the index name was unqualified, check if the table
  79101. ** is a temp table. If so, set the database to 1. Do not do this
  79102. ** if initialising a database schema.
  79103. */
  79104. if( !db->init.busy ){
  79105. pTab = sqlite3SrcListLookup(pParse, pTblName);
  79106. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  79107. iDb = 1;
  79108. }
  79109. }
  79110. #endif
  79111. if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  79112. sqlite3FixSrcList(&sFix, pTblName)
  79113. ){
  79114. /* Because the parser constructs pTblName from a single identifier,
  79115. ** sqlite3FixSrcList can never fail. */
  79116. assert(0);
  79117. }
  79118. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  79119. assert( db->mallocFailed==0 || pTab==0 );
  79120. if( pTab==0 ) goto exit_create_index;
  79121. assert( db->aDb[iDb].pSchema==pTab->pSchema );
  79122. }else{
  79123. assert( pName==0 );
  79124. assert( pStart==0 );
  79125. pTab = pParse->pNewTable;
  79126. if( !pTab ) goto exit_create_index;
  79127. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  79128. }
  79129. pDb = &db->aDb[iDb];
  79130. assert( pTab!=0 );
  79131. assert( pParse->nErr==0 );
  79132. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  79133. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  79134. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  79135. goto exit_create_index;
  79136. }
  79137. #ifndef SQLITE_OMIT_VIEW
  79138. if( pTab->pSelect ){
  79139. sqlite3ErrorMsg(pParse, "views may not be indexed");
  79140. goto exit_create_index;
  79141. }
  79142. #endif
  79143. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79144. if( IsVirtual(pTab) ){
  79145. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  79146. goto exit_create_index;
  79147. }
  79148. #endif
  79149. /*
  79150. ** Find the name of the index. Make sure there is not already another
  79151. ** index or table with the same name.
  79152. **
  79153. ** Exception: If we are reading the names of permanent indices from the
  79154. ** sqlite_master table (because some other process changed the schema) and
  79155. ** one of the index names collides with the name of a temporary table or
  79156. ** index, then we will continue to process this index.
  79157. **
  79158. ** If pName==0 it means that we are
  79159. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  79160. ** own name.
  79161. */
  79162. if( pName ){
  79163. zName = sqlite3NameFromToken(db, pName);
  79164. if( zName==0 ) goto exit_create_index;
  79165. assert( pName->z!=0 );
  79166. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  79167. goto exit_create_index;
  79168. }
  79169. if( !db->init.busy ){
  79170. if( sqlite3FindTable(db, zName, 0)!=0 ){
  79171. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  79172. goto exit_create_index;
  79173. }
  79174. }
  79175. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  79176. if( !ifNotExist ){
  79177. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  79178. }else{
  79179. assert( !db->init.busy );
  79180. sqlite3CodeVerifySchema(pParse, iDb);
  79181. }
  79182. goto exit_create_index;
  79183. }
  79184. }else{
  79185. int n;
  79186. Index *pLoop;
  79187. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  79188. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  79189. if( zName==0 ){
  79190. goto exit_create_index;
  79191. }
  79192. }
  79193. /* Check for authorization to create an index.
  79194. */
  79195. #ifndef SQLITE_OMIT_AUTHORIZATION
  79196. {
  79197. const char *zDb = pDb->zName;
  79198. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  79199. goto exit_create_index;
  79200. }
  79201. i = SQLITE_CREATE_INDEX;
  79202. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  79203. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  79204. goto exit_create_index;
  79205. }
  79206. }
  79207. #endif
  79208. /* If pList==0, it means this routine was called to make a primary
  79209. ** key out of the last column added to the table under construction.
  79210. ** So create a fake list to simulate this.
  79211. */
  79212. if( pList==0 ){
  79213. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  79214. nullId.n = sqlite3Strlen30((char*)nullId.z);
  79215. pList = sqlite3ExprListAppend(pParse, 0, 0);
  79216. if( pList==0 ) goto exit_create_index;
  79217. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  79218. pList->a[0].sortOrder = (u8)sortOrder;
  79219. }
  79220. /* Figure out how many bytes of space are required to store explicitly
  79221. ** specified collation sequence names.
  79222. */
  79223. for(i=0; i<pList->nExpr; i++){
  79224. Expr *pExpr = pList->a[i].pExpr;
  79225. if( pExpr ){
  79226. assert( pExpr->op==TK_COLLATE );
  79227. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  79228. }
  79229. }
  79230. /*
  79231. ** Allocate the index structure.
  79232. */
  79233. nName = sqlite3Strlen30(zName);
  79234. nCol = pList->nExpr;
  79235. pIndex = sqlite3DbMallocZero(db,
  79236. ROUND8(sizeof(Index)) + /* Index structure */
  79237. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  79238. sizeof(char *)*nCol + /* Index.azColl */
  79239. sizeof(int)*nCol + /* Index.aiColumn */
  79240. sizeof(u8)*nCol + /* Index.aSortOrder */
  79241. nName + 1 + /* Index.zName */
  79242. nExtra /* Collation sequence names */
  79243. );
  79244. if( db->mallocFailed ){
  79245. goto exit_create_index;
  79246. }
  79247. zExtra = (char*)pIndex;
  79248. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  79249. pIndex->azColl = (char**)
  79250. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  79251. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  79252. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  79253. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  79254. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  79255. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  79256. zExtra = (char *)(&pIndex->zName[nName+1]);
  79257. memcpy(pIndex->zName, zName, nName+1);
  79258. pIndex->pTable = pTab;
  79259. pIndex->nColumn = pList->nExpr;
  79260. pIndex->onError = (u8)onError;
  79261. pIndex->autoIndex = (u8)(pName==0);
  79262. pIndex->pSchema = db->aDb[iDb].pSchema;
  79263. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79264. /* Check to see if we should honor DESC requests on index columns
  79265. */
  79266. if( pDb->pSchema->file_format>=4 ){
  79267. sortOrderMask = -1; /* Honor DESC */
  79268. }else{
  79269. sortOrderMask = 0; /* Ignore DESC */
  79270. }
  79271. /* Scan the names of the columns of the table to be indexed and
  79272. ** load the column indices into the Index structure. Report an error
  79273. ** if any column is not found.
  79274. **
  79275. ** TODO: Add a test to make sure that the same column is not named
  79276. ** more than once within the same index. Only the first instance of
  79277. ** the column will ever be used by the optimizer. Note that using the
  79278. ** same column more than once cannot be an error because that would
  79279. ** break backwards compatibility - it needs to be a warning.
  79280. */
  79281. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  79282. const char *zColName = pListItem->zName;
  79283. Column *pTabCol;
  79284. int requestedSortOrder;
  79285. char *zColl; /* Collation sequence name */
  79286. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  79287. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  79288. }
  79289. if( j>=pTab->nCol ){
  79290. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  79291. pTab->zName, zColName);
  79292. pParse->checkSchema = 1;
  79293. goto exit_create_index;
  79294. }
  79295. pIndex->aiColumn[i] = j;
  79296. if( pListItem->pExpr ){
  79297. int nColl;
  79298. assert( pListItem->pExpr->op==TK_COLLATE );
  79299. zColl = pListItem->pExpr->u.zToken;
  79300. nColl = sqlite3Strlen30(zColl) + 1;
  79301. assert( nExtra>=nColl );
  79302. memcpy(zExtra, zColl, nColl);
  79303. zColl = zExtra;
  79304. zExtra += nColl;
  79305. nExtra -= nColl;
  79306. }else{
  79307. zColl = pTab->aCol[j].zColl;
  79308. if( !zColl ) zColl = "BINARY";
  79309. }
  79310. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  79311. goto exit_create_index;
  79312. }
  79313. pIndex->azColl[i] = zColl;
  79314. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  79315. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  79316. }
  79317. sqlite3DefaultRowEst(pIndex);
  79318. if( pTab==pParse->pNewTable ){
  79319. /* This routine has been called to create an automatic index as a
  79320. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  79321. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  79322. ** i.e. one of:
  79323. **
  79324. ** CREATE TABLE t(x PRIMARY KEY, y);
  79325. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  79326. **
  79327. ** Either way, check to see if the table already has such an index. If
  79328. ** so, don't bother creating this one. This only applies to
  79329. ** automatically created indices. Users can do as they wish with
  79330. ** explicit indices.
  79331. **
  79332. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  79333. ** (and thus suppressing the second one) even if they have different
  79334. ** sort orders.
  79335. **
  79336. ** If there are different collating sequences or if the columns of
  79337. ** the constraint occur in different orders, then the constraints are
  79338. ** considered distinct and both result in separate indices.
  79339. */
  79340. Index *pIdx;
  79341. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  79342. int k;
  79343. assert( pIdx->onError!=OE_None );
  79344. assert( pIdx->autoIndex );
  79345. assert( pIndex->onError!=OE_None );
  79346. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  79347. for(k=0; k<pIdx->nColumn; k++){
  79348. const char *z1;
  79349. const char *z2;
  79350. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  79351. z1 = pIdx->azColl[k];
  79352. z2 = pIndex->azColl[k];
  79353. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  79354. }
  79355. if( k==pIdx->nColumn ){
  79356. if( pIdx->onError!=pIndex->onError ){
  79357. /* This constraint creates the same index as a previous
  79358. ** constraint specified somewhere in the CREATE TABLE statement.
  79359. ** However the ON CONFLICT clauses are different. If both this
  79360. ** constraint and the previous equivalent constraint have explicit
  79361. ** ON CONFLICT clauses this is an error. Otherwise, use the
  79362. ** explicitly specified behavior for the index.
  79363. */
  79364. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  79365. sqlite3ErrorMsg(pParse,
  79366. "conflicting ON CONFLICT clauses specified", 0);
  79367. }
  79368. if( pIdx->onError==OE_Default ){
  79369. pIdx->onError = pIndex->onError;
  79370. }
  79371. }
  79372. goto exit_create_index;
  79373. }
  79374. }
  79375. }
  79376. /* Link the new Index structure to its table and to the other
  79377. ** in-memory database structures.
  79378. */
  79379. if( db->init.busy ){
  79380. Index *p;
  79381. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  79382. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  79383. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  79384. pIndex);
  79385. if( p ){
  79386. assert( p==pIndex ); /* Malloc must have failed */
  79387. db->mallocFailed = 1;
  79388. goto exit_create_index;
  79389. }
  79390. db->flags |= SQLITE_InternChanges;
  79391. if( pTblName!=0 ){
  79392. pIndex->tnum = db->init.newTnum;
  79393. }
  79394. }
  79395. /* If the db->init.busy is 0 then create the index on disk. This
  79396. ** involves writing the index into the master table and filling in the
  79397. ** index with the current table contents.
  79398. **
  79399. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  79400. ** command. db->init.busy is 1 when a database is opened and
  79401. ** CREATE INDEX statements are read out of the master table. In
  79402. ** the latter case the index already exists on disk, which is why
  79403. ** we don't want to recreate it.
  79404. **
  79405. ** If pTblName==0 it means this index is generated as a primary key
  79406. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  79407. ** has just been created, it contains no data and the index initialization
  79408. ** step can be skipped.
  79409. */
  79410. else{ /* if( db->init.busy==0 ) */
  79411. Vdbe *v;
  79412. char *zStmt;
  79413. int iMem = ++pParse->nMem;
  79414. v = sqlite3GetVdbe(pParse);
  79415. if( v==0 ) goto exit_create_index;
  79416. /* Create the rootpage for the index
  79417. */
  79418. sqlite3BeginWriteOperation(pParse, 1, iDb);
  79419. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  79420. /* Gather the complete text of the CREATE INDEX statement into
  79421. ** the zStmt variable
  79422. */
  79423. if( pStart ){
  79424. assert( pEnd!=0 );
  79425. /* A named index with an explicit CREATE INDEX statement */
  79426. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  79427. onError==OE_None ? "" : " UNIQUE",
  79428. (int)(pEnd->z - pName->z) + 1,
  79429. pName->z);
  79430. }else{
  79431. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  79432. /* zStmt = sqlite3MPrintf(""); */
  79433. zStmt = 0;
  79434. }
  79435. /* Add an entry in sqlite_master for this index
  79436. */
  79437. sqlite3NestedParse(pParse,
  79438. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  79439. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  79440. pIndex->zName,
  79441. pTab->zName,
  79442. iMem,
  79443. zStmt
  79444. );
  79445. sqlite3DbFree(db, zStmt);
  79446. /* Fill the index with data and reparse the schema. Code an OP_Expire
  79447. ** to invalidate all pre-compiled statements.
  79448. */
  79449. if( pTblName ){
  79450. sqlite3RefillIndex(pParse, pIndex, iMem);
  79451. sqlite3ChangeCookie(pParse, iDb);
  79452. sqlite3VdbeAddParseSchemaOp(v, iDb,
  79453. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  79454. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  79455. }
  79456. }
  79457. /* When adding an index to the list of indices for a table, make
  79458. ** sure all indices labeled OE_Replace come after all those labeled
  79459. ** OE_Ignore. This is necessary for the correct constraint check
  79460. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  79461. ** UPDATE and INSERT statements.
  79462. */
  79463. if( db->init.busy || pTblName==0 ){
  79464. if( onError!=OE_Replace || pTab->pIndex==0
  79465. || pTab->pIndex->onError==OE_Replace){
  79466. pIndex->pNext = pTab->pIndex;
  79467. pTab->pIndex = pIndex;
  79468. }else{
  79469. Index *pOther = pTab->pIndex;
  79470. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  79471. pOther = pOther->pNext;
  79472. }
  79473. pIndex->pNext = pOther->pNext;
  79474. pOther->pNext = pIndex;
  79475. }
  79476. pRet = pIndex;
  79477. pIndex = 0;
  79478. }
  79479. /* Clean up before exiting */
  79480. exit_create_index:
  79481. if( pIndex ){
  79482. sqlite3DbFree(db, pIndex->zColAff);
  79483. sqlite3DbFree(db, pIndex);
  79484. }
  79485. sqlite3ExprListDelete(db, pList);
  79486. sqlite3SrcListDelete(db, pTblName);
  79487. sqlite3DbFree(db, zName);
  79488. return pRet;
  79489. }
  79490. /*
  79491. ** Fill the Index.aiRowEst[] array with default information - information
  79492. ** to be used when we have not run the ANALYZE command.
  79493. **
  79494. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  79495. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  79496. ** number of rows in the table that match any particular value of the
  79497. ** first column of the index. aiRowEst[2] is an estimate of the number
  79498. ** of rows that match any particular combiniation of the first 2 columns
  79499. ** of the index. And so forth. It must always be the case that
  79500. *
  79501. ** aiRowEst[N]<=aiRowEst[N-1]
  79502. ** aiRowEst[N]>=1
  79503. **
  79504. ** Apart from that, we have little to go on besides intuition as to
  79505. ** how aiRowEst[] should be initialized. The numbers generated here
  79506. ** are based on typical values found in actual indices.
  79507. */
  79508. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  79509. tRowcnt *a = pIdx->aiRowEst;
  79510. int i;
  79511. tRowcnt n;
  79512. assert( a!=0 );
  79513. a[0] = pIdx->pTable->nRowEst;
  79514. if( a[0]<10 ) a[0] = 10;
  79515. n = 10;
  79516. for(i=1; i<=pIdx->nColumn; i++){
  79517. a[i] = n;
  79518. if( n>5 ) n--;
  79519. }
  79520. if( pIdx->onError!=OE_None ){
  79521. a[pIdx->nColumn] = 1;
  79522. }
  79523. }
  79524. /*
  79525. ** This routine will drop an existing named index. This routine
  79526. ** implements the DROP INDEX statement.
  79527. */
  79528. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  79529. Index *pIndex;
  79530. Vdbe *v;
  79531. sqlite3 *db = pParse->db;
  79532. int iDb;
  79533. assert( pParse->nErr==0 ); /* Never called with prior errors */
  79534. if( db->mallocFailed ){
  79535. goto exit_drop_index;
  79536. }
  79537. assert( pName->nSrc==1 );
  79538. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  79539. goto exit_drop_index;
  79540. }
  79541. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  79542. if( pIndex==0 ){
  79543. if( !ifExists ){
  79544. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  79545. }else{
  79546. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  79547. }
  79548. pParse->checkSchema = 1;
  79549. goto exit_drop_index;
  79550. }
  79551. if( pIndex->autoIndex ){
  79552. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  79553. "or PRIMARY KEY constraint cannot be dropped", 0);
  79554. goto exit_drop_index;
  79555. }
  79556. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  79557. #ifndef SQLITE_OMIT_AUTHORIZATION
  79558. {
  79559. int code = SQLITE_DROP_INDEX;
  79560. Table *pTab = pIndex->pTable;
  79561. const char *zDb = db->aDb[iDb].zName;
  79562. const char *zTab = SCHEMA_TABLE(iDb);
  79563. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  79564. goto exit_drop_index;
  79565. }
  79566. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  79567. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  79568. goto exit_drop_index;
  79569. }
  79570. }
  79571. #endif
  79572. /* Generate code to remove the index and from the master table */
  79573. v = sqlite3GetVdbe(pParse);
  79574. if( v ){
  79575. sqlite3BeginWriteOperation(pParse, 1, iDb);
  79576. sqlite3NestedParse(pParse,
  79577. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  79578. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  79579. );
  79580. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  79581. sqlite3ChangeCookie(pParse, iDb);
  79582. destroyRootPage(pParse, pIndex->tnum, iDb);
  79583. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  79584. }
  79585. exit_drop_index:
  79586. sqlite3SrcListDelete(db, pName);
  79587. }
  79588. /*
  79589. ** pArray is a pointer to an array of objects. Each object in the
  79590. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  79591. ** to extend the array so that there is space for a new object at the end.
  79592. **
  79593. ** When this function is called, *pnEntry contains the current size of
  79594. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  79595. ** in total).
  79596. **
  79597. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  79598. ** space allocated for the new object is zeroed, *pnEntry updated to
  79599. ** reflect the new size of the array and a pointer to the new allocation
  79600. ** returned. *pIdx is set to the index of the new array entry in this case.
  79601. **
  79602. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  79603. ** unchanged and a copy of pArray returned.
  79604. */
  79605. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  79606. sqlite3 *db, /* Connection to notify of malloc failures */
  79607. void *pArray, /* Array of objects. Might be reallocated */
  79608. int szEntry, /* Size of each object in the array */
  79609. int *pnEntry, /* Number of objects currently in use */
  79610. int *pIdx /* Write the index of a new slot here */
  79611. ){
  79612. char *z;
  79613. int n = *pnEntry;
  79614. if( (n & (n-1))==0 ){
  79615. int sz = (n==0) ? 1 : 2*n;
  79616. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  79617. if( pNew==0 ){
  79618. *pIdx = -1;
  79619. return pArray;
  79620. }
  79621. pArray = pNew;
  79622. }
  79623. z = (char*)pArray;
  79624. memset(&z[n * szEntry], 0, szEntry);
  79625. *pIdx = n;
  79626. ++*pnEntry;
  79627. return pArray;
  79628. }
  79629. /*
  79630. ** Append a new element to the given IdList. Create a new IdList if
  79631. ** need be.
  79632. **
  79633. ** A new IdList is returned, or NULL if malloc() fails.
  79634. */
  79635. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  79636. int i;
  79637. if( pList==0 ){
  79638. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  79639. if( pList==0 ) return 0;
  79640. }
  79641. pList->a = sqlite3ArrayAllocate(
  79642. db,
  79643. pList->a,
  79644. sizeof(pList->a[0]),
  79645. &pList->nId,
  79646. &i
  79647. );
  79648. if( i<0 ){
  79649. sqlite3IdListDelete(db, pList);
  79650. return 0;
  79651. }
  79652. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  79653. return pList;
  79654. }
  79655. /*
  79656. ** Delete an IdList.
  79657. */
  79658. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  79659. int i;
  79660. if( pList==0 ) return;
  79661. for(i=0; i<pList->nId; i++){
  79662. sqlite3DbFree(db, pList->a[i].zName);
  79663. }
  79664. sqlite3DbFree(db, pList->a);
  79665. sqlite3DbFree(db, pList);
  79666. }
  79667. /*
  79668. ** Return the index in pList of the identifier named zId. Return -1
  79669. ** if not found.
  79670. */
  79671. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  79672. int i;
  79673. if( pList==0 ) return -1;
  79674. for(i=0; i<pList->nId; i++){
  79675. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  79676. }
  79677. return -1;
  79678. }
  79679. /*
  79680. ** Expand the space allocated for the given SrcList object by
  79681. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  79682. ** New slots are zeroed.
  79683. **
  79684. ** For example, suppose a SrcList initially contains two entries: A,B.
  79685. ** To append 3 new entries onto the end, do this:
  79686. **
  79687. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  79688. **
  79689. ** After the call above it would contain: A, B, nil, nil, nil.
  79690. ** If the iStart argument had been 1 instead of 2, then the result
  79691. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  79692. ** the iStart value would be 0. The result then would
  79693. ** be: nil, nil, nil, A, B.
  79694. **
  79695. ** If a memory allocation fails the SrcList is unchanged. The
  79696. ** db->mallocFailed flag will be set to true.
  79697. */
  79698. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  79699. sqlite3 *db, /* Database connection to notify of OOM errors */
  79700. SrcList *pSrc, /* The SrcList to be enlarged */
  79701. int nExtra, /* Number of new slots to add to pSrc->a[] */
  79702. int iStart /* Index in pSrc->a[] of first new slot */
  79703. ){
  79704. int i;
  79705. /* Sanity checking on calling parameters */
  79706. assert( iStart>=0 );
  79707. assert( nExtra>=1 );
  79708. assert( pSrc!=0 );
  79709. assert( iStart<=pSrc->nSrc );
  79710. /* Allocate additional space if needed */
  79711. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  79712. SrcList *pNew;
  79713. int nAlloc = pSrc->nSrc+nExtra;
  79714. int nGot;
  79715. pNew = sqlite3DbRealloc(db, pSrc,
  79716. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  79717. if( pNew==0 ){
  79718. assert( db->mallocFailed );
  79719. return pSrc;
  79720. }
  79721. pSrc = pNew;
  79722. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  79723. pSrc->nAlloc = (u16)nGot;
  79724. }
  79725. /* Move existing slots that come after the newly inserted slots
  79726. ** out of the way */
  79727. for(i=pSrc->nSrc-1; i>=iStart; i--){
  79728. pSrc->a[i+nExtra] = pSrc->a[i];
  79729. }
  79730. pSrc->nSrc += (i16)nExtra;
  79731. /* Zero the newly allocated slots */
  79732. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  79733. for(i=iStart; i<iStart+nExtra; i++){
  79734. pSrc->a[i].iCursor = -1;
  79735. }
  79736. /* Return a pointer to the enlarged SrcList */
  79737. return pSrc;
  79738. }
  79739. /*
  79740. ** Append a new table name to the given SrcList. Create a new SrcList if
  79741. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  79742. **
  79743. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  79744. ** SrcList might be the same as the SrcList that was input or it might be
  79745. ** a new one. If an OOM error does occurs, then the prior value of pList
  79746. ** that is input to this routine is automatically freed.
  79747. **
  79748. ** If pDatabase is not null, it means that the table has an optional
  79749. ** database name prefix. Like this: "database.table". The pDatabase
  79750. ** points to the table name and the pTable points to the database name.
  79751. ** The SrcList.a[].zName field is filled with the table name which might
  79752. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  79753. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  79754. ** or with NULL if no database is specified.
  79755. **
  79756. ** In other words, if call like this:
  79757. **
  79758. ** sqlite3SrcListAppend(D,A,B,0);
  79759. **
  79760. ** Then B is a table name and the database name is unspecified. If called
  79761. ** like this:
  79762. **
  79763. ** sqlite3SrcListAppend(D,A,B,C);
  79764. **
  79765. ** Then C is the table name and B is the database name. If C is defined
  79766. ** then so is B. In other words, we never have a case where:
  79767. **
  79768. ** sqlite3SrcListAppend(D,A,0,C);
  79769. **
  79770. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  79771. ** before being added to the SrcList.
  79772. */
  79773. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  79774. sqlite3 *db, /* Connection to notify of malloc failures */
  79775. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  79776. Token *pTable, /* Table to append */
  79777. Token *pDatabase /* Database of the table */
  79778. ){
  79779. struct SrcList_item *pItem;
  79780. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  79781. if( pList==0 ){
  79782. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  79783. if( pList==0 ) return 0;
  79784. pList->nAlloc = 1;
  79785. }
  79786. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  79787. if( db->mallocFailed ){
  79788. sqlite3SrcListDelete(db, pList);
  79789. return 0;
  79790. }
  79791. pItem = &pList->a[pList->nSrc-1];
  79792. if( pDatabase && pDatabase->z==0 ){
  79793. pDatabase = 0;
  79794. }
  79795. if( pDatabase ){
  79796. Token *pTemp = pDatabase;
  79797. pDatabase = pTable;
  79798. pTable = pTemp;
  79799. }
  79800. pItem->zName = sqlite3NameFromToken(db, pTable);
  79801. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  79802. return pList;
  79803. }
  79804. /*
  79805. ** Assign VdbeCursor index numbers to all tables in a SrcList
  79806. */
  79807. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  79808. int i;
  79809. struct SrcList_item *pItem;
  79810. assert(pList || pParse->db->mallocFailed );
  79811. if( pList ){
  79812. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  79813. if( pItem->iCursor>=0 ) break;
  79814. pItem->iCursor = pParse->nTab++;
  79815. if( pItem->pSelect ){
  79816. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  79817. }
  79818. }
  79819. }
  79820. }
  79821. /*
  79822. ** Delete an entire SrcList including all its substructure.
  79823. */
  79824. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  79825. int i;
  79826. struct SrcList_item *pItem;
  79827. if( pList==0 ) return;
  79828. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  79829. sqlite3DbFree(db, pItem->zDatabase);
  79830. sqlite3DbFree(db, pItem->zName);
  79831. sqlite3DbFree(db, pItem->zAlias);
  79832. sqlite3DbFree(db, pItem->zIndex);
  79833. sqlite3DeleteTable(db, pItem->pTab);
  79834. sqlite3SelectDelete(db, pItem->pSelect);
  79835. sqlite3ExprDelete(db, pItem->pOn);
  79836. sqlite3IdListDelete(db, pItem->pUsing);
  79837. }
  79838. sqlite3DbFree(db, pList);
  79839. }
  79840. /*
  79841. ** This routine is called by the parser to add a new term to the
  79842. ** end of a growing FROM clause. The "p" parameter is the part of
  79843. ** the FROM clause that has already been constructed. "p" is NULL
  79844. ** if this is the first term of the FROM clause. pTable and pDatabase
  79845. ** are the name of the table and database named in the FROM clause term.
  79846. ** pDatabase is NULL if the database name qualifier is missing - the
  79847. ** usual case. If the term has a alias, then pAlias points to the
  79848. ** alias token. If the term is a subquery, then pSubquery is the
  79849. ** SELECT statement that the subquery encodes. The pTable and
  79850. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  79851. ** parameters are the content of the ON and USING clauses.
  79852. **
  79853. ** Return a new SrcList which encodes is the FROM with the new
  79854. ** term added.
  79855. */
  79856. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  79857. Parse *pParse, /* Parsing context */
  79858. SrcList *p, /* The left part of the FROM clause already seen */
  79859. Token *pTable, /* Name of the table to add to the FROM clause */
  79860. Token *pDatabase, /* Name of the database containing pTable */
  79861. Token *pAlias, /* The right-hand side of the AS subexpression */
  79862. Select *pSubquery, /* A subquery used in place of a table name */
  79863. Expr *pOn, /* The ON clause of a join */
  79864. IdList *pUsing /* The USING clause of a join */
  79865. ){
  79866. struct SrcList_item *pItem;
  79867. sqlite3 *db = pParse->db;
  79868. if( !p && (pOn || pUsing) ){
  79869. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  79870. (pOn ? "ON" : "USING")
  79871. );
  79872. goto append_from_error;
  79873. }
  79874. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  79875. if( p==0 || NEVER(p->nSrc==0) ){
  79876. goto append_from_error;
  79877. }
  79878. pItem = &p->a[p->nSrc-1];
  79879. assert( pAlias!=0 );
  79880. if( pAlias->n ){
  79881. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  79882. }
  79883. pItem->pSelect = pSubquery;
  79884. pItem->pOn = pOn;
  79885. pItem->pUsing = pUsing;
  79886. return p;
  79887. append_from_error:
  79888. assert( p==0 );
  79889. sqlite3ExprDelete(db, pOn);
  79890. sqlite3IdListDelete(db, pUsing);
  79891. sqlite3SelectDelete(db, pSubquery);
  79892. return 0;
  79893. }
  79894. /*
  79895. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  79896. ** element of the source-list passed as the second argument.
  79897. */
  79898. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  79899. assert( pIndexedBy!=0 );
  79900. if( p && ALWAYS(p->nSrc>0) ){
  79901. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  79902. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  79903. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  79904. /* A "NOT INDEXED" clause was supplied. See parse.y
  79905. ** construct "indexed_opt" for details. */
  79906. pItem->notIndexed = 1;
  79907. }else{
  79908. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  79909. }
  79910. }
  79911. }
  79912. /*
  79913. ** When building up a FROM clause in the parser, the join operator
  79914. ** is initially attached to the left operand. But the code generator
  79915. ** expects the join operator to be on the right operand. This routine
  79916. ** Shifts all join operators from left to right for an entire FROM
  79917. ** clause.
  79918. **
  79919. ** Example: Suppose the join is like this:
  79920. **
  79921. ** A natural cross join B
  79922. **
  79923. ** The operator is "natural cross join". The A and B operands are stored
  79924. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  79925. ** operator with A. This routine shifts that operator over to B.
  79926. */
  79927. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  79928. if( p ){
  79929. int i;
  79930. assert( p->a || p->nSrc==0 );
  79931. for(i=p->nSrc-1; i>0; i--){
  79932. p->a[i].jointype = p->a[i-1].jointype;
  79933. }
  79934. p->a[0].jointype = 0;
  79935. }
  79936. }
  79937. /*
  79938. ** Begin a transaction
  79939. */
  79940. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  79941. sqlite3 *db;
  79942. Vdbe *v;
  79943. int i;
  79944. assert( pParse!=0 );
  79945. db = pParse->db;
  79946. assert( db!=0 );
  79947. /* if( db->aDb[0].pBt==0 ) return; */
  79948. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  79949. return;
  79950. }
  79951. v = sqlite3GetVdbe(pParse);
  79952. if( !v ) return;
  79953. if( type!=TK_DEFERRED ){
  79954. for(i=0; i<db->nDb; i++){
  79955. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  79956. sqlite3VdbeUsesBtree(v, i);
  79957. }
  79958. }
  79959. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  79960. }
  79961. /*
  79962. ** Commit a transaction
  79963. */
  79964. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  79965. Vdbe *v;
  79966. assert( pParse!=0 );
  79967. assert( pParse->db!=0 );
  79968. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  79969. return;
  79970. }
  79971. v = sqlite3GetVdbe(pParse);
  79972. if( v ){
  79973. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  79974. }
  79975. }
  79976. /*
  79977. ** Rollback a transaction
  79978. */
  79979. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  79980. Vdbe *v;
  79981. assert( pParse!=0 );
  79982. assert( pParse->db!=0 );
  79983. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  79984. return;
  79985. }
  79986. v = sqlite3GetVdbe(pParse);
  79987. if( v ){
  79988. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  79989. }
  79990. }
  79991. /*
  79992. ** This function is called by the parser when it parses a command to create,
  79993. ** release or rollback an SQL savepoint.
  79994. */
  79995. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  79996. char *zName = sqlite3NameFromToken(pParse->db, pName);
  79997. if( zName ){
  79998. Vdbe *v = sqlite3GetVdbe(pParse);
  79999. #ifndef SQLITE_OMIT_AUTHORIZATION
  80000. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  80001. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  80002. #endif
  80003. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  80004. sqlite3DbFree(pParse->db, zName);
  80005. return;
  80006. }
  80007. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  80008. }
  80009. }
  80010. /*
  80011. ** Make sure the TEMP database is open and available for use. Return
  80012. ** the number of errors. Leave any error messages in the pParse structure.
  80013. */
  80014. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  80015. sqlite3 *db = pParse->db;
  80016. if( db->aDb[1].pBt==0 && !pParse->explain ){
  80017. int rc;
  80018. Btree *pBt;
  80019. static const int flags =
  80020. SQLITE_OPEN_READWRITE |
  80021. SQLITE_OPEN_CREATE |
  80022. SQLITE_OPEN_EXCLUSIVE |
  80023. SQLITE_OPEN_DELETEONCLOSE |
  80024. SQLITE_OPEN_TEMP_DB;
  80025. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  80026. if( rc!=SQLITE_OK ){
  80027. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  80028. "file for storing temporary tables");
  80029. pParse->rc = rc;
  80030. return 1;
  80031. }
  80032. db->aDb[1].pBt = pBt;
  80033. assert( db->aDb[1].pSchema );
  80034. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  80035. db->mallocFailed = 1;
  80036. return 1;
  80037. }
  80038. }
  80039. return 0;
  80040. }
  80041. /*
  80042. ** Generate VDBE code that will verify the schema cookie and start
  80043. ** a read-transaction for all named database files.
  80044. **
  80045. ** It is important that all schema cookies be verified and all
  80046. ** read transactions be started before anything else happens in
  80047. ** the VDBE program. But this routine can be called after much other
  80048. ** code has been generated. So here is what we do:
  80049. **
  80050. ** The first time this routine is called, we code an OP_Goto that
  80051. ** will jump to a subroutine at the end of the program. Then we
  80052. ** record every database that needs its schema verified in the
  80053. ** pParse->cookieMask field. Later, after all other code has been
  80054. ** generated, the subroutine that does the cookie verifications and
  80055. ** starts the transactions will be coded and the OP_Goto P2 value
  80056. ** will be made to point to that subroutine. The generation of the
  80057. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  80058. **
  80059. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  80060. ** schema on any databases. This can be used to position the OP_Goto
  80061. ** early in the code, before we know if any database tables will be used.
  80062. */
  80063. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  80064. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  80065. #ifndef SQLITE_OMIT_TRIGGER
  80066. if( pToplevel!=pParse ){
  80067. /* This branch is taken if a trigger is currently being coded. In this
  80068. ** case, set cookieGoto to a non-zero value to show that this function
  80069. ** has been called. This is used by the sqlite3ExprCodeConstants()
  80070. ** function. */
  80071. pParse->cookieGoto = -1;
  80072. }
  80073. #endif
  80074. if( pToplevel->cookieGoto==0 ){
  80075. Vdbe *v = sqlite3GetVdbe(pToplevel);
  80076. if( v==0 ) return; /* This only happens if there was a prior error */
  80077. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  80078. }
  80079. if( iDb>=0 ){
  80080. sqlite3 *db = pToplevel->db;
  80081. yDbMask mask;
  80082. assert( iDb<db->nDb );
  80083. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  80084. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  80085. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80086. mask = ((yDbMask)1)<<iDb;
  80087. if( (pToplevel->cookieMask & mask)==0 ){
  80088. pToplevel->cookieMask |= mask;
  80089. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  80090. if( !OMIT_TEMPDB && iDb==1 ){
  80091. sqlite3OpenTempDatabase(pToplevel);
  80092. }
  80093. }
  80094. }
  80095. }
  80096. /*
  80097. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  80098. ** attached database. Otherwise, invoke it for the database named zDb only.
  80099. */
  80100. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  80101. sqlite3 *db = pParse->db;
  80102. int i;
  80103. for(i=0; i<db->nDb; i++){
  80104. Db *pDb = &db->aDb[i];
  80105. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  80106. sqlite3CodeVerifySchema(pParse, i);
  80107. }
  80108. }
  80109. }
  80110. /*
  80111. ** Generate VDBE code that prepares for doing an operation that
  80112. ** might change the database.
  80113. **
  80114. ** This routine starts a new transaction if we are not already within
  80115. ** a transaction. If we are already within a transaction, then a checkpoint
  80116. ** is set if the setStatement parameter is true. A checkpoint should
  80117. ** be set for operations that might fail (due to a constraint) part of
  80118. ** the way through and which will need to undo some writes without having to
  80119. ** rollback the whole transaction. For operations where all constraints
  80120. ** can be checked before any changes are made to the database, it is never
  80121. ** necessary to undo a write and the checkpoint should not be set.
  80122. */
  80123. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  80124. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  80125. sqlite3CodeVerifySchema(pParse, iDb);
  80126. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  80127. pToplevel->isMultiWrite |= setStatement;
  80128. }
  80129. /*
  80130. ** Indicate that the statement currently under construction might write
  80131. ** more than one entry (example: deleting one row then inserting another,
  80132. ** inserting multiple rows in a table, or inserting a row and index entries.)
  80133. ** If an abort occurs after some of these writes have completed, then it will
  80134. ** be necessary to undo the completed writes.
  80135. */
  80136. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  80137. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  80138. pToplevel->isMultiWrite = 1;
  80139. }
  80140. /*
  80141. ** The code generator calls this routine if is discovers that it is
  80142. ** possible to abort a statement prior to completion. In order to
  80143. ** perform this abort without corrupting the database, we need to make
  80144. ** sure that the statement is protected by a statement transaction.
  80145. **
  80146. ** Technically, we only need to set the mayAbort flag if the
  80147. ** isMultiWrite flag was previously set. There is a time dependency
  80148. ** such that the abort must occur after the multiwrite. This makes
  80149. ** some statements involving the REPLACE conflict resolution algorithm
  80150. ** go a little faster. But taking advantage of this time dependency
  80151. ** makes it more difficult to prove that the code is correct (in
  80152. ** particular, it prevents us from writing an effective
  80153. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  80154. ** to take the safe route and skip the optimization.
  80155. */
  80156. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  80157. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  80158. pToplevel->mayAbort = 1;
  80159. }
  80160. /*
  80161. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  80162. ** error. The onError parameter determines which (if any) of the statement
  80163. ** and/or current transaction is rolled back.
  80164. */
  80165. SQLITE_PRIVATE void sqlite3HaltConstraint(
  80166. Parse *pParse, /* Parsing context */
  80167. int errCode, /* extended error code */
  80168. int onError, /* Constraint type */
  80169. char *p4, /* Error message */
  80170. int p4type /* P4_STATIC or P4_TRANSIENT */
  80171. ){
  80172. Vdbe *v = sqlite3GetVdbe(pParse);
  80173. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  80174. if( onError==OE_Abort ){
  80175. sqlite3MayAbort(pParse);
  80176. }
  80177. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  80178. }
  80179. /*
  80180. ** Check to see if pIndex uses the collating sequence pColl. Return
  80181. ** true if it does and false if it does not.
  80182. */
  80183. #ifndef SQLITE_OMIT_REINDEX
  80184. static int collationMatch(const char *zColl, Index *pIndex){
  80185. int i;
  80186. assert( zColl!=0 );
  80187. for(i=0; i<pIndex->nColumn; i++){
  80188. const char *z = pIndex->azColl[i];
  80189. assert( z!=0 );
  80190. if( 0==sqlite3StrICmp(z, zColl) ){
  80191. return 1;
  80192. }
  80193. }
  80194. return 0;
  80195. }
  80196. #endif
  80197. /*
  80198. ** Recompute all indices of pTab that use the collating sequence pColl.
  80199. ** If pColl==0 then recompute all indices of pTab.
  80200. */
  80201. #ifndef SQLITE_OMIT_REINDEX
  80202. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  80203. Index *pIndex; /* An index associated with pTab */
  80204. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  80205. if( zColl==0 || collationMatch(zColl, pIndex) ){
  80206. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80207. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80208. sqlite3RefillIndex(pParse, pIndex, -1);
  80209. }
  80210. }
  80211. }
  80212. #endif
  80213. /*
  80214. ** Recompute all indices of all tables in all databases where the
  80215. ** indices use the collating sequence pColl. If pColl==0 then recompute
  80216. ** all indices everywhere.
  80217. */
  80218. #ifndef SQLITE_OMIT_REINDEX
  80219. static void reindexDatabases(Parse *pParse, char const *zColl){
  80220. Db *pDb; /* A single database */
  80221. int iDb; /* The database index number */
  80222. sqlite3 *db = pParse->db; /* The database connection */
  80223. HashElem *k; /* For looping over tables in pDb */
  80224. Table *pTab; /* A table in the database */
  80225. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  80226. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  80227. assert( pDb!=0 );
  80228. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  80229. pTab = (Table*)sqliteHashData(k);
  80230. reindexTable(pParse, pTab, zColl);
  80231. }
  80232. }
  80233. }
  80234. #endif
  80235. /*
  80236. ** Generate code for the REINDEX command.
  80237. **
  80238. ** REINDEX -- 1
  80239. ** REINDEX <collation> -- 2
  80240. ** REINDEX ?<database>.?<tablename> -- 3
  80241. ** REINDEX ?<database>.?<indexname> -- 4
  80242. **
  80243. ** Form 1 causes all indices in all attached databases to be rebuilt.
  80244. ** Form 2 rebuilds all indices in all databases that use the named
  80245. ** collating function. Forms 3 and 4 rebuild the named index or all
  80246. ** indices associated with the named table.
  80247. */
  80248. #ifndef SQLITE_OMIT_REINDEX
  80249. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  80250. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  80251. char *z; /* Name of a table or index */
  80252. const char *zDb; /* Name of the database */
  80253. Table *pTab; /* A table in the database */
  80254. Index *pIndex; /* An index associated with pTab */
  80255. int iDb; /* The database index number */
  80256. sqlite3 *db = pParse->db; /* The database connection */
  80257. Token *pObjName; /* Name of the table or index to be reindexed */
  80258. /* Read the database schema. If an error occurs, leave an error message
  80259. ** and code in pParse and return NULL. */
  80260. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  80261. return;
  80262. }
  80263. if( pName1==0 ){
  80264. reindexDatabases(pParse, 0);
  80265. return;
  80266. }else if( NEVER(pName2==0) || pName2->z==0 ){
  80267. char *zColl;
  80268. assert( pName1->z );
  80269. zColl = sqlite3NameFromToken(pParse->db, pName1);
  80270. if( !zColl ) return;
  80271. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  80272. if( pColl ){
  80273. reindexDatabases(pParse, zColl);
  80274. sqlite3DbFree(db, zColl);
  80275. return;
  80276. }
  80277. sqlite3DbFree(db, zColl);
  80278. }
  80279. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  80280. if( iDb<0 ) return;
  80281. z = sqlite3NameFromToken(db, pObjName);
  80282. if( z==0 ) return;
  80283. zDb = db->aDb[iDb].zName;
  80284. pTab = sqlite3FindTable(db, z, zDb);
  80285. if( pTab ){
  80286. reindexTable(pParse, pTab, 0);
  80287. sqlite3DbFree(db, z);
  80288. return;
  80289. }
  80290. pIndex = sqlite3FindIndex(db, z, zDb);
  80291. sqlite3DbFree(db, z);
  80292. if( pIndex ){
  80293. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80294. sqlite3RefillIndex(pParse, pIndex, -1);
  80295. return;
  80296. }
  80297. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  80298. }
  80299. #endif
  80300. /*
  80301. ** Return a dynamicly allocated KeyInfo structure that can be used
  80302. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  80303. **
  80304. ** If successful, a pointer to the new structure is returned. In this case
  80305. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  80306. ** pointer. If an error occurs (out of memory or missing collation
  80307. ** sequence), NULL is returned and the state of pParse updated to reflect
  80308. ** the error.
  80309. */
  80310. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  80311. int i;
  80312. int nCol = pIdx->nColumn;
  80313. int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  80314. sqlite3 *db = pParse->db;
  80315. KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  80316. if( pKey ){
  80317. pKey->db = pParse->db;
  80318. pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  80319. assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  80320. for(i=0; i<nCol; i++){
  80321. char *zColl = pIdx->azColl[i];
  80322. assert( zColl );
  80323. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  80324. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  80325. }
  80326. pKey->nField = (u16)nCol;
  80327. }
  80328. if( pParse->nErr ){
  80329. sqlite3DbFree(db, pKey);
  80330. pKey = 0;
  80331. }
  80332. return pKey;
  80333. }
  80334. /************** End of build.c ***********************************************/
  80335. /************** Begin file callback.c ****************************************/
  80336. /*
  80337. ** 2005 May 23
  80338. **
  80339. ** The author disclaims copyright to this source code. In place of
  80340. ** a legal notice, here is a blessing:
  80341. **
  80342. ** May you do good and not evil.
  80343. ** May you find forgiveness for yourself and forgive others.
  80344. ** May you share freely, never taking more than you give.
  80345. **
  80346. *************************************************************************
  80347. **
  80348. ** This file contains functions used to access the internal hash tables
  80349. ** of user defined functions and collation sequences.
  80350. */
  80351. /*
  80352. ** Invoke the 'collation needed' callback to request a collation sequence
  80353. ** in the encoding enc of name zName, length nName.
  80354. */
  80355. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  80356. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  80357. if( db->xCollNeeded ){
  80358. char *zExternal = sqlite3DbStrDup(db, zName);
  80359. if( !zExternal ) return;
  80360. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  80361. sqlite3DbFree(db, zExternal);
  80362. }
  80363. #ifndef SQLITE_OMIT_UTF16
  80364. if( db->xCollNeeded16 ){
  80365. char const *zExternal;
  80366. sqlite3_value *pTmp = sqlite3ValueNew(db);
  80367. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  80368. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  80369. if( zExternal ){
  80370. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  80371. }
  80372. sqlite3ValueFree(pTmp);
  80373. }
  80374. #endif
  80375. }
  80376. /*
  80377. ** This routine is called if the collation factory fails to deliver a
  80378. ** collation function in the best encoding but there may be other versions
  80379. ** of this collation function (for other text encodings) available. Use one
  80380. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  80381. ** possible.
  80382. */
  80383. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  80384. CollSeq *pColl2;
  80385. char *z = pColl->zName;
  80386. int i;
  80387. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  80388. for(i=0; i<3; i++){
  80389. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  80390. if( pColl2->xCmp!=0 ){
  80391. memcpy(pColl, pColl2, sizeof(CollSeq));
  80392. pColl->xDel = 0; /* Do not copy the destructor */
  80393. return SQLITE_OK;
  80394. }
  80395. }
  80396. return SQLITE_ERROR;
  80397. }
  80398. /*
  80399. ** This function is responsible for invoking the collation factory callback
  80400. ** or substituting a collation sequence of a different encoding when the
  80401. ** requested collation sequence is not available in the desired encoding.
  80402. **
  80403. ** If it is not NULL, then pColl must point to the database native encoding
  80404. ** collation sequence with name zName, length nName.
  80405. **
  80406. ** The return value is either the collation sequence to be used in database
  80407. ** db for collation type name zName, length nName, or NULL, if no collation
  80408. ** sequence can be found. If no collation is found, leave an error message.
  80409. **
  80410. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  80411. */
  80412. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  80413. Parse *pParse, /* Parsing context */
  80414. u8 enc, /* The desired encoding for the collating sequence */
  80415. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  80416. const char *zName /* Collating sequence name */
  80417. ){
  80418. CollSeq *p;
  80419. sqlite3 *db = pParse->db;
  80420. p = pColl;
  80421. if( !p ){
  80422. p = sqlite3FindCollSeq(db, enc, zName, 0);
  80423. }
  80424. if( !p || !p->xCmp ){
  80425. /* No collation sequence of this type for this encoding is registered.
  80426. ** Call the collation factory to see if it can supply us with one.
  80427. */
  80428. callCollNeeded(db, enc, zName);
  80429. p = sqlite3FindCollSeq(db, enc, zName, 0);
  80430. }
  80431. if( p && !p->xCmp && synthCollSeq(db, p) ){
  80432. p = 0;
  80433. }
  80434. assert( !p || p->xCmp );
  80435. if( p==0 ){
  80436. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  80437. }
  80438. return p;
  80439. }
  80440. /*
  80441. ** This routine is called on a collation sequence before it is used to
  80442. ** check that it is defined. An undefined collation sequence exists when
  80443. ** a database is loaded that contains references to collation sequences
  80444. ** that have not been defined by sqlite3_create_collation() etc.
  80445. **
  80446. ** If required, this routine calls the 'collation needed' callback to
  80447. ** request a definition of the collating sequence. If this doesn't work,
  80448. ** an equivalent collating sequence that uses a text encoding different
  80449. ** from the main database is substituted, if one is available.
  80450. */
  80451. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  80452. if( pColl ){
  80453. const char *zName = pColl->zName;
  80454. sqlite3 *db = pParse->db;
  80455. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  80456. if( !p ){
  80457. return SQLITE_ERROR;
  80458. }
  80459. assert( p==pColl );
  80460. }
  80461. return SQLITE_OK;
  80462. }
  80463. /*
  80464. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  80465. ** specified by zName and nName is not found and parameter 'create' is
  80466. ** true, then create a new entry. Otherwise return NULL.
  80467. **
  80468. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  80469. ** array of three CollSeq structures. The first is the collation sequence
  80470. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  80471. **
  80472. ** Stored immediately after the three collation sequences is a copy of
  80473. ** the collation sequence name. A pointer to this string is stored in
  80474. ** each collation sequence structure.
  80475. */
  80476. static CollSeq *findCollSeqEntry(
  80477. sqlite3 *db, /* Database connection */
  80478. const char *zName, /* Name of the collating sequence */
  80479. int create /* Create a new entry if true */
  80480. ){
  80481. CollSeq *pColl;
  80482. int nName = sqlite3Strlen30(zName);
  80483. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  80484. if( 0==pColl && create ){
  80485. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  80486. if( pColl ){
  80487. CollSeq *pDel = 0;
  80488. pColl[0].zName = (char*)&pColl[3];
  80489. pColl[0].enc = SQLITE_UTF8;
  80490. pColl[1].zName = (char*)&pColl[3];
  80491. pColl[1].enc = SQLITE_UTF16LE;
  80492. pColl[2].zName = (char*)&pColl[3];
  80493. pColl[2].enc = SQLITE_UTF16BE;
  80494. memcpy(pColl[0].zName, zName, nName);
  80495. pColl[0].zName[nName] = 0;
  80496. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  80497. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  80498. ** return the pColl pointer to be deleted (because it wasn't added
  80499. ** to the hash table).
  80500. */
  80501. assert( pDel==0 || pDel==pColl );
  80502. if( pDel!=0 ){
  80503. db->mallocFailed = 1;
  80504. sqlite3DbFree(db, pDel);
  80505. pColl = 0;
  80506. }
  80507. }
  80508. }
  80509. return pColl;
  80510. }
  80511. /*
  80512. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  80513. ** Return the CollSeq* pointer for the collation sequence named zName
  80514. ** for the encoding 'enc' from the database 'db'.
  80515. **
  80516. ** If the entry specified is not found and 'create' is true, then create a
  80517. ** new entry. Otherwise return NULL.
  80518. **
  80519. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  80520. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  80521. ** if necessary and generates an error message if the collating sequence
  80522. ** cannot be found.
  80523. **
  80524. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  80525. */
  80526. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  80527. sqlite3 *db,
  80528. u8 enc,
  80529. const char *zName,
  80530. int create
  80531. ){
  80532. CollSeq *pColl;
  80533. if( zName ){
  80534. pColl = findCollSeqEntry(db, zName, create);
  80535. }else{
  80536. pColl = db->pDfltColl;
  80537. }
  80538. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  80539. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  80540. if( pColl ) pColl += enc-1;
  80541. return pColl;
  80542. }
  80543. /* During the search for the best function definition, this procedure
  80544. ** is called to test how well the function passed as the first argument
  80545. ** matches the request for a function with nArg arguments in a system
  80546. ** that uses encoding enc. The value returned indicates how well the
  80547. ** request is matched. A higher value indicates a better match.
  80548. **
  80549. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  80550. ** is also -1. In other words, we are searching for a function that
  80551. ** takes a variable number of arguments.
  80552. **
  80553. ** If nArg is -2 that means that we are searching for any function
  80554. ** regardless of the number of arguments it uses, so return a positive
  80555. ** match score for any
  80556. **
  80557. ** The returned value is always between 0 and 6, as follows:
  80558. **
  80559. ** 0: Not a match.
  80560. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  80561. ** 2: UTF16 byte order change required and function takes any number of args.
  80562. ** 3: encoding matches and function takes any number of arguments
  80563. ** 4: UTF8/16 conversion required - argument count matches exactly
  80564. ** 5: UTF16 byte order conversion required - argument count matches exactly
  80565. ** 6: Perfect match: encoding and argument count match exactly.
  80566. **
  80567. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  80568. ** a perfect match and any function with both xStep and xFunc NULL is
  80569. ** a non-match.
  80570. */
  80571. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  80572. static int matchQuality(
  80573. FuncDef *p, /* The function we are evaluating for match quality */
  80574. int nArg, /* Desired number of arguments. (-1)==any */
  80575. u8 enc /* Desired text encoding */
  80576. ){
  80577. int match;
  80578. /* nArg of -2 is a special case */
  80579. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  80580. /* Wrong number of arguments means "no match" */
  80581. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  80582. /* Give a better score to a function with a specific number of arguments
  80583. ** than to function that accepts any number of arguments. */
  80584. if( p->nArg==nArg ){
  80585. match = 4;
  80586. }else{
  80587. match = 1;
  80588. }
  80589. /* Bonus points if the text encoding matches */
  80590. if( enc==p->iPrefEnc ){
  80591. match += 2; /* Exact encoding match */
  80592. }else if( (enc & p->iPrefEnc & 2)!=0 ){
  80593. match += 1; /* Both are UTF16, but with different byte orders */
  80594. }
  80595. return match;
  80596. }
  80597. /*
  80598. ** Search a FuncDefHash for a function with the given name. Return
  80599. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  80600. */
  80601. static FuncDef *functionSearch(
  80602. FuncDefHash *pHash, /* Hash table to search */
  80603. int h, /* Hash of the name */
  80604. const char *zFunc, /* Name of function */
  80605. int nFunc /* Number of bytes in zFunc */
  80606. ){
  80607. FuncDef *p;
  80608. for(p=pHash->a[h]; p; p=p->pHash){
  80609. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  80610. return p;
  80611. }
  80612. }
  80613. return 0;
  80614. }
  80615. /*
  80616. ** Insert a new FuncDef into a FuncDefHash hash table.
  80617. */
  80618. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  80619. FuncDefHash *pHash, /* The hash table into which to insert */
  80620. FuncDef *pDef /* The function definition to insert */
  80621. ){
  80622. FuncDef *pOther;
  80623. int nName = sqlite3Strlen30(pDef->zName);
  80624. u8 c1 = (u8)pDef->zName[0];
  80625. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  80626. pOther = functionSearch(pHash, h, pDef->zName, nName);
  80627. if( pOther ){
  80628. assert( pOther!=pDef && pOther->pNext!=pDef );
  80629. pDef->pNext = pOther->pNext;
  80630. pOther->pNext = pDef;
  80631. }else{
  80632. pDef->pNext = 0;
  80633. pDef->pHash = pHash->a[h];
  80634. pHash->a[h] = pDef;
  80635. }
  80636. }
  80637. /*
  80638. ** Locate a user function given a name, a number of arguments and a flag
  80639. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  80640. ** pointer to the FuncDef structure that defines that function, or return
  80641. ** NULL if the function does not exist.
  80642. **
  80643. ** If the createFlag argument is true, then a new (blank) FuncDef
  80644. ** structure is created and liked into the "db" structure if a
  80645. ** no matching function previously existed.
  80646. **
  80647. ** If nArg is -2, then the first valid function found is returned. A
  80648. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  80649. ** case is used to see if zName is a valid function name for some number
  80650. ** of arguments. If nArg is -2, then createFlag must be 0.
  80651. **
  80652. ** If createFlag is false, then a function with the required name and
  80653. ** number of arguments may be returned even if the eTextRep flag does not
  80654. ** match that requested.
  80655. */
  80656. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  80657. sqlite3 *db, /* An open database */
  80658. const char *zName, /* Name of the function. Not null-terminated */
  80659. int nName, /* Number of characters in the name */
  80660. int nArg, /* Number of arguments. -1 means any number */
  80661. u8 enc, /* Preferred text encoding */
  80662. u8 createFlag /* Create new entry if true and does not otherwise exist */
  80663. ){
  80664. FuncDef *p; /* Iterator variable */
  80665. FuncDef *pBest = 0; /* Best match found so far */
  80666. int bestScore = 0; /* Score of best match */
  80667. int h; /* Hash value */
  80668. assert( nArg>=(-2) );
  80669. assert( nArg>=(-1) || createFlag==0 );
  80670. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  80671. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  80672. /* First search for a match amongst the application-defined functions.
  80673. */
  80674. p = functionSearch(&db->aFunc, h, zName, nName);
  80675. while( p ){
  80676. int score = matchQuality(p, nArg, enc);
  80677. if( score>bestScore ){
  80678. pBest = p;
  80679. bestScore = score;
  80680. }
  80681. p = p->pNext;
  80682. }
  80683. /* If no match is found, search the built-in functions.
  80684. **
  80685. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  80686. ** functions even if a prior app-defined function was found. And give
  80687. ** priority to built-in functions.
  80688. **
  80689. ** Except, if createFlag is true, that means that we are trying to
  80690. ** install a new function. Whatever FuncDef structure is returned it will
  80691. ** have fields overwritten with new information appropriate for the
  80692. ** new function. But the FuncDefs for built-in functions are read-only.
  80693. ** So we must not search for built-ins when creating a new function.
  80694. */
  80695. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  80696. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  80697. bestScore = 0;
  80698. p = functionSearch(pHash, h, zName, nName);
  80699. while( p ){
  80700. int score = matchQuality(p, nArg, enc);
  80701. if( score>bestScore ){
  80702. pBest = p;
  80703. bestScore = score;
  80704. }
  80705. p = p->pNext;
  80706. }
  80707. }
  80708. /* If the createFlag parameter is true and the search did not reveal an
  80709. ** exact match for the name, number of arguments and encoding, then add a
  80710. ** new entry to the hash table and return it.
  80711. */
  80712. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  80713. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  80714. pBest->zName = (char *)&pBest[1];
  80715. pBest->nArg = (u16)nArg;
  80716. pBest->iPrefEnc = enc;
  80717. memcpy(pBest->zName, zName, nName);
  80718. pBest->zName[nName] = 0;
  80719. sqlite3FuncDefInsert(&db->aFunc, pBest);
  80720. }
  80721. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  80722. return pBest;
  80723. }
  80724. return 0;
  80725. }
  80726. /*
  80727. ** Free all resources held by the schema structure. The void* argument points
  80728. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  80729. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  80730. ** of the schema hash tables).
  80731. **
  80732. ** The Schema.cache_size variable is not cleared.
  80733. */
  80734. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  80735. Hash temp1;
  80736. Hash temp2;
  80737. HashElem *pElem;
  80738. Schema *pSchema = (Schema *)p;
  80739. temp1 = pSchema->tblHash;
  80740. temp2 = pSchema->trigHash;
  80741. sqlite3HashInit(&pSchema->trigHash);
  80742. sqlite3HashClear(&pSchema->idxHash);
  80743. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  80744. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  80745. }
  80746. sqlite3HashClear(&temp2);
  80747. sqlite3HashInit(&pSchema->tblHash);
  80748. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  80749. Table *pTab = sqliteHashData(pElem);
  80750. sqlite3DeleteTable(0, pTab);
  80751. }
  80752. sqlite3HashClear(&temp1);
  80753. sqlite3HashClear(&pSchema->fkeyHash);
  80754. pSchema->pSeqTab = 0;
  80755. if( pSchema->flags & DB_SchemaLoaded ){
  80756. pSchema->iGeneration++;
  80757. pSchema->flags &= ~DB_SchemaLoaded;
  80758. }
  80759. }
  80760. /*
  80761. ** Find and return the schema associated with a BTree. Create
  80762. ** a new one if necessary.
  80763. */
  80764. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  80765. Schema * p;
  80766. if( pBt ){
  80767. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  80768. }else{
  80769. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  80770. }
  80771. if( !p ){
  80772. db->mallocFailed = 1;
  80773. }else if ( 0==p->file_format ){
  80774. sqlite3HashInit(&p->tblHash);
  80775. sqlite3HashInit(&p->idxHash);
  80776. sqlite3HashInit(&p->trigHash);
  80777. sqlite3HashInit(&p->fkeyHash);
  80778. p->enc = SQLITE_UTF8;
  80779. }
  80780. return p;
  80781. }
  80782. /************** End of callback.c ********************************************/
  80783. /************** Begin file delete.c ******************************************/
  80784. /*
  80785. ** 2001 September 15
  80786. **
  80787. ** The author disclaims copyright to this source code. In place of
  80788. ** a legal notice, here is a blessing:
  80789. **
  80790. ** May you do good and not evil.
  80791. ** May you find forgiveness for yourself and forgive others.
  80792. ** May you share freely, never taking more than you give.
  80793. **
  80794. *************************************************************************
  80795. ** This file contains C code routines that are called by the parser
  80796. ** in order to generate code for DELETE FROM statements.
  80797. */
  80798. /*
  80799. ** While a SrcList can in general represent multiple tables and subqueries
  80800. ** (as in the FROM clause of a SELECT statement) in this case it contains
  80801. ** the name of a single table, as one might find in an INSERT, DELETE,
  80802. ** or UPDATE statement. Look up that table in the symbol table and
  80803. ** return a pointer. Set an error message and return NULL if the table
  80804. ** name is not found or if any other error occurs.
  80805. **
  80806. ** The following fields are initialized appropriate in pSrc:
  80807. **
  80808. ** pSrc->a[0].pTab Pointer to the Table object
  80809. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  80810. **
  80811. */
  80812. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  80813. struct SrcList_item *pItem = pSrc->a;
  80814. Table *pTab;
  80815. assert( pItem && pSrc->nSrc==1 );
  80816. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  80817. sqlite3DeleteTable(pParse->db, pItem->pTab);
  80818. pItem->pTab = pTab;
  80819. if( pTab ){
  80820. pTab->nRef++;
  80821. }
  80822. if( sqlite3IndexedByLookup(pParse, pItem) ){
  80823. pTab = 0;
  80824. }
  80825. return pTab;
  80826. }
  80827. /*
  80828. ** Check to make sure the given table is writable. If it is not
  80829. ** writable, generate an error message and return 1. If it is
  80830. ** writable return 0;
  80831. */
  80832. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  80833. /* A table is not writable under the following circumstances:
  80834. **
  80835. ** 1) It is a virtual table and no implementation of the xUpdate method
  80836. ** has been provided, or
  80837. ** 2) It is a system table (i.e. sqlite_master), this call is not
  80838. ** part of a nested parse and writable_schema pragma has not
  80839. ** been specified.
  80840. **
  80841. ** In either case leave an error message in pParse and return non-zero.
  80842. */
  80843. if( ( IsVirtual(pTab)
  80844. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  80845. || ( (pTab->tabFlags & TF_Readonly)!=0
  80846. && (pParse->db->flags & SQLITE_WriteSchema)==0
  80847. && pParse->nested==0 )
  80848. ){
  80849. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  80850. return 1;
  80851. }
  80852. #ifndef SQLITE_OMIT_VIEW
  80853. if( !viewOk && pTab->pSelect ){
  80854. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  80855. return 1;
  80856. }
  80857. #endif
  80858. return 0;
  80859. }
  80860. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  80861. /*
  80862. ** Evaluate a view and store its result in an ephemeral table. The
  80863. ** pWhere argument is an optional WHERE clause that restricts the
  80864. ** set of rows in the view that are to be added to the ephemeral table.
  80865. */
  80866. SQLITE_PRIVATE void sqlite3MaterializeView(
  80867. Parse *pParse, /* Parsing context */
  80868. Table *pView, /* View definition */
  80869. Expr *pWhere, /* Optional WHERE clause to be added */
  80870. int iCur /* Cursor number for ephemerial table */
  80871. ){
  80872. SelectDest dest;
  80873. Select *pSel;
  80874. SrcList *pFrom;
  80875. sqlite3 *db = pParse->db;
  80876. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  80877. pWhere = sqlite3ExprDup(db, pWhere, 0);
  80878. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  80879. if( pFrom ){
  80880. assert( pFrom->nSrc==1 );
  80881. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  80882. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  80883. assert( pFrom->a[0].pOn==0 );
  80884. assert( pFrom->a[0].pUsing==0 );
  80885. }
  80886. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  80887. if( pSel ) pSel->selFlags |= SF_Materialize;
  80888. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  80889. sqlite3Select(pParse, pSel, &dest);
  80890. sqlite3SelectDelete(db, pSel);
  80891. }
  80892. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  80893. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  80894. /*
  80895. ** Generate an expression tree to implement the WHERE, ORDER BY,
  80896. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  80897. **
  80898. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  80899. ** \__________________________/
  80900. ** pLimitWhere (pInClause)
  80901. */
  80902. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  80903. Parse *pParse, /* The parser context */
  80904. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  80905. Expr *pWhere, /* The WHERE clause. May be null */
  80906. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  80907. Expr *pLimit, /* The LIMIT clause. May be null */
  80908. Expr *pOffset, /* The OFFSET clause. May be null */
  80909. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  80910. ){
  80911. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  80912. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  80913. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  80914. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  80915. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  80916. Select *pSelect = NULL; /* Complete SELECT tree */
  80917. /* Check that there isn't an ORDER BY without a LIMIT clause.
  80918. */
  80919. if( pOrderBy && (pLimit == 0) ) {
  80920. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  80921. goto limit_where_cleanup_2;
  80922. }
  80923. /* We only need to generate a select expression if there
  80924. ** is a limit/offset term to enforce.
  80925. */
  80926. if( pLimit == 0 ) {
  80927. /* if pLimit is null, pOffset will always be null as well. */
  80928. assert( pOffset == 0 );
  80929. return pWhere;
  80930. }
  80931. /* Generate a select expression tree to enforce the limit/offset
  80932. ** term for the DELETE or UPDATE statement. For example:
  80933. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  80934. ** becomes:
  80935. ** DELETE FROM table_a WHERE rowid IN (
  80936. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  80937. ** );
  80938. */
  80939. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  80940. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  80941. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  80942. if( pEList == 0 ) goto limit_where_cleanup_2;
  80943. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  80944. ** and the SELECT subtree. */
  80945. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  80946. if( pSelectSrc == 0 ) {
  80947. sqlite3ExprListDelete(pParse->db, pEList);
  80948. goto limit_where_cleanup_2;
  80949. }
  80950. /* generate the SELECT expression tree. */
  80951. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  80952. pOrderBy,0,pLimit,pOffset);
  80953. if( pSelect == 0 ) return 0;
  80954. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  80955. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  80956. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  80957. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  80958. if( pInClause == 0 ) goto limit_where_cleanup_1;
  80959. pInClause->x.pSelect = pSelect;
  80960. pInClause->flags |= EP_xIsSelect;
  80961. sqlite3ExprSetHeight(pParse, pInClause);
  80962. return pInClause;
  80963. /* something went wrong. clean up anything allocated. */
  80964. limit_where_cleanup_1:
  80965. sqlite3SelectDelete(pParse->db, pSelect);
  80966. return 0;
  80967. limit_where_cleanup_2:
  80968. sqlite3ExprDelete(pParse->db, pWhere);
  80969. sqlite3ExprListDelete(pParse->db, pOrderBy);
  80970. sqlite3ExprDelete(pParse->db, pLimit);
  80971. sqlite3ExprDelete(pParse->db, pOffset);
  80972. return 0;
  80973. }
  80974. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  80975. /*
  80976. ** Generate code for a DELETE FROM statement.
  80977. **
  80978. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  80979. ** \________/ \________________/
  80980. ** pTabList pWhere
  80981. */
  80982. SQLITE_PRIVATE void sqlite3DeleteFrom(
  80983. Parse *pParse, /* The parser context */
  80984. SrcList *pTabList, /* The table from which we should delete things */
  80985. Expr *pWhere /* The WHERE clause. May be null */
  80986. ){
  80987. Vdbe *v; /* The virtual database engine */
  80988. Table *pTab; /* The table from which records will be deleted */
  80989. const char *zDb; /* Name of database holding pTab */
  80990. int end, addr = 0; /* A couple addresses of generated code */
  80991. int i; /* Loop counter */
  80992. WhereInfo *pWInfo; /* Information about the WHERE clause */
  80993. Index *pIdx; /* For looping over indices of the table */
  80994. int iCur; /* VDBE Cursor number for pTab */
  80995. sqlite3 *db; /* Main database structure */
  80996. AuthContext sContext; /* Authorization context */
  80997. NameContext sNC; /* Name context to resolve expressions in */
  80998. int iDb; /* Database number */
  80999. int memCnt = -1; /* Memory cell used for change counting */
  81000. int rcauth; /* Value returned by authorization callback */
  81001. #ifndef SQLITE_OMIT_TRIGGER
  81002. int isView; /* True if attempting to delete from a view */
  81003. Trigger *pTrigger; /* List of table triggers, if required */
  81004. #endif
  81005. memset(&sContext, 0, sizeof(sContext));
  81006. db = pParse->db;
  81007. if( pParse->nErr || db->mallocFailed ){
  81008. goto delete_from_cleanup;
  81009. }
  81010. assert( pTabList->nSrc==1 );
  81011. /* Locate the table which we want to delete. This table has to be
  81012. ** put in an SrcList structure because some of the subroutines we
  81013. ** will be calling are designed to work with multiple tables and expect
  81014. ** an SrcList* parameter instead of just a Table* parameter.
  81015. */
  81016. pTab = sqlite3SrcListLookup(pParse, pTabList);
  81017. if( pTab==0 ) goto delete_from_cleanup;
  81018. /* Figure out if we have any triggers and if the table being
  81019. ** deleted from is a view
  81020. */
  81021. #ifndef SQLITE_OMIT_TRIGGER
  81022. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  81023. isView = pTab->pSelect!=0;
  81024. #else
  81025. # define pTrigger 0
  81026. # define isView 0
  81027. #endif
  81028. #ifdef SQLITE_OMIT_VIEW
  81029. # undef isView
  81030. # define isView 0
  81031. #endif
  81032. /* If pTab is really a view, make sure it has been initialized.
  81033. */
  81034. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  81035. goto delete_from_cleanup;
  81036. }
  81037. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  81038. goto delete_from_cleanup;
  81039. }
  81040. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81041. assert( iDb<db->nDb );
  81042. zDb = db->aDb[iDb].zName;
  81043. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  81044. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  81045. if( rcauth==SQLITE_DENY ){
  81046. goto delete_from_cleanup;
  81047. }
  81048. assert(!isView || pTrigger);
  81049. /* Assign cursor number to the table and all its indices.
  81050. */
  81051. assert( pTabList->nSrc==1 );
  81052. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  81053. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81054. pParse->nTab++;
  81055. }
  81056. /* Start the view context
  81057. */
  81058. if( isView ){
  81059. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  81060. }
  81061. /* Begin generating code.
  81062. */
  81063. v = sqlite3GetVdbe(pParse);
  81064. if( v==0 ){
  81065. goto delete_from_cleanup;
  81066. }
  81067. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  81068. sqlite3BeginWriteOperation(pParse, 1, iDb);
  81069. /* If we are trying to delete from a view, realize that view into
  81070. ** a ephemeral table.
  81071. */
  81072. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  81073. if( isView ){
  81074. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  81075. }
  81076. #endif
  81077. /* Resolve the column names in the WHERE clause.
  81078. */
  81079. memset(&sNC, 0, sizeof(sNC));
  81080. sNC.pParse = pParse;
  81081. sNC.pSrcList = pTabList;
  81082. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  81083. goto delete_from_cleanup;
  81084. }
  81085. /* Initialize the counter of the number of rows deleted, if
  81086. ** we are counting rows.
  81087. */
  81088. if( db->flags & SQLITE_CountRows ){
  81089. memCnt = ++pParse->nMem;
  81090. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  81091. }
  81092. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  81093. /* Special case: A DELETE without a WHERE clause deletes everything.
  81094. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  81095. ** this optimization caused the row change count (the value returned by
  81096. ** API function sqlite3_count_changes) to be set incorrectly. */
  81097. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  81098. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  81099. ){
  81100. assert( !isView );
  81101. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  81102. pTab->zName, P4_STATIC);
  81103. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81104. assert( pIdx->pSchema==pTab->pSchema );
  81105. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  81106. }
  81107. }else
  81108. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  81109. /* The usual case: There is a WHERE clause so we have to scan through
  81110. ** the table and pick which records to delete.
  81111. */
  81112. {
  81113. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  81114. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  81115. int regRowid; /* Actual register containing rowids */
  81116. /* Collect rowids of every row to be deleted.
  81117. */
  81118. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  81119. pWInfo = sqlite3WhereBegin(
  81120. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  81121. );
  81122. if( pWInfo==0 ) goto delete_from_cleanup;
  81123. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  81124. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  81125. if( db->flags & SQLITE_CountRows ){
  81126. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  81127. }
  81128. sqlite3WhereEnd(pWInfo);
  81129. /* Delete every item whose key was written to the list during the
  81130. ** database scan. We have to delete items after the scan is complete
  81131. ** because deleting an item can change the scan order. */
  81132. end = sqlite3VdbeMakeLabel(v);
  81133. /* Unless this is a view, open cursors for the table we are
  81134. ** deleting from and all its indices. If this is a view, then the
  81135. ** only effect this statement has is to fire the INSTEAD OF
  81136. ** triggers. */
  81137. if( !isView ){
  81138. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  81139. }
  81140. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  81141. /* Delete the row */
  81142. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81143. if( IsVirtual(pTab) ){
  81144. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  81145. sqlite3VtabMakeWritable(pParse, pTab);
  81146. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  81147. sqlite3VdbeChangeP5(v, OE_Abort);
  81148. sqlite3MayAbort(pParse);
  81149. }else
  81150. #endif
  81151. {
  81152. int count = (pParse->nested==0); /* True to count changes */
  81153. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  81154. }
  81155. /* End of the delete loop */
  81156. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  81157. sqlite3VdbeResolveLabel(v, end);
  81158. /* Close the cursors open on the table and its indexes. */
  81159. if( !isView && !IsVirtual(pTab) ){
  81160. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  81161. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  81162. }
  81163. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  81164. }
  81165. }
  81166. /* Update the sqlite_sequence table by storing the content of the
  81167. ** maximum rowid counter values recorded while inserting into
  81168. ** autoincrement tables.
  81169. */
  81170. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  81171. sqlite3AutoincrementEnd(pParse);
  81172. }
  81173. /* Return the number of rows that were deleted. If this routine is
  81174. ** generating code because of a call to sqlite3NestedParse(), do not
  81175. ** invoke the callback function.
  81176. */
  81177. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  81178. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  81179. sqlite3VdbeSetNumCols(v, 1);
  81180. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  81181. }
  81182. delete_from_cleanup:
  81183. sqlite3AuthContextPop(&sContext);
  81184. sqlite3SrcListDelete(db, pTabList);
  81185. sqlite3ExprDelete(db, pWhere);
  81186. return;
  81187. }
  81188. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  81189. ** thely may interfere with compilation of other functions in this file
  81190. ** (or in another file, if this file becomes part of the amalgamation). */
  81191. #ifdef isView
  81192. #undef isView
  81193. #endif
  81194. #ifdef pTrigger
  81195. #undef pTrigger
  81196. #endif
  81197. /*
  81198. ** This routine generates VDBE code that causes a single row of a
  81199. ** single table to be deleted.
  81200. **
  81201. ** The VDBE must be in a particular state when this routine is called.
  81202. ** These are the requirements:
  81203. **
  81204. ** 1. A read/write cursor pointing to pTab, the table containing the row
  81205. ** to be deleted, must be opened as cursor number $iCur.
  81206. **
  81207. ** 2. Read/write cursors for all indices of pTab must be open as
  81208. ** cursor number base+i for the i-th index.
  81209. **
  81210. ** 3. The record number of the row to be deleted must be stored in
  81211. ** memory cell iRowid.
  81212. **
  81213. ** This routine generates code to remove both the table record and all
  81214. ** index entries that point to that record.
  81215. */
  81216. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  81217. Parse *pParse, /* Parsing context */
  81218. Table *pTab, /* Table containing the row to be deleted */
  81219. int iCur, /* Cursor number for the table */
  81220. int iRowid, /* Memory cell that contains the rowid to delete */
  81221. int count, /* If non-zero, increment the row change counter */
  81222. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  81223. int onconf /* Default ON CONFLICT policy for triggers */
  81224. ){
  81225. Vdbe *v = pParse->pVdbe; /* Vdbe */
  81226. int iOld = 0; /* First register in OLD.* array */
  81227. int iLabel; /* Label resolved to end of generated code */
  81228. /* Vdbe is guaranteed to have been allocated by this stage. */
  81229. assert( v );
  81230. /* Seek cursor iCur to the row to delete. If this row no longer exists
  81231. ** (this can happen if a trigger program has already deleted it), do
  81232. ** not attempt to delete it or fire any DELETE triggers. */
  81233. iLabel = sqlite3VdbeMakeLabel(v);
  81234. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  81235. /* If there are any triggers to fire, allocate a range of registers to
  81236. ** use for the old.* references in the triggers. */
  81237. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  81238. u32 mask; /* Mask of OLD.* columns in use */
  81239. int iCol; /* Iterator used while populating OLD.* */
  81240. /* TODO: Could use temporary registers here. Also could attempt to
  81241. ** avoid copying the contents of the rowid register. */
  81242. mask = sqlite3TriggerColmask(
  81243. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  81244. );
  81245. mask |= sqlite3FkOldmask(pParse, pTab);
  81246. iOld = pParse->nMem+1;
  81247. pParse->nMem += (1 + pTab->nCol);
  81248. /* Populate the OLD.* pseudo-table register array. These values will be
  81249. ** used by any BEFORE and AFTER triggers that exist. */
  81250. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  81251. for(iCol=0; iCol<pTab->nCol; iCol++){
  81252. if( mask==0xffffffff || mask&(1<<iCol) ){
  81253. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  81254. }
  81255. }
  81256. /* Invoke BEFORE DELETE trigger programs. */
  81257. sqlite3CodeRowTrigger(pParse, pTrigger,
  81258. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  81259. );
  81260. /* Seek the cursor to the row to be deleted again. It may be that
  81261. ** the BEFORE triggers coded above have already removed the row
  81262. ** being deleted. Do not attempt to delete the row a second time, and
  81263. ** do not fire AFTER triggers. */
  81264. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  81265. /* Do FK processing. This call checks that any FK constraints that
  81266. ** refer to this table (i.e. constraints attached to other tables)
  81267. ** are not violated by deleting this row. */
  81268. sqlite3FkCheck(pParse, pTab, iOld, 0);
  81269. }
  81270. /* Delete the index and table entries. Skip this step if pTab is really
  81271. ** a view (in which case the only effect of the DELETE statement is to
  81272. ** fire the INSTEAD OF triggers). */
  81273. if( pTab->pSelect==0 ){
  81274. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  81275. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  81276. if( count ){
  81277. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  81278. }
  81279. }
  81280. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  81281. ** handle rows (possibly in other tables) that refer via a foreign key
  81282. ** to the row just deleted. */
  81283. sqlite3FkActions(pParse, pTab, 0, iOld);
  81284. /* Invoke AFTER DELETE trigger programs. */
  81285. sqlite3CodeRowTrigger(pParse, pTrigger,
  81286. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  81287. );
  81288. /* Jump here if the row had already been deleted before any BEFORE
  81289. ** trigger programs were invoked. Or if a trigger program throws a
  81290. ** RAISE(IGNORE) exception. */
  81291. sqlite3VdbeResolveLabel(v, iLabel);
  81292. }
  81293. /*
  81294. ** This routine generates VDBE code that causes the deletion of all
  81295. ** index entries associated with a single row of a single table.
  81296. **
  81297. ** The VDBE must be in a particular state when this routine is called.
  81298. ** These are the requirements:
  81299. **
  81300. ** 1. A read/write cursor pointing to pTab, the table containing the row
  81301. ** to be deleted, must be opened as cursor number "iCur".
  81302. **
  81303. ** 2. Read/write cursors for all indices of pTab must be open as
  81304. ** cursor number iCur+i for the i-th index.
  81305. **
  81306. ** 3. The "iCur" cursor must be pointing to the row that is to be
  81307. ** deleted.
  81308. */
  81309. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  81310. Parse *pParse, /* Parsing and code generating context */
  81311. Table *pTab, /* Table containing the row to be deleted */
  81312. int iCur, /* Cursor number for the table */
  81313. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  81314. ){
  81315. int i;
  81316. Index *pIdx;
  81317. int r1;
  81318. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  81319. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  81320. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
  81321. sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  81322. }
  81323. }
  81324. /*
  81325. ** Generate code that will assemble an index key and put it in register
  81326. ** regOut. The key with be for index pIdx which is an index on pTab.
  81327. ** iCur is the index of a cursor open on the pTab table and pointing to
  81328. ** the entry that needs indexing.
  81329. **
  81330. ** Return a register number which is the first in a block of
  81331. ** registers that holds the elements of the index key. The
  81332. ** block of registers has already been deallocated by the time
  81333. ** this routine returns.
  81334. */
  81335. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  81336. Parse *pParse, /* Parsing context */
  81337. Index *pIdx, /* The index for which to generate a key */
  81338. int iCur, /* Cursor number for the pIdx->pTable table */
  81339. int regOut, /* Write the new index key to this register */
  81340. int doMakeRec /* Run the OP_MakeRecord instruction if true */
  81341. ){
  81342. Vdbe *v = pParse->pVdbe;
  81343. int j;
  81344. Table *pTab = pIdx->pTable;
  81345. int regBase;
  81346. int nCol;
  81347. nCol = pIdx->nColumn;
  81348. regBase = sqlite3GetTempRange(pParse, nCol+1);
  81349. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  81350. for(j=0; j<nCol; j++){
  81351. int idx = pIdx->aiColumn[j];
  81352. if( idx==pTab->iPKey ){
  81353. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  81354. }else{
  81355. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  81356. sqlite3ColumnDefault(v, pTab, idx, -1);
  81357. }
  81358. }
  81359. if( doMakeRec ){
  81360. const char *zAff;
  81361. if( pTab->pSelect
  81362. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  81363. ){
  81364. zAff = 0;
  81365. }else{
  81366. zAff = sqlite3IndexAffinityStr(v, pIdx);
  81367. }
  81368. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  81369. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  81370. }
  81371. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  81372. return regBase;
  81373. }
  81374. /************** End of delete.c **********************************************/
  81375. /************** Begin file func.c ********************************************/
  81376. /*
  81377. ** 2002 February 23
  81378. **
  81379. ** The author disclaims copyright to this source code. In place of
  81380. ** a legal notice, here is a blessing:
  81381. **
  81382. ** May you do good and not evil.
  81383. ** May you find forgiveness for yourself and forgive others.
  81384. ** May you share freely, never taking more than you give.
  81385. **
  81386. *************************************************************************
  81387. ** This file contains the C functions that implement various SQL
  81388. ** functions of SQLite.
  81389. **
  81390. ** There is only one exported symbol in this file - the function
  81391. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  81392. ** All other code has file scope.
  81393. */
  81394. /* #include <stdlib.h> */
  81395. /* #include <assert.h> */
  81396. /*
  81397. ** Return the collating function associated with a function.
  81398. */
  81399. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  81400. return context->pColl;
  81401. }
  81402. /*
  81403. ** Indicate that the accumulator load should be skipped on this
  81404. ** iteration of the aggregate loop.
  81405. */
  81406. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  81407. context->skipFlag = 1;
  81408. }
  81409. /*
  81410. ** Implementation of the non-aggregate min() and max() functions
  81411. */
  81412. static void minmaxFunc(
  81413. sqlite3_context *context,
  81414. int argc,
  81415. sqlite3_value **argv
  81416. ){
  81417. int i;
  81418. int mask; /* 0 for min() or 0xffffffff for max() */
  81419. int iBest;
  81420. CollSeq *pColl;
  81421. assert( argc>1 );
  81422. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  81423. pColl = sqlite3GetFuncCollSeq(context);
  81424. assert( pColl );
  81425. assert( mask==-1 || mask==0 );
  81426. iBest = 0;
  81427. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  81428. for(i=1; i<argc; i++){
  81429. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  81430. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  81431. testcase( mask==0 );
  81432. iBest = i;
  81433. }
  81434. }
  81435. sqlite3_result_value(context, argv[iBest]);
  81436. }
  81437. /*
  81438. ** Return the type of the argument.
  81439. */
  81440. static void typeofFunc(
  81441. sqlite3_context *context,
  81442. int NotUsed,
  81443. sqlite3_value **argv
  81444. ){
  81445. const char *z = 0;
  81446. UNUSED_PARAMETER(NotUsed);
  81447. switch( sqlite3_value_type(argv[0]) ){
  81448. case SQLITE_INTEGER: z = "integer"; break;
  81449. case SQLITE_TEXT: z = "text"; break;
  81450. case SQLITE_FLOAT: z = "real"; break;
  81451. case SQLITE_BLOB: z = "blob"; break;
  81452. default: z = "null"; break;
  81453. }
  81454. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  81455. }
  81456. /*
  81457. ** Implementation of the length() function
  81458. */
  81459. static void lengthFunc(
  81460. sqlite3_context *context,
  81461. int argc,
  81462. sqlite3_value **argv
  81463. ){
  81464. int len;
  81465. assert( argc==1 );
  81466. UNUSED_PARAMETER(argc);
  81467. switch( sqlite3_value_type(argv[0]) ){
  81468. case SQLITE_BLOB:
  81469. case SQLITE_INTEGER:
  81470. case SQLITE_FLOAT: {
  81471. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  81472. break;
  81473. }
  81474. case SQLITE_TEXT: {
  81475. const unsigned char *z = sqlite3_value_text(argv[0]);
  81476. if( z==0 ) return;
  81477. len = 0;
  81478. while( *z ){
  81479. len++;
  81480. SQLITE_SKIP_UTF8(z);
  81481. }
  81482. sqlite3_result_int(context, len);
  81483. break;
  81484. }
  81485. default: {
  81486. sqlite3_result_null(context);
  81487. break;
  81488. }
  81489. }
  81490. }
  81491. /*
  81492. ** Implementation of the abs() function.
  81493. **
  81494. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  81495. ** the numeric argument X.
  81496. */
  81497. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  81498. assert( argc==1 );
  81499. UNUSED_PARAMETER(argc);
  81500. switch( sqlite3_value_type(argv[0]) ){
  81501. case SQLITE_INTEGER: {
  81502. i64 iVal = sqlite3_value_int64(argv[0]);
  81503. if( iVal<0 ){
  81504. if( (iVal<<1)==0 ){
  81505. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  81506. ** abs(X) throws an integer overflow error since there is no
  81507. ** equivalent positive 64-bit two complement value. */
  81508. sqlite3_result_error(context, "integer overflow", -1);
  81509. return;
  81510. }
  81511. iVal = -iVal;
  81512. }
  81513. sqlite3_result_int64(context, iVal);
  81514. break;
  81515. }
  81516. case SQLITE_NULL: {
  81517. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  81518. sqlite3_result_null(context);
  81519. break;
  81520. }
  81521. default: {
  81522. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  81523. ** something that can be converted into a number, we have:
  81524. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  81525. ** cannot be converted to a numeric value.
  81526. */
  81527. double rVal = sqlite3_value_double(argv[0]);
  81528. if( rVal<0 ) rVal = -rVal;
  81529. sqlite3_result_double(context, rVal);
  81530. break;
  81531. }
  81532. }
  81533. }
  81534. /*
  81535. ** Implementation of the instr() function.
  81536. **
  81537. ** instr(haystack,needle) finds the first occurrence of needle
  81538. ** in haystack and returns the number of previous characters plus 1,
  81539. ** or 0 if needle does not occur within haystack.
  81540. **
  81541. ** If both haystack and needle are BLOBs, then the result is one more than
  81542. ** the number of bytes in haystack prior to the first occurrence of needle,
  81543. ** or 0 if needle never occurs in haystack.
  81544. */
  81545. static void instrFunc(
  81546. sqlite3_context *context,
  81547. int argc,
  81548. sqlite3_value **argv
  81549. ){
  81550. const unsigned char *zHaystack;
  81551. const unsigned char *zNeedle;
  81552. int nHaystack;
  81553. int nNeedle;
  81554. int typeHaystack, typeNeedle;
  81555. int N = 1;
  81556. int isText;
  81557. UNUSED_PARAMETER(argc);
  81558. typeHaystack = sqlite3_value_type(argv[0]);
  81559. typeNeedle = sqlite3_value_type(argv[1]);
  81560. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  81561. nHaystack = sqlite3_value_bytes(argv[0]);
  81562. nNeedle = sqlite3_value_bytes(argv[1]);
  81563. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  81564. zHaystack = sqlite3_value_blob(argv[0]);
  81565. zNeedle = sqlite3_value_blob(argv[1]);
  81566. isText = 0;
  81567. }else{
  81568. zHaystack = sqlite3_value_text(argv[0]);
  81569. zNeedle = sqlite3_value_text(argv[1]);
  81570. isText = 1;
  81571. }
  81572. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  81573. N++;
  81574. do{
  81575. nHaystack--;
  81576. zHaystack++;
  81577. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  81578. }
  81579. if( nNeedle>nHaystack ) N = 0;
  81580. sqlite3_result_int(context, N);
  81581. }
  81582. /*
  81583. ** Implementation of the substr() function.
  81584. **
  81585. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  81586. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  81587. ** of x. If x is text, then we actually count UTF-8 characters.
  81588. ** If x is a blob, then we count bytes.
  81589. **
  81590. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  81591. **
  81592. ** If p2 is negative, return the p2 characters preceeding p1.
  81593. */
  81594. static void substrFunc(
  81595. sqlite3_context *context,
  81596. int argc,
  81597. sqlite3_value **argv
  81598. ){
  81599. const unsigned char *z;
  81600. const unsigned char *z2;
  81601. int len;
  81602. int p0type;
  81603. i64 p1, p2;
  81604. int negP2 = 0;
  81605. assert( argc==3 || argc==2 );
  81606. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  81607. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  81608. ){
  81609. return;
  81610. }
  81611. p0type = sqlite3_value_type(argv[0]);
  81612. p1 = sqlite3_value_int(argv[1]);
  81613. if( p0type==SQLITE_BLOB ){
  81614. len = sqlite3_value_bytes(argv[0]);
  81615. z = sqlite3_value_blob(argv[0]);
  81616. if( z==0 ) return;
  81617. assert( len==sqlite3_value_bytes(argv[0]) );
  81618. }else{
  81619. z = sqlite3_value_text(argv[0]);
  81620. if( z==0 ) return;
  81621. len = 0;
  81622. if( p1<0 ){
  81623. for(z2=z; *z2; len++){
  81624. SQLITE_SKIP_UTF8(z2);
  81625. }
  81626. }
  81627. }
  81628. if( argc==3 ){
  81629. p2 = sqlite3_value_int(argv[2]);
  81630. if( p2<0 ){
  81631. p2 = -p2;
  81632. negP2 = 1;
  81633. }
  81634. }else{
  81635. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  81636. }
  81637. if( p1<0 ){
  81638. p1 += len;
  81639. if( p1<0 ){
  81640. p2 += p1;
  81641. if( p2<0 ) p2 = 0;
  81642. p1 = 0;
  81643. }
  81644. }else if( p1>0 ){
  81645. p1--;
  81646. }else if( p2>0 ){
  81647. p2--;
  81648. }
  81649. if( negP2 ){
  81650. p1 -= p2;
  81651. if( p1<0 ){
  81652. p2 += p1;
  81653. p1 = 0;
  81654. }
  81655. }
  81656. assert( p1>=0 && p2>=0 );
  81657. if( p0type!=SQLITE_BLOB ){
  81658. while( *z && p1 ){
  81659. SQLITE_SKIP_UTF8(z);
  81660. p1--;
  81661. }
  81662. for(z2=z; *z2 && p2; p2--){
  81663. SQLITE_SKIP_UTF8(z2);
  81664. }
  81665. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  81666. }else{
  81667. if( p1+p2>len ){
  81668. p2 = len-p1;
  81669. if( p2<0 ) p2 = 0;
  81670. }
  81671. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  81672. }
  81673. }
  81674. /*
  81675. ** Implementation of the round() function
  81676. */
  81677. #ifndef SQLITE_OMIT_FLOATING_POINT
  81678. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  81679. int n = 0;
  81680. double r;
  81681. char *zBuf;
  81682. assert( argc==1 || argc==2 );
  81683. if( argc==2 ){
  81684. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  81685. n = sqlite3_value_int(argv[1]);
  81686. if( n>30 ) n = 30;
  81687. if( n<0 ) n = 0;
  81688. }
  81689. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  81690. r = sqlite3_value_double(argv[0]);
  81691. /* If Y==0 and X will fit in a 64-bit int,
  81692. ** handle the rounding directly,
  81693. ** otherwise use printf.
  81694. */
  81695. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  81696. r = (double)((sqlite_int64)(r+0.5));
  81697. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  81698. r = -(double)((sqlite_int64)((-r)+0.5));
  81699. }else{
  81700. zBuf = sqlite3_mprintf("%.*f",n,r);
  81701. if( zBuf==0 ){
  81702. sqlite3_result_error_nomem(context);
  81703. return;
  81704. }
  81705. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  81706. sqlite3_free(zBuf);
  81707. }
  81708. sqlite3_result_double(context, r);
  81709. }
  81710. #endif
  81711. /*
  81712. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  81713. ** allocation fails, call sqlite3_result_error_nomem() to notify
  81714. ** the database handle that malloc() has failed and return NULL.
  81715. ** If nByte is larger than the maximum string or blob length, then
  81716. ** raise an SQLITE_TOOBIG exception and return NULL.
  81717. */
  81718. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  81719. char *z;
  81720. sqlite3 *db = sqlite3_context_db_handle(context);
  81721. assert( nByte>0 );
  81722. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  81723. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  81724. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81725. sqlite3_result_error_toobig(context);
  81726. z = 0;
  81727. }else{
  81728. z = sqlite3Malloc((int)nByte);
  81729. if( !z ){
  81730. sqlite3_result_error_nomem(context);
  81731. }
  81732. }
  81733. return z;
  81734. }
  81735. /*
  81736. ** Implementation of the upper() and lower() SQL functions.
  81737. */
  81738. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  81739. char *z1;
  81740. const char *z2;
  81741. int i, n;
  81742. UNUSED_PARAMETER(argc);
  81743. z2 = (char*)sqlite3_value_text(argv[0]);
  81744. n = sqlite3_value_bytes(argv[0]);
  81745. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  81746. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  81747. if( z2 ){
  81748. z1 = contextMalloc(context, ((i64)n)+1);
  81749. if( z1 ){
  81750. for(i=0; i<n; i++){
  81751. z1[i] = (char)sqlite3Toupper(z2[i]);
  81752. }
  81753. sqlite3_result_text(context, z1, n, sqlite3_free);
  81754. }
  81755. }
  81756. }
  81757. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  81758. char *z1;
  81759. const char *z2;
  81760. int i, n;
  81761. UNUSED_PARAMETER(argc);
  81762. z2 = (char*)sqlite3_value_text(argv[0]);
  81763. n = sqlite3_value_bytes(argv[0]);
  81764. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  81765. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  81766. if( z2 ){
  81767. z1 = contextMalloc(context, ((i64)n)+1);
  81768. if( z1 ){
  81769. for(i=0; i<n; i++){
  81770. z1[i] = sqlite3Tolower(z2[i]);
  81771. }
  81772. sqlite3_result_text(context, z1, n, sqlite3_free);
  81773. }
  81774. }
  81775. }
  81776. /*
  81777. ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
  81778. ** that unused argument values do not have to be computed. However, we
  81779. ** still need some kind of function implementation for this routines in
  81780. ** the function table. That function implementation will never be called
  81781. ** so it doesn't matter what the implementation is. We might as well use
  81782. ** the "version()" function as a substitute.
  81783. */
  81784. #define ifnullFunc versionFunc /* Substitute function - never called */
  81785. /*
  81786. ** Implementation of random(). Return a random integer.
  81787. */
  81788. static void randomFunc(
  81789. sqlite3_context *context,
  81790. int NotUsed,
  81791. sqlite3_value **NotUsed2
  81792. ){
  81793. sqlite_int64 r;
  81794. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  81795. sqlite3_randomness(sizeof(r), &r);
  81796. if( r<0 ){
  81797. /* We need to prevent a random number of 0x8000000000000000
  81798. ** (or -9223372036854775808) since when you do abs() of that
  81799. ** number of you get the same value back again. To do this
  81800. ** in a way that is testable, mask the sign bit off of negative
  81801. ** values, resulting in a positive value. Then take the
  81802. ** 2s complement of that positive value. The end result can
  81803. ** therefore be no less than -9223372036854775807.
  81804. */
  81805. r = -(r & LARGEST_INT64);
  81806. }
  81807. sqlite3_result_int64(context, r);
  81808. }
  81809. /*
  81810. ** Implementation of randomblob(N). Return a random blob
  81811. ** that is N bytes long.
  81812. */
  81813. static void randomBlob(
  81814. sqlite3_context *context,
  81815. int argc,
  81816. sqlite3_value **argv
  81817. ){
  81818. int n;
  81819. unsigned char *p;
  81820. assert( argc==1 );
  81821. UNUSED_PARAMETER(argc);
  81822. n = sqlite3_value_int(argv[0]);
  81823. if( n<1 ){
  81824. n = 1;
  81825. }
  81826. p = contextMalloc(context, n);
  81827. if( p ){
  81828. sqlite3_randomness(n, p);
  81829. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  81830. }
  81831. }
  81832. /*
  81833. ** Implementation of the last_insert_rowid() SQL function. The return
  81834. ** value is the same as the sqlite3_last_insert_rowid() API function.
  81835. */
  81836. static void last_insert_rowid(
  81837. sqlite3_context *context,
  81838. int NotUsed,
  81839. sqlite3_value **NotUsed2
  81840. ){
  81841. sqlite3 *db = sqlite3_context_db_handle(context);
  81842. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  81843. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  81844. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  81845. ** function. */
  81846. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  81847. }
  81848. /*
  81849. ** Implementation of the changes() SQL function.
  81850. **
  81851. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  81852. ** around the sqlite3_changes() C/C++ function and hence follows the same
  81853. ** rules for counting changes.
  81854. */
  81855. static void changes(
  81856. sqlite3_context *context,
  81857. int NotUsed,
  81858. sqlite3_value **NotUsed2
  81859. ){
  81860. sqlite3 *db = sqlite3_context_db_handle(context);
  81861. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  81862. sqlite3_result_int(context, sqlite3_changes(db));
  81863. }
  81864. /*
  81865. ** Implementation of the total_changes() SQL function. The return value is
  81866. ** the same as the sqlite3_total_changes() API function.
  81867. */
  81868. static void total_changes(
  81869. sqlite3_context *context,
  81870. int NotUsed,
  81871. sqlite3_value **NotUsed2
  81872. ){
  81873. sqlite3 *db = sqlite3_context_db_handle(context);
  81874. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  81875. /* IMP: R-52756-41993 This function is a wrapper around the
  81876. ** sqlite3_total_changes() C/C++ interface. */
  81877. sqlite3_result_int(context, sqlite3_total_changes(db));
  81878. }
  81879. /*
  81880. ** A structure defining how to do GLOB-style comparisons.
  81881. */
  81882. struct compareInfo {
  81883. u8 matchAll;
  81884. u8 matchOne;
  81885. u8 matchSet;
  81886. u8 noCase;
  81887. };
  81888. /*
  81889. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  81890. ** character is exactly one byte in size. Also, all characters are
  81891. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  81892. ** whereas only characters less than 0x80 do in ASCII.
  81893. */
  81894. #if defined(SQLITE_EBCDIC)
  81895. # define sqlite3Utf8Read(A) (*((*A)++))
  81896. # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
  81897. #else
  81898. # define GlogUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  81899. #endif
  81900. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  81901. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  81902. ** case. Thus 'a' LIKE 'A' would be true. */
  81903. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  81904. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  81905. ** is case sensitive causing 'a' LIKE 'A' to be false */
  81906. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  81907. /*
  81908. ** Compare two UTF-8 strings for equality where the first string can
  81909. ** potentially be a "glob" expression. Return true (1) if they
  81910. ** are the same and false (0) if they are different.
  81911. **
  81912. ** Globbing rules:
  81913. **
  81914. ** '*' Matches any sequence of zero or more characters.
  81915. **
  81916. ** '?' Matches exactly one character.
  81917. **
  81918. ** [...] Matches one character from the enclosed list of
  81919. ** characters.
  81920. **
  81921. ** [^...] Matches one character not in the enclosed list.
  81922. **
  81923. ** With the [...] and [^...] matching, a ']' character can be included
  81924. ** in the list by making it the first character after '[' or '^'. A
  81925. ** range of characters can be specified using '-'. Example:
  81926. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  81927. ** it the last character in the list.
  81928. **
  81929. ** This routine is usually quick, but can be N**2 in the worst case.
  81930. **
  81931. ** Hints: to match '*' or '?', put them in "[]". Like this:
  81932. **
  81933. ** abc[*]xyz Matches "abc*xyz" only
  81934. */
  81935. static int patternCompare(
  81936. const u8 *zPattern, /* The glob pattern */
  81937. const u8 *zString, /* The string to compare against the glob */
  81938. const struct compareInfo *pInfo, /* Information about how to do the compare */
  81939. u32 esc /* The escape character */
  81940. ){
  81941. u32 c, c2;
  81942. int invert;
  81943. int seen;
  81944. u8 matchOne = pInfo->matchOne;
  81945. u8 matchAll = pInfo->matchAll;
  81946. u8 matchSet = pInfo->matchSet;
  81947. u8 noCase = pInfo->noCase;
  81948. int prevEscape = 0; /* True if the previous character was 'escape' */
  81949. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  81950. if( c==matchAll && !prevEscape ){
  81951. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  81952. || c == matchOne ){
  81953. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  81954. return 0;
  81955. }
  81956. }
  81957. if( c==0 ){
  81958. return 1;
  81959. }else if( c==esc ){
  81960. c = sqlite3Utf8Read(&zPattern);
  81961. if( c==0 ){
  81962. return 0;
  81963. }
  81964. }else if( c==matchSet ){
  81965. assert( esc==0 ); /* This is GLOB, not LIKE */
  81966. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  81967. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  81968. SQLITE_SKIP_UTF8(zString);
  81969. }
  81970. return *zString!=0;
  81971. }
  81972. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  81973. if( noCase ){
  81974. GlogUpperToLower(c2);
  81975. GlogUpperToLower(c);
  81976. while( c2 != 0 && c2 != c ){
  81977. c2 = sqlite3Utf8Read(&zString);
  81978. GlogUpperToLower(c2);
  81979. }
  81980. }else{
  81981. while( c2 != 0 && c2 != c ){
  81982. c2 = sqlite3Utf8Read(&zString);
  81983. }
  81984. }
  81985. if( c2==0 ) return 0;
  81986. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  81987. }
  81988. return 0;
  81989. }else if( c==matchOne && !prevEscape ){
  81990. if( sqlite3Utf8Read(&zString)==0 ){
  81991. return 0;
  81992. }
  81993. }else if( c==matchSet ){
  81994. u32 prior_c = 0;
  81995. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  81996. seen = 0;
  81997. invert = 0;
  81998. c = sqlite3Utf8Read(&zString);
  81999. if( c==0 ) return 0;
  82000. c2 = sqlite3Utf8Read(&zPattern);
  82001. if( c2=='^' ){
  82002. invert = 1;
  82003. c2 = sqlite3Utf8Read(&zPattern);
  82004. }
  82005. if( c2==']' ){
  82006. if( c==']' ) seen = 1;
  82007. c2 = sqlite3Utf8Read(&zPattern);
  82008. }
  82009. while( c2 && c2!=']' ){
  82010. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  82011. c2 = sqlite3Utf8Read(&zPattern);
  82012. if( c>=prior_c && c<=c2 ) seen = 1;
  82013. prior_c = 0;
  82014. }else{
  82015. if( c==c2 ){
  82016. seen = 1;
  82017. }
  82018. prior_c = c2;
  82019. }
  82020. c2 = sqlite3Utf8Read(&zPattern);
  82021. }
  82022. if( c2==0 || (seen ^ invert)==0 ){
  82023. return 0;
  82024. }
  82025. }else if( esc==c && !prevEscape ){
  82026. prevEscape = 1;
  82027. }else{
  82028. c2 = sqlite3Utf8Read(&zString);
  82029. if( noCase ){
  82030. GlogUpperToLower(c);
  82031. GlogUpperToLower(c2);
  82032. }
  82033. if( c!=c2 ){
  82034. return 0;
  82035. }
  82036. prevEscape = 0;
  82037. }
  82038. }
  82039. return *zString==0;
  82040. }
  82041. /*
  82042. ** The sqlite3_strglob() interface.
  82043. */
  82044. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  82045. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  82046. }
  82047. /*
  82048. ** Count the number of times that the LIKE operator (or GLOB which is
  82049. ** just a variation of LIKE) gets called. This is used for testing
  82050. ** only.
  82051. */
  82052. #ifdef SQLITE_TEST
  82053. SQLITE_API int sqlite3_like_count = 0;
  82054. #endif
  82055. /*
  82056. ** Implementation of the like() SQL function. This function implements
  82057. ** the build-in LIKE operator. The first argument to the function is the
  82058. ** pattern and the second argument is the string. So, the SQL statements:
  82059. **
  82060. ** A LIKE B
  82061. **
  82062. ** is implemented as like(B,A).
  82063. **
  82064. ** This same function (with a different compareInfo structure) computes
  82065. ** the GLOB operator.
  82066. */
  82067. static void likeFunc(
  82068. sqlite3_context *context,
  82069. int argc,
  82070. sqlite3_value **argv
  82071. ){
  82072. const unsigned char *zA, *zB;
  82073. u32 escape = 0;
  82074. int nPat;
  82075. sqlite3 *db = sqlite3_context_db_handle(context);
  82076. zB = sqlite3_value_text(argv[0]);
  82077. zA = sqlite3_value_text(argv[1]);
  82078. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  82079. ** of deep recursion and N*N behavior in patternCompare().
  82080. */
  82081. nPat = sqlite3_value_bytes(argv[0]);
  82082. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  82083. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  82084. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  82085. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  82086. return;
  82087. }
  82088. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  82089. if( argc==3 ){
  82090. /* The escape character string must consist of a single UTF-8 character.
  82091. ** Otherwise, return an error.
  82092. */
  82093. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  82094. if( zEsc==0 ) return;
  82095. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  82096. sqlite3_result_error(context,
  82097. "ESCAPE expression must be a single character", -1);
  82098. return;
  82099. }
  82100. escape = sqlite3Utf8Read(&zEsc);
  82101. }
  82102. if( zA && zB ){
  82103. struct compareInfo *pInfo = sqlite3_user_data(context);
  82104. #ifdef SQLITE_TEST
  82105. sqlite3_like_count++;
  82106. #endif
  82107. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  82108. }
  82109. }
  82110. /*
  82111. ** Implementation of the NULLIF(x,y) function. The result is the first
  82112. ** argument if the arguments are different. The result is NULL if the
  82113. ** arguments are equal to each other.
  82114. */
  82115. static void nullifFunc(
  82116. sqlite3_context *context,
  82117. int NotUsed,
  82118. sqlite3_value **argv
  82119. ){
  82120. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  82121. UNUSED_PARAMETER(NotUsed);
  82122. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  82123. sqlite3_result_value(context, argv[0]);
  82124. }
  82125. }
  82126. /*
  82127. ** Implementation of the sqlite_version() function. The result is the version
  82128. ** of the SQLite library that is running.
  82129. */
  82130. static void versionFunc(
  82131. sqlite3_context *context,
  82132. int NotUsed,
  82133. sqlite3_value **NotUsed2
  82134. ){
  82135. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  82136. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  82137. ** sqlite3_libversion() C-interface. */
  82138. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  82139. }
  82140. /*
  82141. ** Implementation of the sqlite_source_id() function. The result is a string
  82142. ** that identifies the particular version of the source code used to build
  82143. ** SQLite.
  82144. */
  82145. static void sourceidFunc(
  82146. sqlite3_context *context,
  82147. int NotUsed,
  82148. sqlite3_value **NotUsed2
  82149. ){
  82150. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  82151. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  82152. ** sqlite3_sourceid() C interface. */
  82153. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  82154. }
  82155. /*
  82156. ** Implementation of the sqlite_log() function. This is a wrapper around
  82157. ** sqlite3_log(). The return value is NULL. The function exists purely for
  82158. ** its side-effects.
  82159. */
  82160. static void errlogFunc(
  82161. sqlite3_context *context,
  82162. int argc,
  82163. sqlite3_value **argv
  82164. ){
  82165. UNUSED_PARAMETER(argc);
  82166. UNUSED_PARAMETER(context);
  82167. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  82168. }
  82169. /*
  82170. ** Implementation of the sqlite_compileoption_used() function.
  82171. ** The result is an integer that identifies if the compiler option
  82172. ** was used to build SQLite.
  82173. */
  82174. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  82175. static void compileoptionusedFunc(
  82176. sqlite3_context *context,
  82177. int argc,
  82178. sqlite3_value **argv
  82179. ){
  82180. const char *zOptName;
  82181. assert( argc==1 );
  82182. UNUSED_PARAMETER(argc);
  82183. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  82184. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  82185. ** function.
  82186. */
  82187. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  82188. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  82189. }
  82190. }
  82191. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  82192. /*
  82193. ** Implementation of the sqlite_compileoption_get() function.
  82194. ** The result is a string that identifies the compiler options
  82195. ** used to build SQLite.
  82196. */
  82197. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  82198. static void compileoptiongetFunc(
  82199. sqlite3_context *context,
  82200. int argc,
  82201. sqlite3_value **argv
  82202. ){
  82203. int n;
  82204. assert( argc==1 );
  82205. UNUSED_PARAMETER(argc);
  82206. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  82207. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  82208. */
  82209. n = sqlite3_value_int(argv[0]);
  82210. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  82211. }
  82212. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  82213. /* Array for converting from half-bytes (nybbles) into ASCII hex
  82214. ** digits. */
  82215. static const char hexdigits[] = {
  82216. '0', '1', '2', '3', '4', '5', '6', '7',
  82217. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  82218. };
  82219. /*
  82220. ** EXPERIMENTAL - This is not an official function. The interface may
  82221. ** change. This function may disappear. Do not write code that depends
  82222. ** on this function.
  82223. **
  82224. ** Implementation of the QUOTE() function. This function takes a single
  82225. ** argument. If the argument is numeric, the return value is the same as
  82226. ** the argument. If the argument is NULL, the return value is the string
  82227. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  82228. ** single-quote escapes.
  82229. */
  82230. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  82231. assert( argc==1 );
  82232. UNUSED_PARAMETER(argc);
  82233. switch( sqlite3_value_type(argv[0]) ){
  82234. case SQLITE_FLOAT: {
  82235. double r1, r2;
  82236. char zBuf[50];
  82237. r1 = sqlite3_value_double(argv[0]);
  82238. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  82239. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  82240. if( r1!=r2 ){
  82241. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  82242. }
  82243. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  82244. break;
  82245. }
  82246. case SQLITE_INTEGER: {
  82247. sqlite3_result_value(context, argv[0]);
  82248. break;
  82249. }
  82250. case SQLITE_BLOB: {
  82251. char *zText = 0;
  82252. char const *zBlob = sqlite3_value_blob(argv[0]);
  82253. int nBlob = sqlite3_value_bytes(argv[0]);
  82254. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  82255. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  82256. if( zText ){
  82257. int i;
  82258. for(i=0; i<nBlob; i++){
  82259. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  82260. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  82261. }
  82262. zText[(nBlob*2)+2] = '\'';
  82263. zText[(nBlob*2)+3] = '\0';
  82264. zText[0] = 'X';
  82265. zText[1] = '\'';
  82266. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  82267. sqlite3_free(zText);
  82268. }
  82269. break;
  82270. }
  82271. case SQLITE_TEXT: {
  82272. int i,j;
  82273. u64 n;
  82274. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  82275. char *z;
  82276. if( zArg==0 ) return;
  82277. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  82278. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  82279. if( z ){
  82280. z[0] = '\'';
  82281. for(i=0, j=1; zArg[i]; i++){
  82282. z[j++] = zArg[i];
  82283. if( zArg[i]=='\'' ){
  82284. z[j++] = '\'';
  82285. }
  82286. }
  82287. z[j++] = '\'';
  82288. z[j] = 0;
  82289. sqlite3_result_text(context, z, j, sqlite3_free);
  82290. }
  82291. break;
  82292. }
  82293. default: {
  82294. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  82295. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  82296. break;
  82297. }
  82298. }
  82299. }
  82300. /*
  82301. ** The unicode() function. Return the integer unicode code-point value
  82302. ** for the first character of the input string.
  82303. */
  82304. static void unicodeFunc(
  82305. sqlite3_context *context,
  82306. int argc,
  82307. sqlite3_value **argv
  82308. ){
  82309. const unsigned char *z = sqlite3_value_text(argv[0]);
  82310. (void)argc;
  82311. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  82312. }
  82313. /*
  82314. ** The char() function takes zero or more arguments, each of which is
  82315. ** an integer. It constructs a string where each character of the string
  82316. ** is the unicode character for the corresponding integer argument.
  82317. */
  82318. static void charFunc(
  82319. sqlite3_context *context,
  82320. int argc,
  82321. sqlite3_value **argv
  82322. ){
  82323. unsigned char *z, *zOut;
  82324. int i;
  82325. zOut = z = sqlite3_malloc( argc*4 );
  82326. if( z==0 ){
  82327. sqlite3_result_error_nomem(context);
  82328. return;
  82329. }
  82330. for(i=0; i<argc; i++){
  82331. sqlite3_int64 x;
  82332. unsigned c;
  82333. x = sqlite3_value_int64(argv[i]);
  82334. if( x<0 || x>0x10ffff ) x = 0xfffd;
  82335. c = (unsigned)(x & 0x1fffff);
  82336. if( c<0x00080 ){
  82337. *zOut++ = (u8)(c&0xFF);
  82338. }else if( c<0x00800 ){
  82339. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  82340. *zOut++ = 0x80 + (u8)(c & 0x3F);
  82341. }else if( c<0x10000 ){
  82342. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  82343. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  82344. *zOut++ = 0x80 + (u8)(c & 0x3F);
  82345. }else{
  82346. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  82347. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  82348. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  82349. *zOut++ = 0x80 + (u8)(c & 0x3F);
  82350. } \
  82351. }
  82352. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  82353. }
  82354. /*
  82355. ** The hex() function. Interpret the argument as a blob. Return
  82356. ** a hexadecimal rendering as text.
  82357. */
  82358. static void hexFunc(
  82359. sqlite3_context *context,
  82360. int argc,
  82361. sqlite3_value **argv
  82362. ){
  82363. int i, n;
  82364. const unsigned char *pBlob;
  82365. char *zHex, *z;
  82366. assert( argc==1 );
  82367. UNUSED_PARAMETER(argc);
  82368. pBlob = sqlite3_value_blob(argv[0]);
  82369. n = sqlite3_value_bytes(argv[0]);
  82370. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  82371. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  82372. if( zHex ){
  82373. for(i=0; i<n; i++, pBlob++){
  82374. unsigned char c = *pBlob;
  82375. *(z++) = hexdigits[(c>>4)&0xf];
  82376. *(z++) = hexdigits[c&0xf];
  82377. }
  82378. *z = 0;
  82379. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  82380. }
  82381. }
  82382. /*
  82383. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  82384. */
  82385. static void zeroblobFunc(
  82386. sqlite3_context *context,
  82387. int argc,
  82388. sqlite3_value **argv
  82389. ){
  82390. i64 n;
  82391. sqlite3 *db = sqlite3_context_db_handle(context);
  82392. assert( argc==1 );
  82393. UNUSED_PARAMETER(argc);
  82394. n = sqlite3_value_int64(argv[0]);
  82395. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  82396. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  82397. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  82398. sqlite3_result_error_toobig(context);
  82399. }else{
  82400. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  82401. }
  82402. }
  82403. /*
  82404. ** The replace() function. Three arguments are all strings: call
  82405. ** them A, B, and C. The result is also a string which is derived
  82406. ** from A by replacing every occurance of B with C. The match
  82407. ** must be exact. Collating sequences are not used.
  82408. */
  82409. static void replaceFunc(
  82410. sqlite3_context *context,
  82411. int argc,
  82412. sqlite3_value **argv
  82413. ){
  82414. const unsigned char *zStr; /* The input string A */
  82415. const unsigned char *zPattern; /* The pattern string B */
  82416. const unsigned char *zRep; /* The replacement string C */
  82417. unsigned char *zOut; /* The output */
  82418. int nStr; /* Size of zStr */
  82419. int nPattern; /* Size of zPattern */
  82420. int nRep; /* Size of zRep */
  82421. i64 nOut; /* Maximum size of zOut */
  82422. int loopLimit; /* Last zStr[] that might match zPattern[] */
  82423. int i, j; /* Loop counters */
  82424. assert( argc==3 );
  82425. UNUSED_PARAMETER(argc);
  82426. zStr = sqlite3_value_text(argv[0]);
  82427. if( zStr==0 ) return;
  82428. nStr = sqlite3_value_bytes(argv[0]);
  82429. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  82430. zPattern = sqlite3_value_text(argv[1]);
  82431. if( zPattern==0 ){
  82432. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  82433. || sqlite3_context_db_handle(context)->mallocFailed );
  82434. return;
  82435. }
  82436. if( zPattern[0]==0 ){
  82437. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  82438. sqlite3_result_value(context, argv[0]);
  82439. return;
  82440. }
  82441. nPattern = sqlite3_value_bytes(argv[1]);
  82442. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  82443. zRep = sqlite3_value_text(argv[2]);
  82444. if( zRep==0 ) return;
  82445. nRep = sqlite3_value_bytes(argv[2]);
  82446. assert( zRep==sqlite3_value_text(argv[2]) );
  82447. nOut = nStr + 1;
  82448. assert( nOut<SQLITE_MAX_LENGTH );
  82449. zOut = contextMalloc(context, (i64)nOut);
  82450. if( zOut==0 ){
  82451. return;
  82452. }
  82453. loopLimit = nStr - nPattern;
  82454. for(i=j=0; i<=loopLimit; i++){
  82455. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  82456. zOut[j++] = zStr[i];
  82457. }else{
  82458. u8 *zOld;
  82459. sqlite3 *db = sqlite3_context_db_handle(context);
  82460. nOut += nRep - nPattern;
  82461. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  82462. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  82463. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  82464. sqlite3_result_error_toobig(context);
  82465. sqlite3_free(zOut);
  82466. return;
  82467. }
  82468. zOld = zOut;
  82469. zOut = sqlite3_realloc(zOut, (int)nOut);
  82470. if( zOut==0 ){
  82471. sqlite3_result_error_nomem(context);
  82472. sqlite3_free(zOld);
  82473. return;
  82474. }
  82475. memcpy(&zOut[j], zRep, nRep);
  82476. j += nRep;
  82477. i += nPattern-1;
  82478. }
  82479. }
  82480. assert( j+nStr-i+1==nOut );
  82481. memcpy(&zOut[j], &zStr[i], nStr-i);
  82482. j += nStr - i;
  82483. assert( j<=nOut );
  82484. zOut[j] = 0;
  82485. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  82486. }
  82487. /*
  82488. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  82489. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  82490. */
  82491. static void trimFunc(
  82492. sqlite3_context *context,
  82493. int argc,
  82494. sqlite3_value **argv
  82495. ){
  82496. const unsigned char *zIn; /* Input string */
  82497. const unsigned char *zCharSet; /* Set of characters to trim */
  82498. int nIn; /* Number of bytes in input */
  82499. int flags; /* 1: trimleft 2: trimright 3: trim */
  82500. int i; /* Loop counter */
  82501. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  82502. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  82503. int nChar; /* Number of characters in zCharSet */
  82504. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  82505. return;
  82506. }
  82507. zIn = sqlite3_value_text(argv[0]);
  82508. if( zIn==0 ) return;
  82509. nIn = sqlite3_value_bytes(argv[0]);
  82510. assert( zIn==sqlite3_value_text(argv[0]) );
  82511. if( argc==1 ){
  82512. static const unsigned char lenOne[] = { 1 };
  82513. static unsigned char * const azOne[] = { (u8*)" " };
  82514. nChar = 1;
  82515. aLen = (u8*)lenOne;
  82516. azChar = (unsigned char **)azOne;
  82517. zCharSet = 0;
  82518. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  82519. return;
  82520. }else{
  82521. const unsigned char *z;
  82522. for(z=zCharSet, nChar=0; *z; nChar++){
  82523. SQLITE_SKIP_UTF8(z);
  82524. }
  82525. if( nChar>0 ){
  82526. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  82527. if( azChar==0 ){
  82528. return;
  82529. }
  82530. aLen = (unsigned char*)&azChar[nChar];
  82531. for(z=zCharSet, nChar=0; *z; nChar++){
  82532. azChar[nChar] = (unsigned char *)z;
  82533. SQLITE_SKIP_UTF8(z);
  82534. aLen[nChar] = (u8)(z - azChar[nChar]);
  82535. }
  82536. }
  82537. }
  82538. if( nChar>0 ){
  82539. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  82540. if( flags & 1 ){
  82541. while( nIn>0 ){
  82542. int len = 0;
  82543. for(i=0; i<nChar; i++){
  82544. len = aLen[i];
  82545. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  82546. }
  82547. if( i>=nChar ) break;
  82548. zIn += len;
  82549. nIn -= len;
  82550. }
  82551. }
  82552. if( flags & 2 ){
  82553. while( nIn>0 ){
  82554. int len = 0;
  82555. for(i=0; i<nChar; i++){
  82556. len = aLen[i];
  82557. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  82558. }
  82559. if( i>=nChar ) break;
  82560. nIn -= len;
  82561. }
  82562. }
  82563. if( zCharSet ){
  82564. sqlite3_free(azChar);
  82565. }
  82566. }
  82567. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  82568. }
  82569. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  82570. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  82571. ** when SQLite is built.
  82572. */
  82573. #ifdef SQLITE_SOUNDEX
  82574. /*
  82575. ** Compute the soundex encoding of a word.
  82576. **
  82577. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  82578. ** soundex encoding of the string X.
  82579. */
  82580. static void soundexFunc(
  82581. sqlite3_context *context,
  82582. int argc,
  82583. sqlite3_value **argv
  82584. ){
  82585. char zResult[8];
  82586. const u8 *zIn;
  82587. int i, j;
  82588. static const unsigned char iCode[] = {
  82589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  82590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  82591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  82592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  82593. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  82594. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  82595. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  82596. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  82597. };
  82598. assert( argc==1 );
  82599. zIn = (u8*)sqlite3_value_text(argv[0]);
  82600. if( zIn==0 ) zIn = (u8*)"";
  82601. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  82602. if( zIn[i] ){
  82603. u8 prevcode = iCode[zIn[i]&0x7f];
  82604. zResult[0] = sqlite3Toupper(zIn[i]);
  82605. for(j=1; j<4 && zIn[i]; i++){
  82606. int code = iCode[zIn[i]&0x7f];
  82607. if( code>0 ){
  82608. if( code!=prevcode ){
  82609. prevcode = code;
  82610. zResult[j++] = code + '0';
  82611. }
  82612. }else{
  82613. prevcode = 0;
  82614. }
  82615. }
  82616. while( j<4 ){
  82617. zResult[j++] = '0';
  82618. }
  82619. zResult[j] = 0;
  82620. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  82621. }else{
  82622. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  82623. ** is NULL or contains no ASCII alphabetic characters. */
  82624. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  82625. }
  82626. }
  82627. #endif /* SQLITE_SOUNDEX */
  82628. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  82629. /*
  82630. ** A function that loads a shared-library extension then returns NULL.
  82631. */
  82632. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  82633. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  82634. const char *zProc;
  82635. sqlite3 *db = sqlite3_context_db_handle(context);
  82636. char *zErrMsg = 0;
  82637. if( argc==2 ){
  82638. zProc = (const char *)sqlite3_value_text(argv[1]);
  82639. }else{
  82640. zProc = 0;
  82641. }
  82642. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  82643. sqlite3_result_error(context, zErrMsg, -1);
  82644. sqlite3_free(zErrMsg);
  82645. }
  82646. }
  82647. #endif
  82648. /*
  82649. ** An instance of the following structure holds the context of a
  82650. ** sum() or avg() aggregate computation.
  82651. */
  82652. typedef struct SumCtx SumCtx;
  82653. struct SumCtx {
  82654. double rSum; /* Floating point sum */
  82655. i64 iSum; /* Integer sum */
  82656. i64 cnt; /* Number of elements summed */
  82657. u8 overflow; /* True if integer overflow seen */
  82658. u8 approx; /* True if non-integer value was input to the sum */
  82659. };
  82660. /*
  82661. ** Routines used to compute the sum, average, and total.
  82662. **
  82663. ** The SUM() function follows the (broken) SQL standard which means
  82664. ** that it returns NULL if it sums over no inputs. TOTAL returns
  82665. ** 0.0 in that case. In addition, TOTAL always returns a float where
  82666. ** SUM might return an integer if it never encounters a floating point
  82667. ** value. TOTAL never fails, but SUM might through an exception if
  82668. ** it overflows an integer.
  82669. */
  82670. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  82671. SumCtx *p;
  82672. int type;
  82673. assert( argc==1 );
  82674. UNUSED_PARAMETER(argc);
  82675. p = sqlite3_aggregate_context(context, sizeof(*p));
  82676. type = sqlite3_value_numeric_type(argv[0]);
  82677. if( p && type!=SQLITE_NULL ){
  82678. p->cnt++;
  82679. if( type==SQLITE_INTEGER ){
  82680. i64 v = sqlite3_value_int64(argv[0]);
  82681. p->rSum += v;
  82682. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  82683. p->overflow = 1;
  82684. }
  82685. }else{
  82686. p->rSum += sqlite3_value_double(argv[0]);
  82687. p->approx = 1;
  82688. }
  82689. }
  82690. }
  82691. static void sumFinalize(sqlite3_context *context){
  82692. SumCtx *p;
  82693. p = sqlite3_aggregate_context(context, 0);
  82694. if( p && p->cnt>0 ){
  82695. if( p->overflow ){
  82696. sqlite3_result_error(context,"integer overflow",-1);
  82697. }else if( p->approx ){
  82698. sqlite3_result_double(context, p->rSum);
  82699. }else{
  82700. sqlite3_result_int64(context, p->iSum);
  82701. }
  82702. }
  82703. }
  82704. static void avgFinalize(sqlite3_context *context){
  82705. SumCtx *p;
  82706. p = sqlite3_aggregate_context(context, 0);
  82707. if( p && p->cnt>0 ){
  82708. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  82709. }
  82710. }
  82711. static void totalFinalize(sqlite3_context *context){
  82712. SumCtx *p;
  82713. p = sqlite3_aggregate_context(context, 0);
  82714. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  82715. sqlite3_result_double(context, p ? p->rSum : (double)0);
  82716. }
  82717. /*
  82718. ** The following structure keeps track of state information for the
  82719. ** count() aggregate function.
  82720. */
  82721. typedef struct CountCtx CountCtx;
  82722. struct CountCtx {
  82723. i64 n;
  82724. };
  82725. /*
  82726. ** Routines to implement the count() aggregate function.
  82727. */
  82728. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  82729. CountCtx *p;
  82730. p = sqlite3_aggregate_context(context, sizeof(*p));
  82731. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  82732. p->n++;
  82733. }
  82734. #ifndef SQLITE_OMIT_DEPRECATED
  82735. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  82736. ** sure it still operates correctly, verify that its count agrees with our
  82737. ** internal count when using count(*) and when the total count can be
  82738. ** expressed as a 32-bit integer. */
  82739. assert( argc==1 || p==0 || p->n>0x7fffffff
  82740. || p->n==sqlite3_aggregate_count(context) );
  82741. #endif
  82742. }
  82743. static void countFinalize(sqlite3_context *context){
  82744. CountCtx *p;
  82745. p = sqlite3_aggregate_context(context, 0);
  82746. sqlite3_result_int64(context, p ? p->n : 0);
  82747. }
  82748. /*
  82749. ** Routines to implement min() and max() aggregate functions.
  82750. */
  82751. static void minmaxStep(
  82752. sqlite3_context *context,
  82753. int NotUsed,
  82754. sqlite3_value **argv
  82755. ){
  82756. Mem *pArg = (Mem *)argv[0];
  82757. Mem *pBest;
  82758. UNUSED_PARAMETER(NotUsed);
  82759. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  82760. if( !pBest ) return;
  82761. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  82762. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  82763. }else if( pBest->flags ){
  82764. int max;
  82765. int cmp;
  82766. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  82767. /* This step function is used for both the min() and max() aggregates,
  82768. ** the only difference between the two being that the sense of the
  82769. ** comparison is inverted. For the max() aggregate, the
  82770. ** sqlite3_user_data() function returns (void *)-1. For min() it
  82771. ** returns (void *)db, where db is the sqlite3* database pointer.
  82772. ** Therefore the next statement sets variable 'max' to 1 for the max()
  82773. ** aggregate, or 0 for min().
  82774. */
  82775. max = sqlite3_user_data(context)!=0;
  82776. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  82777. if( (max && cmp<0) || (!max && cmp>0) ){
  82778. sqlite3VdbeMemCopy(pBest, pArg);
  82779. }else{
  82780. sqlite3SkipAccumulatorLoad(context);
  82781. }
  82782. }else{
  82783. sqlite3VdbeMemCopy(pBest, pArg);
  82784. }
  82785. }
  82786. static void minMaxFinalize(sqlite3_context *context){
  82787. sqlite3_value *pRes;
  82788. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  82789. if( pRes ){
  82790. if( pRes->flags ){
  82791. sqlite3_result_value(context, pRes);
  82792. }
  82793. sqlite3VdbeMemRelease(pRes);
  82794. }
  82795. }
  82796. /*
  82797. ** group_concat(EXPR, ?SEPARATOR?)
  82798. */
  82799. static void groupConcatStep(
  82800. sqlite3_context *context,
  82801. int argc,
  82802. sqlite3_value **argv
  82803. ){
  82804. const char *zVal;
  82805. StrAccum *pAccum;
  82806. const char *zSep;
  82807. int nVal, nSep;
  82808. assert( argc==1 || argc==2 );
  82809. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  82810. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  82811. if( pAccum ){
  82812. sqlite3 *db = sqlite3_context_db_handle(context);
  82813. int firstTerm = pAccum->useMalloc==0;
  82814. pAccum->useMalloc = 2;
  82815. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  82816. if( !firstTerm ){
  82817. if( argc==2 ){
  82818. zSep = (char*)sqlite3_value_text(argv[1]);
  82819. nSep = sqlite3_value_bytes(argv[1]);
  82820. }else{
  82821. zSep = ",";
  82822. nSep = 1;
  82823. }
  82824. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  82825. }
  82826. zVal = (char*)sqlite3_value_text(argv[0]);
  82827. nVal = sqlite3_value_bytes(argv[0]);
  82828. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  82829. }
  82830. }
  82831. static void groupConcatFinalize(sqlite3_context *context){
  82832. StrAccum *pAccum;
  82833. pAccum = sqlite3_aggregate_context(context, 0);
  82834. if( pAccum ){
  82835. if( pAccum->tooBig ){
  82836. sqlite3_result_error_toobig(context);
  82837. }else if( pAccum->mallocFailed ){
  82838. sqlite3_result_error_nomem(context);
  82839. }else{
  82840. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  82841. sqlite3_free);
  82842. }
  82843. }
  82844. }
  82845. /*
  82846. ** This routine does per-connection function registration. Most
  82847. ** of the built-in functions above are part of the global function set.
  82848. ** This routine only deals with those that are not global.
  82849. */
  82850. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  82851. int rc = sqlite3_overload_function(db, "MATCH", 2);
  82852. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  82853. if( rc==SQLITE_NOMEM ){
  82854. db->mallocFailed = 1;
  82855. }
  82856. }
  82857. /*
  82858. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  82859. */
  82860. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  82861. FuncDef *pDef;
  82862. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  82863. 2, SQLITE_UTF8, 0);
  82864. if( ALWAYS(pDef) ){
  82865. pDef->flags = flagVal;
  82866. }
  82867. }
  82868. /*
  82869. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  82870. ** parameter determines whether or not the LIKE operator is case
  82871. ** sensitive. GLOB is always case sensitive.
  82872. */
  82873. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  82874. struct compareInfo *pInfo;
  82875. if( caseSensitive ){
  82876. pInfo = (struct compareInfo*)&likeInfoAlt;
  82877. }else{
  82878. pInfo = (struct compareInfo*)&likeInfoNorm;
  82879. }
  82880. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  82881. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  82882. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  82883. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  82884. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  82885. setLikeOptFlag(db, "like",
  82886. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  82887. }
  82888. /*
  82889. ** pExpr points to an expression which implements a function. If
  82890. ** it is appropriate to apply the LIKE optimization to that function
  82891. ** then set aWc[0] through aWc[2] to the wildcard characters and
  82892. ** return TRUE. If the function is not a LIKE-style function then
  82893. ** return FALSE.
  82894. */
  82895. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  82896. FuncDef *pDef;
  82897. if( pExpr->op!=TK_FUNCTION
  82898. || !pExpr->x.pList
  82899. || pExpr->x.pList->nExpr!=2
  82900. ){
  82901. return 0;
  82902. }
  82903. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  82904. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  82905. sqlite3Strlen30(pExpr->u.zToken),
  82906. 2, SQLITE_UTF8, 0);
  82907. if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  82908. return 0;
  82909. }
  82910. /* The memcpy() statement assumes that the wildcard characters are
  82911. ** the first three statements in the compareInfo structure. The
  82912. ** asserts() that follow verify that assumption
  82913. */
  82914. memcpy(aWc, pDef->pUserData, 3);
  82915. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  82916. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  82917. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  82918. *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  82919. return 1;
  82920. }
  82921. /*
  82922. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  82923. ** to the global function hash table. This occurs at start-time (as
  82924. ** a consequence of calling sqlite3_initialize()).
  82925. **
  82926. ** After this routine runs
  82927. */
  82928. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  82929. /*
  82930. ** The following array holds FuncDef structures for all of the functions
  82931. ** defined in this file.
  82932. **
  82933. ** The array cannot be constant since changes are made to the
  82934. ** FuncDef.pHash elements at start-time. The elements of this array
  82935. ** are read-only after initialization is complete.
  82936. */
  82937. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  82938. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  82939. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  82940. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  82941. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  82942. FUNCTION(trim, 1, 3, 0, trimFunc ),
  82943. FUNCTION(trim, 2, 3, 0, trimFunc ),
  82944. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  82945. FUNCTION(min, 0, 0, 1, 0 ),
  82946. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  82947. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  82948. FUNCTION(max, 0, 1, 1, 0 ),
  82949. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  82950. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  82951. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  82952. FUNCTION(instr, 2, 0, 0, instrFunc ),
  82953. FUNCTION(substr, 2, 0, 0, substrFunc ),
  82954. FUNCTION(substr, 3, 0, 0, substrFunc ),
  82955. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  82956. FUNCTION(char, -1, 0, 0, charFunc ),
  82957. FUNCTION(abs, 1, 0, 0, absFunc ),
  82958. #ifndef SQLITE_OMIT_FLOATING_POINT
  82959. FUNCTION(round, 1, 0, 0, roundFunc ),
  82960. FUNCTION(round, 2, 0, 0, roundFunc ),
  82961. #endif
  82962. FUNCTION(upper, 1, 0, 0, upperFunc ),
  82963. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  82964. FUNCTION(coalesce, 1, 0, 0, 0 ),
  82965. FUNCTION(coalesce, 0, 0, 0, 0 ),
  82966. FUNCTION2(coalesce, -1, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
  82967. FUNCTION(hex, 1, 0, 0, hexFunc ),
  82968. FUNCTION2(ifnull, 2, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
  82969. FUNCTION(random, 0, 0, 0, randomFunc ),
  82970. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  82971. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  82972. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  82973. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  82974. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  82975. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  82976. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  82977. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  82978. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  82979. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  82980. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  82981. FUNCTION(changes, 0, 0, 0, changes ),
  82982. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  82983. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  82984. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  82985. #ifdef SQLITE_SOUNDEX
  82986. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  82987. #endif
  82988. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  82989. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  82990. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  82991. #endif
  82992. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  82993. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  82994. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  82995. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  82996. {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  82997. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  82998. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  82999. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  83000. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  83001. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  83002. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  83003. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  83004. #else
  83005. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  83006. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  83007. #endif
  83008. };
  83009. int i;
  83010. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  83011. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  83012. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  83013. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  83014. }
  83015. sqlite3RegisterDateTimeFunctions();
  83016. #ifndef SQLITE_OMIT_ALTERTABLE
  83017. sqlite3AlterFunctions();
  83018. #endif
  83019. }
  83020. /************** End of func.c ************************************************/
  83021. /************** Begin file fkey.c ********************************************/
  83022. /*
  83023. **
  83024. ** The author disclaims copyright to this source code. In place of
  83025. ** a legal notice, here is a blessing:
  83026. **
  83027. ** May you do good and not evil.
  83028. ** May you find forgiveness for yourself and forgive others.
  83029. ** May you share freely, never taking more than you give.
  83030. **
  83031. *************************************************************************
  83032. ** This file contains code used by the compiler to add foreign key
  83033. ** support to compiled SQL statements.
  83034. */
  83035. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83036. #ifndef SQLITE_OMIT_TRIGGER
  83037. /*
  83038. ** Deferred and Immediate FKs
  83039. ** --------------------------
  83040. **
  83041. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  83042. ** If an immediate foreign key constraint is violated,
  83043. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  83044. ** statement transaction rolled back. If a
  83045. ** deferred foreign key constraint is violated, no action is taken
  83046. ** immediately. However if the application attempts to commit the
  83047. ** transaction before fixing the constraint violation, the attempt fails.
  83048. **
  83049. ** Deferred constraints are implemented using a simple counter associated
  83050. ** with the database handle. The counter is set to zero each time a
  83051. ** database transaction is opened. Each time a statement is executed
  83052. ** that causes a foreign key violation, the counter is incremented. Each
  83053. ** time a statement is executed that removes an existing violation from
  83054. ** the database, the counter is decremented. When the transaction is
  83055. ** committed, the commit fails if the current value of the counter is
  83056. ** greater than zero. This scheme has two big drawbacks:
  83057. **
  83058. ** * When a commit fails due to a deferred foreign key constraint,
  83059. ** there is no way to tell which foreign constraint is not satisfied,
  83060. ** or which row it is not satisfied for.
  83061. **
  83062. ** * If the database contains foreign key violations when the
  83063. ** transaction is opened, this may cause the mechanism to malfunction.
  83064. **
  83065. ** Despite these problems, this approach is adopted as it seems simpler
  83066. ** than the alternatives.
  83067. **
  83068. ** INSERT operations:
  83069. **
  83070. ** I.1) For each FK for which the table is the child table, search
  83071. ** the parent table for a match. If none is found increment the
  83072. ** constraint counter.
  83073. **
  83074. ** I.2) For each FK for which the table is the parent table,
  83075. ** search the child table for rows that correspond to the new
  83076. ** row in the parent table. Decrement the counter for each row
  83077. ** found (as the constraint is now satisfied).
  83078. **
  83079. ** DELETE operations:
  83080. **
  83081. ** D.1) For each FK for which the table is the child table,
  83082. ** search the parent table for a row that corresponds to the
  83083. ** deleted row in the child table. If such a row is not found,
  83084. ** decrement the counter.
  83085. **
  83086. ** D.2) For each FK for which the table is the parent table, search
  83087. ** the child table for rows that correspond to the deleted row
  83088. ** in the parent table. For each found increment the counter.
  83089. **
  83090. ** UPDATE operations:
  83091. **
  83092. ** An UPDATE command requires that all 4 steps above are taken, but only
  83093. ** for FK constraints for which the affected columns are actually
  83094. ** modified (values must be compared at runtime).
  83095. **
  83096. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  83097. ** This simplifies the implementation a bit.
  83098. **
  83099. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  83100. ** resolution is considered to delete rows before the new row is inserted.
  83101. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  83102. ** is thrown, even if the FK constraint would be satisfied after the new
  83103. ** row is inserted.
  83104. **
  83105. ** Immediate constraints are usually handled similarly. The only difference
  83106. ** is that the counter used is stored as part of each individual statement
  83107. ** object (struct Vdbe). If, after the statement has run, its immediate
  83108. ** constraint counter is greater than zero,
  83109. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  83110. ** and the statement transaction is rolled back. An exception is an INSERT
  83111. ** statement that inserts a single row only (no triggers). In this case,
  83112. ** instead of using a counter, an exception is thrown immediately if the
  83113. ** INSERT violates a foreign key constraint. This is necessary as such
  83114. ** an INSERT does not open a statement transaction.
  83115. **
  83116. ** TODO: How should dropping a table be handled? How should renaming a
  83117. ** table be handled?
  83118. **
  83119. **
  83120. ** Query API Notes
  83121. ** ---------------
  83122. **
  83123. ** Before coding an UPDATE or DELETE row operation, the code-generator
  83124. ** for those two operations needs to know whether or not the operation
  83125. ** requires any FK processing and, if so, which columns of the original
  83126. ** row are required by the FK processing VDBE code (i.e. if FKs were
  83127. ** implemented using triggers, which of the old.* columns would be
  83128. ** accessed). No information is required by the code-generator before
  83129. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  83130. ** generation code to query for this information are:
  83131. **
  83132. ** sqlite3FkRequired() - Test to see if FK processing is required.
  83133. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  83134. **
  83135. **
  83136. ** Externally accessible module functions
  83137. ** --------------------------------------
  83138. **
  83139. ** sqlite3FkCheck() - Check for foreign key violations.
  83140. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  83141. ** sqlite3FkDelete() - Delete an FKey structure.
  83142. */
  83143. /*
  83144. ** VDBE Calling Convention
  83145. ** -----------------------
  83146. **
  83147. ** Example:
  83148. **
  83149. ** For the following INSERT statement:
  83150. **
  83151. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  83152. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  83153. **
  83154. ** Register (x): 2 (type integer)
  83155. ** Register (x+1): 1 (type integer)
  83156. ** Register (x+2): NULL (type NULL)
  83157. ** Register (x+3): 3.1 (type real)
  83158. */
  83159. /*
  83160. ** A foreign key constraint requires that the key columns in the parent
  83161. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  83162. ** Given that pParent is the parent table for foreign key constraint pFKey,
  83163. ** search the schema for a unique index on the parent key columns.
  83164. **
  83165. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  83166. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  83167. ** is set to point to the unique index.
  83168. **
  83169. ** If the parent key consists of a single column (the foreign key constraint
  83170. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  83171. ** Otherwise, it is set to point to an allocated array of size N, where
  83172. ** N is the number of columns in the parent key. The first element of the
  83173. ** array is the index of the child table column that is mapped by the FK
  83174. ** constraint to the parent table column stored in the left-most column
  83175. ** of index *ppIdx. The second element of the array is the index of the
  83176. ** child table column that corresponds to the second left-most column of
  83177. ** *ppIdx, and so on.
  83178. **
  83179. ** If the required index cannot be found, either because:
  83180. **
  83181. ** 1) The named parent key columns do not exist, or
  83182. **
  83183. ** 2) The named parent key columns do exist, but are not subject to a
  83184. ** UNIQUE or PRIMARY KEY constraint, or
  83185. **
  83186. ** 3) No parent key columns were provided explicitly as part of the
  83187. ** foreign key definition, and the parent table does not have a
  83188. ** PRIMARY KEY, or
  83189. **
  83190. ** 4) No parent key columns were provided explicitly as part of the
  83191. ** foreign key definition, and the PRIMARY KEY of the parent table
  83192. ** consists of a a different number of columns to the child key in
  83193. ** the child table.
  83194. **
  83195. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  83196. ** into pParse. If an OOM error occurs, non-zero is returned and the
  83197. ** pParse->db->mallocFailed flag is set.
  83198. */
  83199. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  83200. Parse *pParse, /* Parse context to store any error in */
  83201. Table *pParent, /* Parent table of FK constraint pFKey */
  83202. FKey *pFKey, /* Foreign key to find index for */
  83203. Index **ppIdx, /* OUT: Unique index on parent table */
  83204. int **paiCol /* OUT: Map of index columns in pFKey */
  83205. ){
  83206. Index *pIdx = 0; /* Value to return via *ppIdx */
  83207. int *aiCol = 0; /* Value to return via *paiCol */
  83208. int nCol = pFKey->nCol; /* Number of columns in parent key */
  83209. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  83210. /* The caller is responsible for zeroing output parameters. */
  83211. assert( ppIdx && *ppIdx==0 );
  83212. assert( !paiCol || *paiCol==0 );
  83213. assert( pParse );
  83214. /* If this is a non-composite (single column) foreign key, check if it
  83215. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  83216. ** and *paiCol set to zero and return early.
  83217. **
  83218. ** Otherwise, for a composite foreign key (more than one column), allocate
  83219. ** space for the aiCol array (returned via output parameter *paiCol).
  83220. ** Non-composite foreign keys do not require the aiCol array.
  83221. */
  83222. if( nCol==1 ){
  83223. /* The FK maps to the IPK if any of the following are true:
  83224. **
  83225. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  83226. ** mapped to the primary key of table pParent, or
  83227. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  83228. ** PRIMARY KEY.
  83229. */
  83230. if( pParent->iPKey>=0 ){
  83231. if( !zKey ) return 0;
  83232. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  83233. }
  83234. }else if( paiCol ){
  83235. assert( nCol>1 );
  83236. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  83237. if( !aiCol ) return 1;
  83238. *paiCol = aiCol;
  83239. }
  83240. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  83241. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  83242. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  83243. ** of columns. If each indexed column corresponds to a foreign key
  83244. ** column of pFKey, then this index is a winner. */
  83245. if( zKey==0 ){
  83246. /* If zKey is NULL, then this foreign key is implicitly mapped to
  83247. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  83248. ** identified by the test (Index.autoIndex==2). */
  83249. if( pIdx->autoIndex==2 ){
  83250. if( aiCol ){
  83251. int i;
  83252. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  83253. }
  83254. break;
  83255. }
  83256. }else{
  83257. /* If zKey is non-NULL, then this foreign key was declared to
  83258. ** map to an explicit list of columns in table pParent. Check if this
  83259. ** index matches those columns. Also, check that the index uses
  83260. ** the default collation sequences for each column. */
  83261. int i, j;
  83262. for(i=0; i<nCol; i++){
  83263. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  83264. char *zDfltColl; /* Def. collation for column */
  83265. char *zIdxCol; /* Name of indexed column */
  83266. /* If the index uses a collation sequence that is different from
  83267. ** the default collation sequence for the column, this index is
  83268. ** unusable. Bail out early in this case. */
  83269. zDfltColl = pParent->aCol[iCol].zColl;
  83270. if( !zDfltColl ){
  83271. zDfltColl = "BINARY";
  83272. }
  83273. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  83274. zIdxCol = pParent->aCol[iCol].zName;
  83275. for(j=0; j<nCol; j++){
  83276. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  83277. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  83278. break;
  83279. }
  83280. }
  83281. if( j==nCol ) break;
  83282. }
  83283. if( i==nCol ) break; /* pIdx is usable */
  83284. }
  83285. }
  83286. }
  83287. if( !pIdx ){
  83288. if( !pParse->disableTriggers ){
  83289. sqlite3ErrorMsg(pParse,
  83290. "foreign key mismatch - \"%w\" referencing \"%w\"",
  83291. pFKey->pFrom->zName, pFKey->zTo);
  83292. }
  83293. sqlite3DbFree(pParse->db, aiCol);
  83294. return 1;
  83295. }
  83296. *ppIdx = pIdx;
  83297. return 0;
  83298. }
  83299. /*
  83300. ** This function is called when a row is inserted into or deleted from the
  83301. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  83302. ** on the child table of pFKey, this function is invoked twice for each row
  83303. ** affected - once to "delete" the old row, and then again to "insert" the
  83304. ** new row.
  83305. **
  83306. ** Each time it is called, this function generates VDBE code to locate the
  83307. ** row in the parent table that corresponds to the row being inserted into
  83308. ** or deleted from the child table. If the parent row can be found, no
  83309. ** special action is taken. Otherwise, if the parent row can *not* be
  83310. ** found in the parent table:
  83311. **
  83312. ** Operation | FK type | Action taken
  83313. ** --------------------------------------------------------------------------
  83314. ** INSERT immediate Increment the "immediate constraint counter".
  83315. **
  83316. ** DELETE immediate Decrement the "immediate constraint counter".
  83317. **
  83318. ** INSERT deferred Increment the "deferred constraint counter".
  83319. **
  83320. ** DELETE deferred Decrement the "deferred constraint counter".
  83321. **
  83322. ** These operations are identified in the comment at the top of this file
  83323. ** (fkey.c) as "I.1" and "D.1".
  83324. */
  83325. static void fkLookupParent(
  83326. Parse *pParse, /* Parse context */
  83327. int iDb, /* Index of database housing pTab */
  83328. Table *pTab, /* Parent table of FK pFKey */
  83329. Index *pIdx, /* Unique index on parent key columns in pTab */
  83330. FKey *pFKey, /* Foreign key constraint */
  83331. int *aiCol, /* Map from parent key columns to child table columns */
  83332. int regData, /* Address of array containing child table row */
  83333. int nIncr, /* Increment constraint counter by this */
  83334. int isIgnore /* If true, pretend pTab contains all NULL values */
  83335. ){
  83336. int i; /* Iterator variable */
  83337. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  83338. int iCur = pParse->nTab - 1; /* Cursor number to use */
  83339. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  83340. /* If nIncr is less than zero, then check at runtime if there are any
  83341. ** outstanding constraints to resolve. If there are not, there is no need
  83342. ** to check if deleting this row resolves any outstanding violations.
  83343. **
  83344. ** Check if any of the key columns in the child table row are NULL. If
  83345. ** any are, then the constraint is considered satisfied. No need to
  83346. ** search for a matching row in the parent table. */
  83347. if( nIncr<0 ){
  83348. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  83349. }
  83350. for(i=0; i<pFKey->nCol; i++){
  83351. int iReg = aiCol[i] + regData + 1;
  83352. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  83353. }
  83354. if( isIgnore==0 ){
  83355. if( pIdx==0 ){
  83356. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  83357. ** column of the parent table (table pTab). */
  83358. int iMustBeInt; /* Address of MustBeInt instruction */
  83359. int regTemp = sqlite3GetTempReg(pParse);
  83360. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  83361. ** apply the affinity of the parent key). If this fails, then there
  83362. ** is no matching parent key. Before using MustBeInt, make a copy of
  83363. ** the value. Otherwise, the value inserted into the child key column
  83364. ** will have INTEGER affinity applied to it, which may not be correct. */
  83365. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  83366. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  83367. /* If the parent table is the same as the child table, and we are about
  83368. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  83369. ** then check if the row being inserted matches itself. If so, do not
  83370. ** increment the constraint-counter. */
  83371. if( pTab==pFKey->pFrom && nIncr==1 ){
  83372. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  83373. }
  83374. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  83375. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  83376. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  83377. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  83378. sqlite3VdbeJumpHere(v, iMustBeInt);
  83379. sqlite3ReleaseTempReg(pParse, regTemp);
  83380. }else{
  83381. int nCol = pFKey->nCol;
  83382. int regTemp = sqlite3GetTempRange(pParse, nCol);
  83383. int regRec = sqlite3GetTempReg(pParse);
  83384. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  83385. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  83386. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  83387. for(i=0; i<nCol; i++){
  83388. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  83389. }
  83390. /* If the parent table is the same as the child table, and we are about
  83391. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  83392. ** then check if the row being inserted matches itself. If so, do not
  83393. ** increment the constraint-counter.
  83394. **
  83395. ** If any of the parent-key values are NULL, then the row cannot match
  83396. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  83397. ** of the parent-key values are NULL (at this point it is known that
  83398. ** none of the child key values are).
  83399. */
  83400. if( pTab==pFKey->pFrom && nIncr==1 ){
  83401. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  83402. for(i=0; i<nCol; i++){
  83403. int iChild = aiCol[i]+1+regData;
  83404. int iParent = pIdx->aiColumn[i]+1+regData;
  83405. assert( aiCol[i]!=pTab->iPKey );
  83406. if( pIdx->aiColumn[i]==pTab->iPKey ){
  83407. /* The parent key is a composite key that includes the IPK column */
  83408. iParent = regData;
  83409. }
  83410. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  83411. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  83412. }
  83413. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  83414. }
  83415. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  83416. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  83417. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  83418. sqlite3ReleaseTempReg(pParse, regRec);
  83419. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  83420. }
  83421. }
  83422. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  83423. /* Special case: If this is an INSERT statement that will insert exactly
  83424. ** one row into the table, raise a constraint immediately instead of
  83425. ** incrementing a counter. This is necessary as the VM code is being
  83426. ** generated for will not open a statement transaction. */
  83427. assert( nIncr==1 );
  83428. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  83429. OE_Abort, "foreign key constraint failed", P4_STATIC
  83430. );
  83431. }else{
  83432. if( nIncr>0 && pFKey->isDeferred==0 ){
  83433. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  83434. }
  83435. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  83436. }
  83437. sqlite3VdbeResolveLabel(v, iOk);
  83438. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  83439. }
  83440. /*
  83441. ** This function is called to generate code executed when a row is deleted
  83442. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  83443. ** deferred, when a row is inserted into the same table. When generating
  83444. ** code for an SQL UPDATE operation, this function may be called twice -
  83445. ** once to "delete" the old row and once to "insert" the new row.
  83446. **
  83447. ** The code generated by this function scans through the rows in the child
  83448. ** table that correspond to the parent table row being deleted or inserted.
  83449. ** For each child row found, one of the following actions is taken:
  83450. **
  83451. ** Operation | FK type | Action taken
  83452. ** --------------------------------------------------------------------------
  83453. ** DELETE immediate Increment the "immediate constraint counter".
  83454. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  83455. ** throw a "foreign key constraint failed" exception.
  83456. **
  83457. ** INSERT immediate Decrement the "immediate constraint counter".
  83458. **
  83459. ** DELETE deferred Increment the "deferred constraint counter".
  83460. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  83461. ** throw a "foreign key constraint failed" exception.
  83462. **
  83463. ** INSERT deferred Decrement the "deferred constraint counter".
  83464. **
  83465. ** These operations are identified in the comment at the top of this file
  83466. ** (fkey.c) as "I.2" and "D.2".
  83467. */
  83468. static void fkScanChildren(
  83469. Parse *pParse, /* Parse context */
  83470. SrcList *pSrc, /* SrcList containing the table to scan */
  83471. Table *pTab,
  83472. Index *pIdx, /* Foreign key index */
  83473. FKey *pFKey, /* Foreign key relationship */
  83474. int *aiCol, /* Map from pIdx cols to child table cols */
  83475. int regData, /* Referenced table data starts here */
  83476. int nIncr /* Amount to increment deferred counter by */
  83477. ){
  83478. sqlite3 *db = pParse->db; /* Database handle */
  83479. int i; /* Iterator variable */
  83480. Expr *pWhere = 0; /* WHERE clause to scan with */
  83481. NameContext sNameContext; /* Context used to resolve WHERE clause */
  83482. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  83483. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  83484. Vdbe *v = sqlite3GetVdbe(pParse);
  83485. assert( !pIdx || pIdx->pTable==pTab );
  83486. if( nIncr<0 ){
  83487. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  83488. }
  83489. /* Create an Expr object representing an SQL expression like:
  83490. **
  83491. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  83492. **
  83493. ** The collation sequence used for the comparison should be that of
  83494. ** the parent key columns. The affinity of the parent key column should
  83495. ** be applied to each child key value before the comparison takes place.
  83496. */
  83497. for(i=0; i<pFKey->nCol; i++){
  83498. Expr *pLeft; /* Value from parent table row */
  83499. Expr *pRight; /* Column ref to child table */
  83500. Expr *pEq; /* Expression (pLeft = pRight) */
  83501. int iCol; /* Index of column in child table */
  83502. const char *zCol; /* Name of column in child table */
  83503. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  83504. if( pLeft ){
  83505. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  83506. ** expression to the parent key column defaults. */
  83507. if( pIdx ){
  83508. Column *pCol;
  83509. const char *zColl;
  83510. iCol = pIdx->aiColumn[i];
  83511. pCol = &pTab->aCol[iCol];
  83512. if( pTab->iPKey==iCol ) iCol = -1;
  83513. pLeft->iTable = regData+iCol+1;
  83514. pLeft->affinity = pCol->affinity;
  83515. zColl = pCol->zColl;
  83516. if( zColl==0 ) zColl = db->pDfltColl->zName;
  83517. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  83518. }else{
  83519. pLeft->iTable = regData;
  83520. pLeft->affinity = SQLITE_AFF_INTEGER;
  83521. }
  83522. }
  83523. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  83524. assert( iCol>=0 );
  83525. zCol = pFKey->pFrom->aCol[iCol].zName;
  83526. pRight = sqlite3Expr(db, TK_ID, zCol);
  83527. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  83528. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  83529. }
  83530. /* If the child table is the same as the parent table, and this scan
  83531. ** is taking place as part of a DELETE operation (operation D.2), omit the
  83532. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  83533. ** clause, where $rowid is the rowid of the row being deleted. */
  83534. if( pTab==pFKey->pFrom && nIncr>0 ){
  83535. Expr *pEq; /* Expression (pLeft = pRight) */
  83536. Expr *pLeft; /* Value from parent table row */
  83537. Expr *pRight; /* Column ref to child table */
  83538. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  83539. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  83540. if( pLeft && pRight ){
  83541. pLeft->iTable = regData;
  83542. pLeft->affinity = SQLITE_AFF_INTEGER;
  83543. pRight->iTable = pSrc->a[0].iCursor;
  83544. pRight->iColumn = -1;
  83545. }
  83546. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  83547. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  83548. }
  83549. /* Resolve the references in the WHERE clause. */
  83550. memset(&sNameContext, 0, sizeof(NameContext));
  83551. sNameContext.pSrcList = pSrc;
  83552. sNameContext.pParse = pParse;
  83553. sqlite3ResolveExprNames(&sNameContext, pWhere);
  83554. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  83555. ** clause. If the constraint is not deferred, throw an exception for
  83556. ** each row found. Otherwise, for deferred constraints, increment the
  83557. ** deferred constraint counter by nIncr for each row selected. */
  83558. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  83559. if( nIncr>0 && pFKey->isDeferred==0 ){
  83560. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  83561. }
  83562. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  83563. if( pWInfo ){
  83564. sqlite3WhereEnd(pWInfo);
  83565. }
  83566. /* Clean up the WHERE clause constructed above. */
  83567. sqlite3ExprDelete(db, pWhere);
  83568. if( iFkIfZero ){
  83569. sqlite3VdbeJumpHere(v, iFkIfZero);
  83570. }
  83571. }
  83572. /*
  83573. ** This function returns a pointer to the head of a linked list of FK
  83574. ** constraints for which table pTab is the parent table. For example,
  83575. ** given the following schema:
  83576. **
  83577. ** CREATE TABLE t1(a PRIMARY KEY);
  83578. ** CREATE TABLE t2(b REFERENCES t1(a);
  83579. **
  83580. ** Calling this function with table "t1" as an argument returns a pointer
  83581. ** to the FKey structure representing the foreign key constraint on table
  83582. ** "t2". Calling this function with "t2" as the argument would return a
  83583. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  83584. ** table).
  83585. */
  83586. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  83587. int nName = sqlite3Strlen30(pTab->zName);
  83588. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  83589. }
  83590. /*
  83591. ** The second argument is a Trigger structure allocated by the
  83592. ** fkActionTrigger() routine. This function deletes the Trigger structure
  83593. ** and all of its sub-components.
  83594. **
  83595. ** The Trigger structure or any of its sub-components may be allocated from
  83596. ** the lookaside buffer belonging to database handle dbMem.
  83597. */
  83598. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  83599. if( p ){
  83600. TriggerStep *pStep = p->step_list;
  83601. sqlite3ExprDelete(dbMem, pStep->pWhere);
  83602. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  83603. sqlite3SelectDelete(dbMem, pStep->pSelect);
  83604. sqlite3ExprDelete(dbMem, p->pWhen);
  83605. sqlite3DbFree(dbMem, p);
  83606. }
  83607. }
  83608. /*
  83609. ** This function is called to generate code that runs when table pTab is
  83610. ** being dropped from the database. The SrcList passed as the second argument
  83611. ** to this function contains a single entry guaranteed to resolve to
  83612. ** table pTab.
  83613. **
  83614. ** Normally, no code is required. However, if either
  83615. **
  83616. ** (a) The table is the parent table of a FK constraint, or
  83617. ** (b) The table is the child table of a deferred FK constraint and it is
  83618. ** determined at runtime that there are outstanding deferred FK
  83619. ** constraint violations in the database,
  83620. **
  83621. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  83622. ** the table from the database. Triggers are disabled while running this
  83623. ** DELETE, but foreign key actions are not.
  83624. */
  83625. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  83626. sqlite3 *db = pParse->db;
  83627. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  83628. int iSkip = 0;
  83629. Vdbe *v = sqlite3GetVdbe(pParse);
  83630. assert( v ); /* VDBE has already been allocated */
  83631. if( sqlite3FkReferences(pTab)==0 ){
  83632. /* Search for a deferred foreign key constraint for which this table
  83633. ** is the child table. If one cannot be found, return without
  83634. ** generating any VDBE code. If one can be found, then jump over
  83635. ** the entire DELETE if there are no outstanding deferred constraints
  83636. ** when this statement is run. */
  83637. FKey *p;
  83638. for(p=pTab->pFKey; p; p=p->pNextFrom){
  83639. if( p->isDeferred ) break;
  83640. }
  83641. if( !p ) return;
  83642. iSkip = sqlite3VdbeMakeLabel(v);
  83643. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  83644. }
  83645. pParse->disableTriggers = 1;
  83646. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  83647. pParse->disableTriggers = 0;
  83648. /* If the DELETE has generated immediate foreign key constraint
  83649. ** violations, halt the VDBE and return an error at this point, before
  83650. ** any modifications to the schema are made. This is because statement
  83651. ** transactions are not able to rollback schema changes. */
  83652. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  83653. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  83654. OE_Abort, "foreign key constraint failed", P4_STATIC
  83655. );
  83656. if( iSkip ){
  83657. sqlite3VdbeResolveLabel(v, iSkip);
  83658. }
  83659. }
  83660. }
  83661. /*
  83662. ** This function is called when inserting, deleting or updating a row of
  83663. ** table pTab to generate VDBE code to perform foreign key constraint
  83664. ** processing for the operation.
  83665. **
  83666. ** For a DELETE operation, parameter regOld is passed the index of the
  83667. ** first register in an array of (pTab->nCol+1) registers containing the
  83668. ** rowid of the row being deleted, followed by each of the column values
  83669. ** of the row being deleted, from left to right. Parameter regNew is passed
  83670. ** zero in this case.
  83671. **
  83672. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  83673. ** first register of an array of (pTab->nCol+1) registers containing the new
  83674. ** row data.
  83675. **
  83676. ** For an UPDATE operation, this function is called twice. Once before
  83677. ** the original record is deleted from the table using the calling convention
  83678. ** described for DELETE. Then again after the original record is deleted
  83679. ** but before the new record is inserted using the INSERT convention.
  83680. */
  83681. SQLITE_PRIVATE void sqlite3FkCheck(
  83682. Parse *pParse, /* Parse context */
  83683. Table *pTab, /* Row is being deleted from this table */
  83684. int regOld, /* Previous row data is stored here */
  83685. int regNew /* New row data is stored here */
  83686. ){
  83687. sqlite3 *db = pParse->db; /* Database handle */
  83688. FKey *pFKey; /* Used to iterate through FKs */
  83689. int iDb; /* Index of database containing pTab */
  83690. const char *zDb; /* Name of database containing pTab */
  83691. int isIgnoreErrors = pParse->disableTriggers;
  83692. /* Exactly one of regOld and regNew should be non-zero. */
  83693. assert( (regOld==0)!=(regNew==0) );
  83694. /* If foreign-keys are disabled, this function is a no-op. */
  83695. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  83696. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83697. zDb = db->aDb[iDb].zName;
  83698. /* Loop through all the foreign key constraints for which pTab is the
  83699. ** child table (the table that the foreign key definition is part of). */
  83700. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  83701. Table *pTo; /* Parent table of foreign key pFKey */
  83702. Index *pIdx = 0; /* Index on key columns in pTo */
  83703. int *aiFree = 0;
  83704. int *aiCol;
  83705. int iCol;
  83706. int i;
  83707. int isIgnore = 0;
  83708. /* Find the parent table of this foreign key. Also find a unique index
  83709. ** on the parent key columns in the parent table. If either of these
  83710. ** schema items cannot be located, set an error in pParse and return
  83711. ** early. */
  83712. if( pParse->disableTriggers ){
  83713. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  83714. }else{
  83715. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  83716. }
  83717. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  83718. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  83719. if( !isIgnoreErrors || db->mallocFailed ) return;
  83720. if( pTo==0 ){
  83721. /* If isIgnoreErrors is true, then a table is being dropped. In this
  83722. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  83723. ** before actually dropping it in order to check FK constraints.
  83724. ** If the parent table of an FK constraint on the current table is
  83725. ** missing, behave as if it is empty. i.e. decrement the relevant
  83726. ** FK counter for each row of the current table with non-NULL keys.
  83727. */
  83728. Vdbe *v = sqlite3GetVdbe(pParse);
  83729. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  83730. for(i=0; i<pFKey->nCol; i++){
  83731. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  83732. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  83733. }
  83734. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  83735. }
  83736. continue;
  83737. }
  83738. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  83739. if( aiFree ){
  83740. aiCol = aiFree;
  83741. }else{
  83742. iCol = pFKey->aCol[0].iFrom;
  83743. aiCol = &iCol;
  83744. }
  83745. for(i=0; i<pFKey->nCol; i++){
  83746. if( aiCol[i]==pTab->iPKey ){
  83747. aiCol[i] = -1;
  83748. }
  83749. #ifndef SQLITE_OMIT_AUTHORIZATION
  83750. /* Request permission to read the parent key columns. If the
  83751. ** authorization callback returns SQLITE_IGNORE, behave as if any
  83752. ** values read from the parent table are NULL. */
  83753. if( db->xAuth ){
  83754. int rcauth;
  83755. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  83756. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  83757. isIgnore = (rcauth==SQLITE_IGNORE);
  83758. }
  83759. #endif
  83760. }
  83761. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  83762. ** a cursor to use to search the unique index on the parent key columns
  83763. ** in the parent table. */
  83764. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  83765. pParse->nTab++;
  83766. if( regOld!=0 ){
  83767. /* A row is being removed from the child table. Search for the parent.
  83768. ** If the parent does not exist, removing the child row resolves an
  83769. ** outstanding foreign key constraint violation. */
  83770. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  83771. }
  83772. if( regNew!=0 ){
  83773. /* A row is being added to the child table. If a parent row cannot
  83774. ** be found, adding the child row has violated the FK constraint. */
  83775. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  83776. }
  83777. sqlite3DbFree(db, aiFree);
  83778. }
  83779. /* Loop through all the foreign key constraints that refer to this table */
  83780. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  83781. Index *pIdx = 0; /* Foreign key index for pFKey */
  83782. SrcList *pSrc;
  83783. int *aiCol = 0;
  83784. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  83785. assert( regOld==0 && regNew!=0 );
  83786. /* Inserting a single row into a parent table cannot cause an immediate
  83787. ** foreign key violation. So do nothing in this case. */
  83788. continue;
  83789. }
  83790. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  83791. if( !isIgnoreErrors || db->mallocFailed ) return;
  83792. continue;
  83793. }
  83794. assert( aiCol || pFKey->nCol==1 );
  83795. /* Create a SrcList structure containing a single table (the table
  83796. ** the foreign key that refers to this table is attached to). This
  83797. ** is required for the sqlite3WhereXXX() interface. */
  83798. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  83799. if( pSrc ){
  83800. struct SrcList_item *pItem = pSrc->a;
  83801. pItem->pTab = pFKey->pFrom;
  83802. pItem->zName = pFKey->pFrom->zName;
  83803. pItem->pTab->nRef++;
  83804. pItem->iCursor = pParse->nTab++;
  83805. if( regNew!=0 ){
  83806. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  83807. }
  83808. if( regOld!=0 ){
  83809. /* If there is a RESTRICT action configured for the current operation
  83810. ** on the parent table of this FK, then throw an exception
  83811. ** immediately if the FK constraint is violated, even if this is a
  83812. ** deferred trigger. That's what RESTRICT means. To defer checking
  83813. ** the constraint, the FK should specify NO ACTION (represented
  83814. ** using OE_None). NO ACTION is the default. */
  83815. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  83816. }
  83817. pItem->zName = 0;
  83818. sqlite3SrcListDelete(db, pSrc);
  83819. }
  83820. sqlite3DbFree(db, aiCol);
  83821. }
  83822. }
  83823. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  83824. /*
  83825. ** This function is called before generating code to update or delete a
  83826. ** row contained in table pTab.
  83827. */
  83828. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  83829. Parse *pParse, /* Parse context */
  83830. Table *pTab /* Table being modified */
  83831. ){
  83832. u32 mask = 0;
  83833. if( pParse->db->flags&SQLITE_ForeignKeys ){
  83834. FKey *p;
  83835. int i;
  83836. for(p=pTab->pFKey; p; p=p->pNextFrom){
  83837. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  83838. }
  83839. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  83840. Index *pIdx = 0;
  83841. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  83842. if( pIdx ){
  83843. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  83844. }
  83845. }
  83846. }
  83847. return mask;
  83848. }
  83849. /*
  83850. ** This function is called before generating code to update or delete a
  83851. ** row contained in table pTab. If the operation is a DELETE, then
  83852. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  83853. ** to an array of size N, where N is the number of columns in table pTab.
  83854. ** If the i'th column is not modified by the UPDATE, then the corresponding
  83855. ** entry in the aChange[] array is set to -1. If the column is modified,
  83856. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  83857. ** UPDATE statement modifies the rowid fields of the table.
  83858. **
  83859. ** If any foreign key processing will be required, this function returns
  83860. ** true. If there is no foreign key related processing, this function
  83861. ** returns false.
  83862. */
  83863. SQLITE_PRIVATE int sqlite3FkRequired(
  83864. Parse *pParse, /* Parse context */
  83865. Table *pTab, /* Table being modified */
  83866. int *aChange, /* Non-NULL for UPDATE operations */
  83867. int chngRowid /* True for UPDATE that affects rowid */
  83868. ){
  83869. if( pParse->db->flags&SQLITE_ForeignKeys ){
  83870. if( !aChange ){
  83871. /* A DELETE operation. Foreign key processing is required if the
  83872. ** table in question is either the child or parent table for any
  83873. ** foreign key constraint. */
  83874. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  83875. }else{
  83876. /* This is an UPDATE. Foreign key processing is only required if the
  83877. ** operation modifies one or more child or parent key columns. */
  83878. int i;
  83879. FKey *p;
  83880. /* Check if any child key columns are being modified. */
  83881. for(p=pTab->pFKey; p; p=p->pNextFrom){
  83882. for(i=0; i<p->nCol; i++){
  83883. int iChildKey = p->aCol[i].iFrom;
  83884. if( aChange[iChildKey]>=0 ) return 1;
  83885. if( iChildKey==pTab->iPKey && chngRowid ) return 1;
  83886. }
  83887. }
  83888. /* Check if any parent key columns are being modified. */
  83889. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  83890. for(i=0; i<p->nCol; i++){
  83891. char *zKey = p->aCol[i].zCol;
  83892. int iKey;
  83893. for(iKey=0; iKey<pTab->nCol; iKey++){
  83894. Column *pCol = &pTab->aCol[iKey];
  83895. if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
  83896. : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
  83897. if( aChange[iKey]>=0 ) return 1;
  83898. if( iKey==pTab->iPKey && chngRowid ) return 1;
  83899. }
  83900. }
  83901. }
  83902. }
  83903. }
  83904. }
  83905. return 0;
  83906. }
  83907. /*
  83908. ** This function is called when an UPDATE or DELETE operation is being
  83909. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  83910. ** If the current operation is an UPDATE, then the pChanges parameter is
  83911. ** passed a pointer to the list of columns being modified. If it is a
  83912. ** DELETE, pChanges is passed a NULL pointer.
  83913. **
  83914. ** It returns a pointer to a Trigger structure containing a trigger
  83915. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  83916. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  83917. ** returned (these actions require no special handling by the triggers
  83918. ** sub-system, code for them is created by fkScanChildren()).
  83919. **
  83920. ** For example, if pFKey is the foreign key and pTab is table "p" in
  83921. ** the following schema:
  83922. **
  83923. ** CREATE TABLE p(pk PRIMARY KEY);
  83924. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  83925. **
  83926. ** then the returned trigger structure is equivalent to:
  83927. **
  83928. ** CREATE TRIGGER ... DELETE ON p BEGIN
  83929. ** DELETE FROM c WHERE ck = old.pk;
  83930. ** END;
  83931. **
  83932. ** The returned pointer is cached as part of the foreign key object. It
  83933. ** is eventually freed along with the rest of the foreign key object by
  83934. ** sqlite3FkDelete().
  83935. */
  83936. static Trigger *fkActionTrigger(
  83937. Parse *pParse, /* Parse context */
  83938. Table *pTab, /* Table being updated or deleted from */
  83939. FKey *pFKey, /* Foreign key to get action for */
  83940. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  83941. ){
  83942. sqlite3 *db = pParse->db; /* Database handle */
  83943. int action; /* One of OE_None, OE_Cascade etc. */
  83944. Trigger *pTrigger; /* Trigger definition to return */
  83945. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  83946. action = pFKey->aAction[iAction];
  83947. pTrigger = pFKey->apTrigger[iAction];
  83948. if( action!=OE_None && !pTrigger ){
  83949. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  83950. char const *zFrom; /* Name of child table */
  83951. int nFrom; /* Length in bytes of zFrom */
  83952. Index *pIdx = 0; /* Parent key index for this FK */
  83953. int *aiCol = 0; /* child table cols -> parent key cols */
  83954. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  83955. Expr *pWhere = 0; /* WHERE clause of trigger step */
  83956. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  83957. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  83958. int i; /* Iterator variable */
  83959. Expr *pWhen = 0; /* WHEN clause for the trigger */
  83960. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  83961. assert( aiCol || pFKey->nCol==1 );
  83962. for(i=0; i<pFKey->nCol; i++){
  83963. Token tOld = { "old", 3 }; /* Literal "old" token */
  83964. Token tNew = { "new", 3 }; /* Literal "new" token */
  83965. Token tFromCol; /* Name of column in child table */
  83966. Token tToCol; /* Name of column in parent table */
  83967. int iFromCol; /* Idx of column in child table */
  83968. Expr *pEq; /* tFromCol = OLD.tToCol */
  83969. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  83970. assert( iFromCol>=0 );
  83971. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  83972. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  83973. tToCol.n = sqlite3Strlen30(tToCol.z);
  83974. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  83975. /* Create the expression "OLD.zToCol = zFromCol". It is important
  83976. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  83977. ** that the affinity and collation sequence associated with the
  83978. ** parent table are used for the comparison. */
  83979. pEq = sqlite3PExpr(pParse, TK_EQ,
  83980. sqlite3PExpr(pParse, TK_DOT,
  83981. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  83982. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  83983. , 0),
  83984. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  83985. , 0);
  83986. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  83987. /* For ON UPDATE, construct the next term of the WHEN clause.
  83988. ** The final WHEN clause will be like this:
  83989. **
  83990. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  83991. */
  83992. if( pChanges ){
  83993. pEq = sqlite3PExpr(pParse, TK_IS,
  83994. sqlite3PExpr(pParse, TK_DOT,
  83995. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  83996. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  83997. 0),
  83998. sqlite3PExpr(pParse, TK_DOT,
  83999. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  84000. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  84001. 0),
  84002. 0);
  84003. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  84004. }
  84005. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  84006. Expr *pNew;
  84007. if( action==OE_Cascade ){
  84008. pNew = sqlite3PExpr(pParse, TK_DOT,
  84009. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  84010. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  84011. , 0);
  84012. }else if( action==OE_SetDflt ){
  84013. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  84014. if( pDflt ){
  84015. pNew = sqlite3ExprDup(db, pDflt, 0);
  84016. }else{
  84017. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  84018. }
  84019. }else{
  84020. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  84021. }
  84022. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  84023. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  84024. }
  84025. }
  84026. sqlite3DbFree(db, aiCol);
  84027. zFrom = pFKey->pFrom->zName;
  84028. nFrom = sqlite3Strlen30(zFrom);
  84029. if( action==OE_Restrict ){
  84030. Token tFrom;
  84031. Expr *pRaise;
  84032. tFrom.z = zFrom;
  84033. tFrom.n = nFrom;
  84034. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  84035. if( pRaise ){
  84036. pRaise->affinity = OE_Abort;
  84037. }
  84038. pSelect = sqlite3SelectNew(pParse,
  84039. sqlite3ExprListAppend(pParse, 0, pRaise),
  84040. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  84041. pWhere,
  84042. 0, 0, 0, 0, 0, 0
  84043. );
  84044. pWhere = 0;
  84045. }
  84046. /* Disable lookaside memory allocation */
  84047. enableLookaside = db->lookaside.bEnabled;
  84048. db->lookaside.bEnabled = 0;
  84049. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  84050. sizeof(Trigger) + /* struct Trigger */
  84051. sizeof(TriggerStep) + /* Single step in trigger program */
  84052. nFrom + 1 /* Space for pStep->target.z */
  84053. );
  84054. if( pTrigger ){
  84055. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  84056. pStep->target.z = (char *)&pStep[1];
  84057. pStep->target.n = nFrom;
  84058. memcpy((char *)pStep->target.z, zFrom, nFrom);
  84059. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  84060. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  84061. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  84062. if( pWhen ){
  84063. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  84064. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  84065. }
  84066. }
  84067. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  84068. db->lookaside.bEnabled = enableLookaside;
  84069. sqlite3ExprDelete(db, pWhere);
  84070. sqlite3ExprDelete(db, pWhen);
  84071. sqlite3ExprListDelete(db, pList);
  84072. sqlite3SelectDelete(db, pSelect);
  84073. if( db->mallocFailed==1 ){
  84074. fkTriggerDelete(db, pTrigger);
  84075. return 0;
  84076. }
  84077. assert( pStep!=0 );
  84078. switch( action ){
  84079. case OE_Restrict:
  84080. pStep->op = TK_SELECT;
  84081. break;
  84082. case OE_Cascade:
  84083. if( !pChanges ){
  84084. pStep->op = TK_DELETE;
  84085. break;
  84086. }
  84087. default:
  84088. pStep->op = TK_UPDATE;
  84089. }
  84090. pStep->pTrig = pTrigger;
  84091. pTrigger->pSchema = pTab->pSchema;
  84092. pTrigger->pTabSchema = pTab->pSchema;
  84093. pFKey->apTrigger[iAction] = pTrigger;
  84094. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  84095. }
  84096. return pTrigger;
  84097. }
  84098. /*
  84099. ** This function is called when deleting or updating a row to implement
  84100. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  84101. */
  84102. SQLITE_PRIVATE void sqlite3FkActions(
  84103. Parse *pParse, /* Parse context */
  84104. Table *pTab, /* Table being updated or deleted from */
  84105. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  84106. int regOld /* Address of array containing old row */
  84107. ){
  84108. /* If foreign-key support is enabled, iterate through all FKs that
  84109. ** refer to table pTab. If there is an action associated with the FK
  84110. ** for this operation (either update or delete), invoke the associated
  84111. ** trigger sub-program. */
  84112. if( pParse->db->flags&SQLITE_ForeignKeys ){
  84113. FKey *pFKey; /* Iterator variable */
  84114. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  84115. Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  84116. if( pAction ){
  84117. sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
  84118. }
  84119. }
  84120. }
  84121. }
  84122. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  84123. /*
  84124. ** Free all memory associated with foreign key definitions attached to
  84125. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  84126. ** hash table.
  84127. */
  84128. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  84129. FKey *pFKey; /* Iterator variable */
  84130. FKey *pNext; /* Copy of pFKey->pNextFrom */
  84131. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  84132. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  84133. /* Remove the FK from the fkeyHash hash table. */
  84134. if( !db || db->pnBytesFreed==0 ){
  84135. if( pFKey->pPrevTo ){
  84136. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  84137. }else{
  84138. void *p = (void *)pFKey->pNextTo;
  84139. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  84140. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  84141. }
  84142. if( pFKey->pNextTo ){
  84143. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  84144. }
  84145. }
  84146. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  84147. ** classified as either immediate or deferred.
  84148. */
  84149. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  84150. /* Delete any triggers created to implement actions for this FK. */
  84151. #ifndef SQLITE_OMIT_TRIGGER
  84152. fkTriggerDelete(db, pFKey->apTrigger[0]);
  84153. fkTriggerDelete(db, pFKey->apTrigger[1]);
  84154. #endif
  84155. pNext = pFKey->pNextFrom;
  84156. sqlite3DbFree(db, pFKey);
  84157. }
  84158. }
  84159. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  84160. /************** End of fkey.c ************************************************/
  84161. /************** Begin file insert.c ******************************************/
  84162. /*
  84163. ** 2001 September 15
  84164. **
  84165. ** The author disclaims copyright to this source code. In place of
  84166. ** a legal notice, here is a blessing:
  84167. **
  84168. ** May you do good and not evil.
  84169. ** May you find forgiveness for yourself and forgive others.
  84170. ** May you share freely, never taking more than you give.
  84171. **
  84172. *************************************************************************
  84173. ** This file contains C code routines that are called by the parser
  84174. ** to handle INSERT statements in SQLite.
  84175. */
  84176. /*
  84177. ** Generate code that will open a table for reading.
  84178. */
  84179. SQLITE_PRIVATE void sqlite3OpenTable(
  84180. Parse *p, /* Generate code into this VDBE */
  84181. int iCur, /* The cursor number of the table */
  84182. int iDb, /* The database index in sqlite3.aDb[] */
  84183. Table *pTab, /* The table to be opened */
  84184. int opcode /* OP_OpenRead or OP_OpenWrite */
  84185. ){
  84186. Vdbe *v;
  84187. assert( !IsVirtual(pTab) );
  84188. v = sqlite3GetVdbe(p);
  84189. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  84190. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  84191. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  84192. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  84193. VdbeComment((v, "%s", pTab->zName));
  84194. }
  84195. /*
  84196. ** Return a pointer to the column affinity string associated with index
  84197. ** pIdx. A column affinity string has one character for each column in
  84198. ** the table, according to the affinity of the column:
  84199. **
  84200. ** Character Column affinity
  84201. ** ------------------------------
  84202. ** 'a' TEXT
  84203. ** 'b' NONE
  84204. ** 'c' NUMERIC
  84205. ** 'd' INTEGER
  84206. ** 'e' REAL
  84207. **
  84208. ** An extra 'd' is appended to the end of the string to cover the
  84209. ** rowid that appears as the last column in every index.
  84210. **
  84211. ** Memory for the buffer containing the column index affinity string
  84212. ** is managed along with the rest of the Index structure. It will be
  84213. ** released when sqlite3DeleteIndex() is called.
  84214. */
  84215. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  84216. if( !pIdx->zColAff ){
  84217. /* The first time a column affinity string for a particular index is
  84218. ** required, it is allocated and populated here. It is then stored as
  84219. ** a member of the Index structure for subsequent use.
  84220. **
  84221. ** The column affinity string will eventually be deleted by
  84222. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  84223. ** up.
  84224. */
  84225. int n;
  84226. Table *pTab = pIdx->pTable;
  84227. sqlite3 *db = sqlite3VdbeDb(v);
  84228. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  84229. if( !pIdx->zColAff ){
  84230. db->mallocFailed = 1;
  84231. return 0;
  84232. }
  84233. for(n=0; n<pIdx->nColumn; n++){
  84234. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  84235. }
  84236. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  84237. pIdx->zColAff[n] = 0;
  84238. }
  84239. return pIdx->zColAff;
  84240. }
  84241. /*
  84242. ** Set P4 of the most recently inserted opcode to a column affinity
  84243. ** string for table pTab. A column affinity string has one character
  84244. ** for each column indexed by the index, according to the affinity of the
  84245. ** column:
  84246. **
  84247. ** Character Column affinity
  84248. ** ------------------------------
  84249. ** 'a' TEXT
  84250. ** 'b' NONE
  84251. ** 'c' NUMERIC
  84252. ** 'd' INTEGER
  84253. ** 'e' REAL
  84254. */
  84255. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  84256. /* The first time a column affinity string for a particular table
  84257. ** is required, it is allocated and populated here. It is then
  84258. ** stored as a member of the Table structure for subsequent use.
  84259. **
  84260. ** The column affinity string will eventually be deleted by
  84261. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  84262. */
  84263. if( !pTab->zColAff ){
  84264. char *zColAff;
  84265. int i;
  84266. sqlite3 *db = sqlite3VdbeDb(v);
  84267. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  84268. if( !zColAff ){
  84269. db->mallocFailed = 1;
  84270. return;
  84271. }
  84272. for(i=0; i<pTab->nCol; i++){
  84273. zColAff[i] = pTab->aCol[i].affinity;
  84274. }
  84275. zColAff[pTab->nCol] = '\0';
  84276. pTab->zColAff = zColAff;
  84277. }
  84278. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  84279. }
  84280. /*
  84281. ** Return non-zero if the table pTab in database iDb or any of its indices
  84282. ** have been opened at any point in the VDBE program beginning at location
  84283. ** iStartAddr throught the end of the program. This is used to see if
  84284. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  84285. ** run without using temporary table for the results of the SELECT.
  84286. */
  84287. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  84288. Vdbe *v = sqlite3GetVdbe(p);
  84289. int i;
  84290. int iEnd = sqlite3VdbeCurrentAddr(v);
  84291. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84292. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  84293. #endif
  84294. for(i=iStartAddr; i<iEnd; i++){
  84295. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  84296. assert( pOp!=0 );
  84297. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  84298. Index *pIndex;
  84299. int tnum = pOp->p2;
  84300. if( tnum==pTab->tnum ){
  84301. return 1;
  84302. }
  84303. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  84304. if( tnum==pIndex->tnum ){
  84305. return 1;
  84306. }
  84307. }
  84308. }
  84309. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84310. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  84311. assert( pOp->p4.pVtab!=0 );
  84312. assert( pOp->p4type==P4_VTAB );
  84313. return 1;
  84314. }
  84315. #endif
  84316. }
  84317. return 0;
  84318. }
  84319. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84320. /*
  84321. ** Locate or create an AutoincInfo structure associated with table pTab
  84322. ** which is in database iDb. Return the register number for the register
  84323. ** that holds the maximum rowid.
  84324. **
  84325. ** There is at most one AutoincInfo structure per table even if the
  84326. ** same table is autoincremented multiple times due to inserts within
  84327. ** triggers. A new AutoincInfo structure is created if this is the
  84328. ** first use of table pTab. On 2nd and subsequent uses, the original
  84329. ** AutoincInfo structure is used.
  84330. **
  84331. ** Three memory locations are allocated:
  84332. **
  84333. ** (1) Register to hold the name of the pTab table.
  84334. ** (2) Register to hold the maximum ROWID of pTab.
  84335. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  84336. **
  84337. ** The 2nd register is the one that is returned. That is all the
  84338. ** insert routine needs to know about.
  84339. */
  84340. static int autoIncBegin(
  84341. Parse *pParse, /* Parsing context */
  84342. int iDb, /* Index of the database holding pTab */
  84343. Table *pTab /* The table we are writing to */
  84344. ){
  84345. int memId = 0; /* Register holding maximum rowid */
  84346. if( pTab->tabFlags & TF_Autoincrement ){
  84347. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84348. AutoincInfo *pInfo;
  84349. pInfo = pToplevel->pAinc;
  84350. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  84351. if( pInfo==0 ){
  84352. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  84353. if( pInfo==0 ) return 0;
  84354. pInfo->pNext = pToplevel->pAinc;
  84355. pToplevel->pAinc = pInfo;
  84356. pInfo->pTab = pTab;
  84357. pInfo->iDb = iDb;
  84358. pToplevel->nMem++; /* Register to hold name of table */
  84359. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  84360. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  84361. }
  84362. memId = pInfo->regCtr;
  84363. }
  84364. return memId;
  84365. }
  84366. /*
  84367. ** This routine generates code that will initialize all of the
  84368. ** register used by the autoincrement tracker.
  84369. */
  84370. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  84371. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  84372. sqlite3 *db = pParse->db; /* The database connection */
  84373. Db *pDb; /* Database only autoinc table */
  84374. int memId; /* Register holding max rowid */
  84375. int addr; /* A VDBE address */
  84376. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  84377. /* This routine is never called during trigger-generation. It is
  84378. ** only called from the top-level */
  84379. assert( pParse->pTriggerTab==0 );
  84380. assert( pParse==sqlite3ParseToplevel(pParse) );
  84381. assert( v ); /* We failed long ago if this is not so */
  84382. for(p = pParse->pAinc; p; p = p->pNext){
  84383. pDb = &db->aDb[p->iDb];
  84384. memId = p->regCtr;
  84385. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  84386. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  84387. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  84388. addr = sqlite3VdbeCurrentAddr(v);
  84389. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  84390. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  84391. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  84392. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  84393. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  84394. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  84395. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  84396. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  84397. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  84398. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  84399. sqlite3VdbeAddOp0(v, OP_Close);
  84400. }
  84401. }
  84402. /*
  84403. ** Update the maximum rowid for an autoincrement calculation.
  84404. **
  84405. ** This routine should be called when the top of the stack holds a
  84406. ** new rowid that is about to be inserted. If that new rowid is
  84407. ** larger than the maximum rowid in the memId memory cell, then the
  84408. ** memory cell is updated. The stack is unchanged.
  84409. */
  84410. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  84411. if( memId>0 ){
  84412. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  84413. }
  84414. }
  84415. /*
  84416. ** This routine generates the code needed to write autoincrement
  84417. ** maximum rowid values back into the sqlite_sequence register.
  84418. ** Every statement that might do an INSERT into an autoincrement
  84419. ** table (either directly or through triggers) needs to call this
  84420. ** routine just before the "exit" code.
  84421. */
  84422. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  84423. AutoincInfo *p;
  84424. Vdbe *v = pParse->pVdbe;
  84425. sqlite3 *db = pParse->db;
  84426. assert( v );
  84427. for(p = pParse->pAinc; p; p = p->pNext){
  84428. Db *pDb = &db->aDb[p->iDb];
  84429. int j1, j2, j3, j4, j5;
  84430. int iRec;
  84431. int memId = p->regCtr;
  84432. iRec = sqlite3GetTempReg(pParse);
  84433. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  84434. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  84435. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  84436. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  84437. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  84438. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  84439. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  84440. sqlite3VdbeJumpHere(v, j2);
  84441. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  84442. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  84443. sqlite3VdbeJumpHere(v, j4);
  84444. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  84445. sqlite3VdbeJumpHere(v, j1);
  84446. sqlite3VdbeJumpHere(v, j5);
  84447. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  84448. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  84449. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84450. sqlite3VdbeAddOp0(v, OP_Close);
  84451. sqlite3ReleaseTempReg(pParse, iRec);
  84452. }
  84453. }
  84454. #else
  84455. /*
  84456. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  84457. ** above are all no-ops
  84458. */
  84459. # define autoIncBegin(A,B,C) (0)
  84460. # define autoIncStep(A,B,C)
  84461. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  84462. /*
  84463. ** Generate code for a co-routine that will evaluate a subquery one
  84464. ** row at a time.
  84465. **
  84466. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  84467. ** Information about the location of co-routine and the registers it will use
  84468. ** is returned by filling in the pDest object.
  84469. **
  84470. ** Registers are allocated as follows:
  84471. **
  84472. ** pDest->iSDParm The register holding the next entry-point of the
  84473. ** co-routine. Run the co-routine to its next breakpoint
  84474. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  84475. **
  84476. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  84477. ** co-routine. This register is 0 if the previous Yield
  84478. ** generated a new result row, or 1 if the subquery
  84479. ** has completed. If the Yield is called again
  84480. ** after this register becomes 1, then the VDBE will
  84481. ** halt with an SQLITE_INTERNAL error.
  84482. **
  84483. ** pDest->iSdst First result register.
  84484. **
  84485. ** pDest->nSdst Number of result registers.
  84486. **
  84487. ** This routine handles all of the register allocation and fills in the
  84488. ** pDest structure appropriately.
  84489. **
  84490. ** Here is a schematic of the generated code assuming that X is the
  84491. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  84492. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  84493. ** registers that hold the result set, reg[pDest->iSdst] through
  84494. ** reg[pDest->iSdst+pDest->nSdst-1]:
  84495. **
  84496. ** X <- A
  84497. ** EOF <- 0
  84498. ** goto B
  84499. ** A: setup for the SELECT
  84500. ** loop rows in the SELECT
  84501. ** load results into registers R..S
  84502. ** yield X
  84503. ** end loop
  84504. ** cleanup after the SELECT
  84505. ** EOF <- 1
  84506. ** yield X
  84507. ** halt-error
  84508. ** B:
  84509. **
  84510. ** To use this subroutine, the caller generates code as follows:
  84511. **
  84512. ** [ Co-routine generated by this subroutine, shown above ]
  84513. ** S: yield X
  84514. ** if EOF goto E
  84515. ** if skip this row, goto C
  84516. ** if terminate loop, goto E
  84517. ** deal with this row
  84518. ** C: goto S
  84519. ** E:
  84520. */
  84521. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  84522. int regYield; /* Register holding co-routine entry-point */
  84523. int regEof; /* Register holding co-routine completion flag */
  84524. int addrTop; /* Top of the co-routine */
  84525. int j1; /* Jump instruction */
  84526. int rc; /* Result code */
  84527. Vdbe *v; /* VDBE under construction */
  84528. regYield = ++pParse->nMem;
  84529. regEof = ++pParse->nMem;
  84530. v = sqlite3GetVdbe(pParse);
  84531. addrTop = sqlite3VdbeCurrentAddr(v);
  84532. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  84533. VdbeComment((v, "Co-routine entry point"));
  84534. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  84535. VdbeComment((v, "Co-routine completion flag"));
  84536. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  84537. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  84538. rc = sqlite3Select(pParse, pSelect, pDest);
  84539. assert( pParse->nErr==0 || rc );
  84540. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  84541. if( rc ) return rc;
  84542. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  84543. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  84544. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  84545. VdbeComment((v, "End of coroutine"));
  84546. sqlite3VdbeJumpHere(v, j1); /* label B: */
  84547. return rc;
  84548. }
  84549. /* Forward declaration */
  84550. static int xferOptimization(
  84551. Parse *pParse, /* Parser context */
  84552. Table *pDest, /* The table we are inserting into */
  84553. Select *pSelect, /* A SELECT statement to use as the data source */
  84554. int onError, /* How to handle constraint errors */
  84555. int iDbDest /* The database of pDest */
  84556. );
  84557. /*
  84558. ** This routine is call to handle SQL of the following forms:
  84559. **
  84560. ** insert into TABLE (IDLIST) values(EXPRLIST)
  84561. ** insert into TABLE (IDLIST) select
  84562. **
  84563. ** The IDLIST following the table name is always optional. If omitted,
  84564. ** then a list of all columns for the table is substituted. The IDLIST
  84565. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  84566. **
  84567. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  84568. ** statement above, and pSelect is NULL. For the second form, pList is
  84569. ** NULL and pSelect is a pointer to the select statement used to generate
  84570. ** data for the insert.
  84571. **
  84572. ** The code generated follows one of four templates. For a simple
  84573. ** select with data coming from a VALUES clause, the code executes
  84574. ** once straight down through. Pseudo-code follows (we call this
  84575. ** the "1st template"):
  84576. **
  84577. ** open write cursor to <table> and its indices
  84578. ** puts VALUES clause expressions onto the stack
  84579. ** write the resulting record into <table>
  84580. ** cleanup
  84581. **
  84582. ** The three remaining templates assume the statement is of the form
  84583. **
  84584. ** INSERT INTO <table> SELECT ...
  84585. **
  84586. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  84587. ** in other words if the SELECT pulls all columns from a single table
  84588. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  84589. ** if <table2> and <table1> are distinct tables but have identical
  84590. ** schemas, including all the same indices, then a special optimization
  84591. ** is invoked that copies raw records from <table2> over to <table1>.
  84592. ** See the xferOptimization() function for the implementation of this
  84593. ** template. This is the 2nd template.
  84594. **
  84595. ** open a write cursor to <table>
  84596. ** open read cursor on <table2>
  84597. ** transfer all records in <table2> over to <table>
  84598. ** close cursors
  84599. ** foreach index on <table>
  84600. ** open a write cursor on the <table> index
  84601. ** open a read cursor on the corresponding <table2> index
  84602. ** transfer all records from the read to the write cursors
  84603. ** close cursors
  84604. ** end foreach
  84605. **
  84606. ** The 3rd template is for when the second template does not apply
  84607. ** and the SELECT clause does not read from <table> at any time.
  84608. ** The generated code follows this template:
  84609. **
  84610. ** EOF <- 0
  84611. ** X <- A
  84612. ** goto B
  84613. ** A: setup for the SELECT
  84614. ** loop over the rows in the SELECT
  84615. ** load values into registers R..R+n
  84616. ** yield X
  84617. ** end loop
  84618. ** cleanup after the SELECT
  84619. ** EOF <- 1
  84620. ** yield X
  84621. ** goto A
  84622. ** B: open write cursor to <table> and its indices
  84623. ** C: yield X
  84624. ** if EOF goto D
  84625. ** insert the select result into <table> from R..R+n
  84626. ** goto C
  84627. ** D: cleanup
  84628. **
  84629. ** The 4th template is used if the insert statement takes its
  84630. ** values from a SELECT but the data is being inserted into a table
  84631. ** that is also read as part of the SELECT. In the third form,
  84632. ** we have to use a intermediate table to store the results of
  84633. ** the select. The template is like this:
  84634. **
  84635. ** EOF <- 0
  84636. ** X <- A
  84637. ** goto B
  84638. ** A: setup for the SELECT
  84639. ** loop over the tables in the SELECT
  84640. ** load value into register R..R+n
  84641. ** yield X
  84642. ** end loop
  84643. ** cleanup after the SELECT
  84644. ** EOF <- 1
  84645. ** yield X
  84646. ** halt-error
  84647. ** B: open temp table
  84648. ** L: yield X
  84649. ** if EOF goto M
  84650. ** insert row from R..R+n into temp table
  84651. ** goto L
  84652. ** M: open write cursor to <table> and its indices
  84653. ** rewind temp table
  84654. ** C: loop over rows of intermediate table
  84655. ** transfer values form intermediate table into <table>
  84656. ** end loop
  84657. ** D: cleanup
  84658. */
  84659. SQLITE_PRIVATE void sqlite3Insert(
  84660. Parse *pParse, /* Parser context */
  84661. SrcList *pTabList, /* Name of table into which we are inserting */
  84662. ExprList *pList, /* List of values to be inserted */
  84663. Select *pSelect, /* A SELECT statement to use as the data source */
  84664. IdList *pColumn, /* Column names corresponding to IDLIST. */
  84665. int onError /* How to handle constraint errors */
  84666. ){
  84667. sqlite3 *db; /* The main database structure */
  84668. Table *pTab; /* The table to insert into. aka TABLE */
  84669. char *zTab; /* Name of the table into which we are inserting */
  84670. const char *zDb; /* Name of the database holding this table */
  84671. int i, j, idx; /* Loop counters */
  84672. Vdbe *v; /* Generate code into this virtual machine */
  84673. Index *pIdx; /* For looping over indices of the table */
  84674. int nColumn; /* Number of columns in the data */
  84675. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  84676. int baseCur = 0; /* VDBE Cursor number for pTab */
  84677. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  84678. int endOfLoop; /* Label for the end of the insertion loop */
  84679. int useTempTable = 0; /* Store SELECT results in intermediate table */
  84680. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  84681. int addrInsTop = 0; /* Jump to label "D" */
  84682. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  84683. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  84684. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  84685. int iDb; /* Index of database holding TABLE */
  84686. Db *pDb; /* The database containing table being inserted into */
  84687. int appendFlag = 0; /* True if the insert is likely to be an append */
  84688. /* Register allocations */
  84689. int regFromSelect = 0;/* Base register for data coming from SELECT */
  84690. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  84691. int regRowCount = 0; /* Memory cell used for the row counter */
  84692. int regIns; /* Block of regs holding rowid+data being inserted */
  84693. int regRowid; /* registers holding insert rowid */
  84694. int regData; /* register holding first column to insert */
  84695. int regEof = 0; /* Register recording end of SELECT data */
  84696. int *aRegIdx = 0; /* One register allocated to each index */
  84697. #ifndef SQLITE_OMIT_TRIGGER
  84698. int isView; /* True if attempting to insert into a view */
  84699. Trigger *pTrigger; /* List of triggers on pTab, if required */
  84700. int tmask; /* Mask of trigger times */
  84701. #endif
  84702. db = pParse->db;
  84703. memset(&dest, 0, sizeof(dest));
  84704. if( pParse->nErr || db->mallocFailed ){
  84705. goto insert_cleanup;
  84706. }
  84707. /* Locate the table into which we will be inserting new information.
  84708. */
  84709. assert( pTabList->nSrc==1 );
  84710. zTab = pTabList->a[0].zName;
  84711. if( NEVER(zTab==0) ) goto insert_cleanup;
  84712. pTab = sqlite3SrcListLookup(pParse, pTabList);
  84713. if( pTab==0 ){
  84714. goto insert_cleanup;
  84715. }
  84716. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  84717. assert( iDb<db->nDb );
  84718. pDb = &db->aDb[iDb];
  84719. zDb = pDb->zName;
  84720. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  84721. goto insert_cleanup;
  84722. }
  84723. /* Figure out if we have any triggers and if the table being
  84724. ** inserted into is a view
  84725. */
  84726. #ifndef SQLITE_OMIT_TRIGGER
  84727. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  84728. isView = pTab->pSelect!=0;
  84729. #else
  84730. # define pTrigger 0
  84731. # define tmask 0
  84732. # define isView 0
  84733. #endif
  84734. #ifdef SQLITE_OMIT_VIEW
  84735. # undef isView
  84736. # define isView 0
  84737. #endif
  84738. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  84739. /* If pTab is really a view, make sure it has been initialized.
  84740. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  84741. ** module table).
  84742. */
  84743. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  84744. goto insert_cleanup;
  84745. }
  84746. /* Ensure that:
  84747. * (a) the table is not read-only,
  84748. * (b) that if it is a view then ON INSERT triggers exist
  84749. */
  84750. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  84751. goto insert_cleanup;
  84752. }
  84753. /* Allocate a VDBE
  84754. */
  84755. v = sqlite3GetVdbe(pParse);
  84756. if( v==0 ) goto insert_cleanup;
  84757. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  84758. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  84759. #ifndef SQLITE_OMIT_XFER_OPT
  84760. /* If the statement is of the form
  84761. **
  84762. ** INSERT INTO <table1> SELECT * FROM <table2>;
  84763. **
  84764. ** Then special optimizations can be applied that make the transfer
  84765. ** very fast and which reduce fragmentation of indices.
  84766. **
  84767. ** This is the 2nd template.
  84768. */
  84769. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  84770. assert( !pTrigger );
  84771. assert( pList==0 );
  84772. goto insert_end;
  84773. }
  84774. #endif /* SQLITE_OMIT_XFER_OPT */
  84775. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  84776. ** sqlite_sequence table and store it in memory cell regAutoinc.
  84777. */
  84778. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  84779. /* Figure out how many columns of data are supplied. If the data
  84780. ** is coming from a SELECT statement, then generate a co-routine that
  84781. ** produces a single row of the SELECT on each invocation. The
  84782. ** co-routine is the common header to the 3rd and 4th templates.
  84783. */
  84784. if( pSelect ){
  84785. /* Data is coming from a SELECT. Generate a co-routine to run that
  84786. ** SELECT. */
  84787. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  84788. if( rc ) goto insert_cleanup;
  84789. regEof = dest.iSDParm + 1;
  84790. regFromSelect = dest.iSdst;
  84791. assert( pSelect->pEList );
  84792. nColumn = pSelect->pEList->nExpr;
  84793. assert( dest.nSdst==nColumn );
  84794. /* Set useTempTable to TRUE if the result of the SELECT statement
  84795. ** should be written into a temporary table (template 4). Set to
  84796. ** FALSE if each* row of the SELECT can be written directly into
  84797. ** the destination table (template 3).
  84798. **
  84799. ** A temp table must be used if the table being updated is also one
  84800. ** of the tables being read by the SELECT statement. Also use a
  84801. ** temp table in the case of row triggers.
  84802. */
  84803. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  84804. useTempTable = 1;
  84805. }
  84806. if( useTempTable ){
  84807. /* Invoke the coroutine to extract information from the SELECT
  84808. ** and add it to a transient table srcTab. The code generated
  84809. ** here is from the 4th template:
  84810. **
  84811. ** B: open temp table
  84812. ** L: yield X
  84813. ** if EOF goto M
  84814. ** insert row from R..R+n into temp table
  84815. ** goto L
  84816. ** M: ...
  84817. */
  84818. int regRec; /* Register to hold packed record */
  84819. int regTempRowid; /* Register to hold temp table ROWID */
  84820. int addrTop; /* Label "L" */
  84821. int addrIf; /* Address of jump to M */
  84822. srcTab = pParse->nTab++;
  84823. regRec = sqlite3GetTempReg(pParse);
  84824. regTempRowid = sqlite3GetTempReg(pParse);
  84825. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  84826. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  84827. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  84828. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  84829. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  84830. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  84831. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  84832. sqlite3VdbeJumpHere(v, addrIf);
  84833. sqlite3ReleaseTempReg(pParse, regRec);
  84834. sqlite3ReleaseTempReg(pParse, regTempRowid);
  84835. }
  84836. }else{
  84837. /* This is the case if the data for the INSERT is coming from a VALUES
  84838. ** clause
  84839. */
  84840. NameContext sNC;
  84841. memset(&sNC, 0, sizeof(sNC));
  84842. sNC.pParse = pParse;
  84843. srcTab = -1;
  84844. assert( useTempTable==0 );
  84845. nColumn = pList ? pList->nExpr : 0;
  84846. for(i=0; i<nColumn; i++){
  84847. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  84848. goto insert_cleanup;
  84849. }
  84850. }
  84851. }
  84852. /* Make sure the number of columns in the source data matches the number
  84853. ** of columns to be inserted into the table.
  84854. */
  84855. if( IsVirtual(pTab) ){
  84856. for(i=0; i<pTab->nCol; i++){
  84857. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  84858. }
  84859. }
  84860. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  84861. sqlite3ErrorMsg(pParse,
  84862. "table %S has %d columns but %d values were supplied",
  84863. pTabList, 0, pTab->nCol-nHidden, nColumn);
  84864. goto insert_cleanup;
  84865. }
  84866. if( pColumn!=0 && nColumn!=pColumn->nId ){
  84867. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  84868. goto insert_cleanup;
  84869. }
  84870. /* If the INSERT statement included an IDLIST term, then make sure
  84871. ** all elements of the IDLIST really are columns of the table and
  84872. ** remember the column indices.
  84873. **
  84874. ** If the table has an INTEGER PRIMARY KEY column and that column
  84875. ** is named in the IDLIST, then record in the keyColumn variable
  84876. ** the index into IDLIST of the primary key column. keyColumn is
  84877. ** the index of the primary key as it appears in IDLIST, not as
  84878. ** is appears in the original table. (The index of the primary
  84879. ** key in the original table is pTab->iPKey.)
  84880. */
  84881. if( pColumn ){
  84882. for(i=0; i<pColumn->nId; i++){
  84883. pColumn->a[i].idx = -1;
  84884. }
  84885. for(i=0; i<pColumn->nId; i++){
  84886. for(j=0; j<pTab->nCol; j++){
  84887. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  84888. pColumn->a[i].idx = j;
  84889. if( j==pTab->iPKey ){
  84890. keyColumn = i;
  84891. }
  84892. break;
  84893. }
  84894. }
  84895. if( j>=pTab->nCol ){
  84896. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  84897. keyColumn = i;
  84898. }else{
  84899. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  84900. pTabList, 0, pColumn->a[i].zName);
  84901. pParse->checkSchema = 1;
  84902. goto insert_cleanup;
  84903. }
  84904. }
  84905. }
  84906. }
  84907. /* If there is no IDLIST term but the table has an integer primary
  84908. ** key, the set the keyColumn variable to the primary key column index
  84909. ** in the original table definition.
  84910. */
  84911. if( pColumn==0 && nColumn>0 ){
  84912. keyColumn = pTab->iPKey;
  84913. }
  84914. /* Initialize the count of rows to be inserted
  84915. */
  84916. if( db->flags & SQLITE_CountRows ){
  84917. regRowCount = ++pParse->nMem;
  84918. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  84919. }
  84920. /* If this is not a view, open the table and and all indices */
  84921. if( !isView ){
  84922. int nIdx;
  84923. baseCur = pParse->nTab;
  84924. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  84925. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  84926. if( aRegIdx==0 ){
  84927. goto insert_cleanup;
  84928. }
  84929. for(i=0; i<nIdx; i++){
  84930. aRegIdx[i] = ++pParse->nMem;
  84931. }
  84932. }
  84933. /* This is the top of the main insertion loop */
  84934. if( useTempTable ){
  84935. /* This block codes the top of loop only. The complete loop is the
  84936. ** following pseudocode (template 4):
  84937. **
  84938. ** rewind temp table
  84939. ** C: loop over rows of intermediate table
  84940. ** transfer values form intermediate table into <table>
  84941. ** end loop
  84942. ** D: ...
  84943. */
  84944. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  84945. addrCont = sqlite3VdbeCurrentAddr(v);
  84946. }else if( pSelect ){
  84947. /* This block codes the top of loop only. The complete loop is the
  84948. ** following pseudocode (template 3):
  84949. **
  84950. ** C: yield X
  84951. ** if EOF goto D
  84952. ** insert the select result into <table> from R..R+n
  84953. ** goto C
  84954. ** D: ...
  84955. */
  84956. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  84957. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  84958. }
  84959. /* Allocate registers for holding the rowid of the new row,
  84960. ** the content of the new row, and the assemblied row record.
  84961. */
  84962. regRowid = regIns = pParse->nMem+1;
  84963. pParse->nMem += pTab->nCol + 1;
  84964. if( IsVirtual(pTab) ){
  84965. regRowid++;
  84966. pParse->nMem++;
  84967. }
  84968. regData = regRowid+1;
  84969. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  84970. */
  84971. endOfLoop = sqlite3VdbeMakeLabel(v);
  84972. if( tmask & TRIGGER_BEFORE ){
  84973. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  84974. /* build the NEW.* reference row. Note that if there is an INTEGER
  84975. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  84976. ** translated into a unique ID for the row. But on a BEFORE trigger,
  84977. ** we do not know what the unique ID will be (because the insert has
  84978. ** not happened yet) so we substitute a rowid of -1
  84979. */
  84980. if( keyColumn<0 ){
  84981. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  84982. }else{
  84983. int j1;
  84984. if( useTempTable ){
  84985. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  84986. }else{
  84987. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  84988. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  84989. }
  84990. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  84991. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  84992. sqlite3VdbeJumpHere(v, j1);
  84993. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  84994. }
  84995. /* Cannot have triggers on a virtual table. If it were possible,
  84996. ** this block would have to account for hidden column.
  84997. */
  84998. assert( !IsVirtual(pTab) );
  84999. /* Create the new column data
  85000. */
  85001. for(i=0; i<pTab->nCol; i++){
  85002. if( pColumn==0 ){
  85003. j = i;
  85004. }else{
  85005. for(j=0; j<pColumn->nId; j++){
  85006. if( pColumn->a[j].idx==i ) break;
  85007. }
  85008. }
  85009. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  85010. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  85011. }else if( useTempTable ){
  85012. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  85013. }else{
  85014. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  85015. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  85016. }
  85017. }
  85018. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  85019. ** do not attempt any conversions before assembling the record.
  85020. ** If this is a real table, attempt conversions as required by the
  85021. ** table column affinities.
  85022. */
  85023. if( !isView ){
  85024. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  85025. sqlite3TableAffinityStr(v, pTab);
  85026. }
  85027. /* Fire BEFORE or INSTEAD OF triggers */
  85028. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  85029. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  85030. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  85031. }
  85032. /* Push the record number for the new entry onto the stack. The
  85033. ** record number is a randomly generate integer created by NewRowid
  85034. ** except when the table has an INTEGER PRIMARY KEY column, in which
  85035. ** case the record number is the same as that column.
  85036. */
  85037. if( !isView ){
  85038. if( IsVirtual(pTab) ){
  85039. /* The row that the VUpdate opcode will delete: none */
  85040. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  85041. }
  85042. if( keyColumn>=0 ){
  85043. if( useTempTable ){
  85044. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  85045. }else if( pSelect ){
  85046. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  85047. }else{
  85048. VdbeOp *pOp;
  85049. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  85050. pOp = sqlite3VdbeGetOp(v, -1);
  85051. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  85052. appendFlag = 1;
  85053. pOp->opcode = OP_NewRowid;
  85054. pOp->p1 = baseCur;
  85055. pOp->p2 = regRowid;
  85056. pOp->p3 = regAutoinc;
  85057. }
  85058. }
  85059. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  85060. ** to generate a unique primary key value.
  85061. */
  85062. if( !appendFlag ){
  85063. int j1;
  85064. if( !IsVirtual(pTab) ){
  85065. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  85066. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  85067. sqlite3VdbeJumpHere(v, j1);
  85068. }else{
  85069. j1 = sqlite3VdbeCurrentAddr(v);
  85070. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  85071. }
  85072. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  85073. }
  85074. }else if( IsVirtual(pTab) ){
  85075. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  85076. }else{
  85077. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  85078. appendFlag = 1;
  85079. }
  85080. autoIncStep(pParse, regAutoinc, regRowid);
  85081. /* Push onto the stack, data for all columns of the new entry, beginning
  85082. ** with the first column.
  85083. */
  85084. nHidden = 0;
  85085. for(i=0; i<pTab->nCol; i++){
  85086. int iRegStore = regRowid+1+i;
  85087. if( i==pTab->iPKey ){
  85088. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  85089. ** Whenever this column is read, the record number will be substituted
  85090. ** in its place. So will fill this column with a NULL to avoid
  85091. ** taking up data space with information that will never be used. */
  85092. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  85093. continue;
  85094. }
  85095. if( pColumn==0 ){
  85096. if( IsHiddenColumn(&pTab->aCol[i]) ){
  85097. assert( IsVirtual(pTab) );
  85098. j = -1;
  85099. nHidden++;
  85100. }else{
  85101. j = i - nHidden;
  85102. }
  85103. }else{
  85104. for(j=0; j<pColumn->nId; j++){
  85105. if( pColumn->a[j].idx==i ) break;
  85106. }
  85107. }
  85108. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  85109. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  85110. }else if( useTempTable ){
  85111. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  85112. }else if( pSelect ){
  85113. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  85114. }else{
  85115. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  85116. }
  85117. }
  85118. /* Generate code to check constraints and generate index keys and
  85119. ** do the insertion.
  85120. */
  85121. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85122. if( IsVirtual(pTab) ){
  85123. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  85124. sqlite3VtabMakeWritable(pParse, pTab);
  85125. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  85126. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  85127. sqlite3MayAbort(pParse);
  85128. }else
  85129. #endif
  85130. {
  85131. int isReplace; /* Set to true if constraints may cause a replace */
  85132. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  85133. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  85134. );
  85135. sqlite3FkCheck(pParse, pTab, 0, regIns);
  85136. sqlite3CompleteInsertion(
  85137. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  85138. );
  85139. }
  85140. }
  85141. /* Update the count of rows that are inserted
  85142. */
  85143. if( (db->flags & SQLITE_CountRows)!=0 ){
  85144. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  85145. }
  85146. if( pTrigger ){
  85147. /* Code AFTER triggers */
  85148. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  85149. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  85150. }
  85151. /* The bottom of the main insertion loop, if the data source
  85152. ** is a SELECT statement.
  85153. */
  85154. sqlite3VdbeResolveLabel(v, endOfLoop);
  85155. if( useTempTable ){
  85156. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  85157. sqlite3VdbeJumpHere(v, addrInsTop);
  85158. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  85159. }else if( pSelect ){
  85160. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  85161. sqlite3VdbeJumpHere(v, addrInsTop);
  85162. }
  85163. if( !IsVirtual(pTab) && !isView ){
  85164. /* Close all tables opened */
  85165. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  85166. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  85167. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  85168. }
  85169. }
  85170. insert_end:
  85171. /* Update the sqlite_sequence table by storing the content of the
  85172. ** maximum rowid counter values recorded while inserting into
  85173. ** autoincrement tables.
  85174. */
  85175. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  85176. sqlite3AutoincrementEnd(pParse);
  85177. }
  85178. /*
  85179. ** Return the number of rows inserted. If this routine is
  85180. ** generating code because of a call to sqlite3NestedParse(), do not
  85181. ** invoke the callback function.
  85182. */
  85183. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  85184. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  85185. sqlite3VdbeSetNumCols(v, 1);
  85186. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  85187. }
  85188. insert_cleanup:
  85189. sqlite3SrcListDelete(db, pTabList);
  85190. sqlite3ExprListDelete(db, pList);
  85191. sqlite3SelectDelete(db, pSelect);
  85192. sqlite3IdListDelete(db, pColumn);
  85193. sqlite3DbFree(db, aRegIdx);
  85194. }
  85195. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  85196. ** thely may interfere with compilation of other functions in this file
  85197. ** (or in another file, if this file becomes part of the amalgamation). */
  85198. #ifdef isView
  85199. #undef isView
  85200. #endif
  85201. #ifdef pTrigger
  85202. #undef pTrigger
  85203. #endif
  85204. #ifdef tmask
  85205. #undef tmask
  85206. #endif
  85207. /*
  85208. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  85209. **
  85210. ** The input is a range of consecutive registers as follows:
  85211. **
  85212. ** 1. The rowid of the row after the update.
  85213. **
  85214. ** 2. The data in the first column of the entry after the update.
  85215. **
  85216. ** i. Data from middle columns...
  85217. **
  85218. ** N. The data in the last column of the entry after the update.
  85219. **
  85220. ** The regRowid parameter is the index of the register containing (1).
  85221. **
  85222. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  85223. ** the address of a register containing the rowid before the update takes
  85224. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  85225. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  85226. ** indicates that the rowid was explicitly specified as part of the
  85227. ** INSERT statement. If rowidChng is false, it means that the rowid is
  85228. ** computed automatically in an insert or that the rowid value is not
  85229. ** modified by an update.
  85230. **
  85231. ** The code generated by this routine store new index entries into
  85232. ** registers identified by aRegIdx[]. No index entry is created for
  85233. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  85234. ** the same as the order of indices on the linked list of indices
  85235. ** attached to the table.
  85236. **
  85237. ** This routine also generates code to check constraints. NOT NULL,
  85238. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  85239. ** then the appropriate action is performed. There are five possible
  85240. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  85241. **
  85242. ** Constraint type Action What Happens
  85243. ** --------------- ---------- ----------------------------------------
  85244. ** any ROLLBACK The current transaction is rolled back and
  85245. ** sqlite3_exec() returns immediately with a
  85246. ** return code of SQLITE_CONSTRAINT.
  85247. **
  85248. ** any ABORT Back out changes from the current command
  85249. ** only (do not do a complete rollback) then
  85250. ** cause sqlite3_exec() to return immediately
  85251. ** with SQLITE_CONSTRAINT.
  85252. **
  85253. ** any FAIL Sqlite3_exec() returns immediately with a
  85254. ** return code of SQLITE_CONSTRAINT. The
  85255. ** transaction is not rolled back and any
  85256. ** prior changes are retained.
  85257. **
  85258. ** any IGNORE The record number and data is popped from
  85259. ** the stack and there is an immediate jump
  85260. ** to label ignoreDest.
  85261. **
  85262. ** NOT NULL REPLACE The NULL value is replace by the default
  85263. ** value for that column. If the default value
  85264. ** is NULL, the action is the same as ABORT.
  85265. **
  85266. ** UNIQUE REPLACE The other row that conflicts with the row
  85267. ** being inserted is removed.
  85268. **
  85269. ** CHECK REPLACE Illegal. The results in an exception.
  85270. **
  85271. ** Which action to take is determined by the overrideError parameter.
  85272. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  85273. ** is used. Or if pParse->onError==OE_Default then the onError value
  85274. ** for the constraint is used.
  85275. **
  85276. ** The calling routine must open a read/write cursor for pTab with
  85277. ** cursor number "baseCur". All indices of pTab must also have open
  85278. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  85279. ** Except, if there is no possibility of a REPLACE action then
  85280. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  85281. */
  85282. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  85283. Parse *pParse, /* The parser context */
  85284. Table *pTab, /* the table into which we are inserting */
  85285. int baseCur, /* Index of a read/write cursor pointing at pTab */
  85286. int regRowid, /* Index of the range of input registers */
  85287. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  85288. int rowidChng, /* True if the rowid might collide with existing entry */
  85289. int isUpdate, /* True for UPDATE, False for INSERT */
  85290. int overrideError, /* Override onError to this if not OE_Default */
  85291. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  85292. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  85293. ){
  85294. int i; /* loop counter */
  85295. Vdbe *v; /* VDBE under constrution */
  85296. int nCol; /* Number of columns */
  85297. int onError; /* Conflict resolution strategy */
  85298. int j1; /* Addresss of jump instruction */
  85299. int j2 = 0, j3; /* Addresses of jump instructions */
  85300. int regData; /* Register containing first data column */
  85301. int iCur; /* Table cursor number */
  85302. Index *pIdx; /* Pointer to one of the indices */
  85303. sqlite3 *db; /* Database connection */
  85304. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  85305. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  85306. db = pParse->db;
  85307. v = sqlite3GetVdbe(pParse);
  85308. assert( v!=0 );
  85309. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  85310. nCol = pTab->nCol;
  85311. regData = regRowid + 1;
  85312. /* Test all NOT NULL constraints.
  85313. */
  85314. for(i=0; i<nCol; i++){
  85315. if( i==pTab->iPKey ){
  85316. continue;
  85317. }
  85318. onError = pTab->aCol[i].notNull;
  85319. if( onError==OE_None ) continue;
  85320. if( overrideError!=OE_Default ){
  85321. onError = overrideError;
  85322. }else if( onError==OE_Default ){
  85323. onError = OE_Abort;
  85324. }
  85325. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  85326. onError = OE_Abort;
  85327. }
  85328. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  85329. || onError==OE_Ignore || onError==OE_Replace );
  85330. switch( onError ){
  85331. case OE_Abort:
  85332. sqlite3MayAbort(pParse);
  85333. case OE_Rollback:
  85334. case OE_Fail: {
  85335. char *zMsg;
  85336. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  85337. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  85338. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  85339. pTab->zName, pTab->aCol[i].zName);
  85340. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  85341. break;
  85342. }
  85343. case OE_Ignore: {
  85344. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  85345. break;
  85346. }
  85347. default: {
  85348. assert( onError==OE_Replace );
  85349. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  85350. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  85351. sqlite3VdbeJumpHere(v, j1);
  85352. break;
  85353. }
  85354. }
  85355. }
  85356. /* Test all CHECK constraints
  85357. */
  85358. #ifndef SQLITE_OMIT_CHECK
  85359. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  85360. ExprList *pCheck = pTab->pCheck;
  85361. pParse->ckBase = regData;
  85362. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  85363. for(i=0; i<pCheck->nExpr; i++){
  85364. int allOk = sqlite3VdbeMakeLabel(v);
  85365. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  85366. if( onError==OE_Ignore ){
  85367. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  85368. }else{
  85369. char *zConsName = pCheck->a[i].zName;
  85370. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  85371. if( zConsName ){
  85372. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  85373. }else{
  85374. zConsName = 0;
  85375. }
  85376. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  85377. onError, zConsName, P4_DYNAMIC);
  85378. }
  85379. sqlite3VdbeResolveLabel(v, allOk);
  85380. }
  85381. }
  85382. #endif /* !defined(SQLITE_OMIT_CHECK) */
  85383. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  85384. ** of the new record does not previously exist. Except, if this
  85385. ** is an UPDATE and the primary key is not changing, that is OK.
  85386. */
  85387. if( rowidChng ){
  85388. onError = pTab->keyConf;
  85389. if( overrideError!=OE_Default ){
  85390. onError = overrideError;
  85391. }else if( onError==OE_Default ){
  85392. onError = OE_Abort;
  85393. }
  85394. if( isUpdate ){
  85395. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  85396. }
  85397. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  85398. switch( onError ){
  85399. default: {
  85400. onError = OE_Abort;
  85401. /* Fall thru into the next case */
  85402. }
  85403. case OE_Rollback:
  85404. case OE_Abort:
  85405. case OE_Fail: {
  85406. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  85407. onError, "PRIMARY KEY must be unique", P4_STATIC);
  85408. break;
  85409. }
  85410. case OE_Replace: {
  85411. /* If there are DELETE triggers on this table and the
  85412. ** recursive-triggers flag is set, call GenerateRowDelete() to
  85413. ** remove the conflicting row from the table. This will fire
  85414. ** the triggers and remove both the table and index b-tree entries.
  85415. **
  85416. ** Otherwise, if there are no triggers or the recursive-triggers
  85417. ** flag is not set, but the table has one or more indexes, call
  85418. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  85419. ** only. The table b-tree entry will be replaced by the new entry
  85420. ** when it is inserted.
  85421. **
  85422. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  85423. ** also invoke MultiWrite() to indicate that this VDBE may require
  85424. ** statement rollback (if the statement is aborted after the delete
  85425. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  85426. ** but being more selective here allows statements like:
  85427. **
  85428. ** REPLACE INTO t(rowid) VALUES($newrowid)
  85429. **
  85430. ** to run without a statement journal if there are no indexes on the
  85431. ** table.
  85432. */
  85433. Trigger *pTrigger = 0;
  85434. if( db->flags&SQLITE_RecTriggers ){
  85435. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  85436. }
  85437. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  85438. sqlite3MultiWrite(pParse);
  85439. sqlite3GenerateRowDelete(
  85440. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  85441. );
  85442. }else if( pTab->pIndex ){
  85443. sqlite3MultiWrite(pParse);
  85444. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  85445. }
  85446. seenReplace = 1;
  85447. break;
  85448. }
  85449. case OE_Ignore: {
  85450. assert( seenReplace==0 );
  85451. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  85452. break;
  85453. }
  85454. }
  85455. sqlite3VdbeJumpHere(v, j3);
  85456. if( isUpdate ){
  85457. sqlite3VdbeJumpHere(v, j2);
  85458. }
  85459. }
  85460. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  85461. ** index and making sure that duplicate entries do not already exist.
  85462. ** Add the new records to the indices as we go.
  85463. */
  85464. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  85465. int regIdx;
  85466. int regR;
  85467. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  85468. /* Create a key for accessing the index entry */
  85469. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  85470. for(i=0; i<pIdx->nColumn; i++){
  85471. int idx = pIdx->aiColumn[i];
  85472. if( idx==pTab->iPKey ){
  85473. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  85474. }else{
  85475. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  85476. }
  85477. }
  85478. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  85479. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  85480. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  85481. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  85482. /* Find out what action to take in case there is an indexing conflict */
  85483. onError = pIdx->onError;
  85484. if( onError==OE_None ){
  85485. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  85486. continue; /* pIdx is not a UNIQUE index */
  85487. }
  85488. if( overrideError!=OE_Default ){
  85489. onError = overrideError;
  85490. }else if( onError==OE_Default ){
  85491. onError = OE_Abort;
  85492. }
  85493. if( seenReplace ){
  85494. if( onError==OE_Ignore ) onError = OE_Replace;
  85495. else if( onError==OE_Fail ) onError = OE_Abort;
  85496. }
  85497. /* Check to see if the new index entry will be unique */
  85498. regR = sqlite3GetTempReg(pParse);
  85499. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  85500. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  85501. regR, SQLITE_INT_TO_PTR(regIdx),
  85502. P4_INT32);
  85503. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  85504. /* Generate code that executes if the new index entry is not unique */
  85505. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  85506. || onError==OE_Ignore || onError==OE_Replace );
  85507. switch( onError ){
  85508. case OE_Rollback:
  85509. case OE_Abort:
  85510. case OE_Fail: {
  85511. int j;
  85512. StrAccum errMsg;
  85513. const char *zSep;
  85514. char *zErr;
  85515. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  85516. errMsg.db = db;
  85517. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  85518. for(j=0; j<pIdx->nColumn; j++){
  85519. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  85520. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  85521. zSep = ", ";
  85522. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  85523. }
  85524. sqlite3StrAccumAppend(&errMsg,
  85525. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  85526. zErr = sqlite3StrAccumFinish(&errMsg);
  85527. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  85528. onError, zErr, 0);
  85529. sqlite3DbFree(errMsg.db, zErr);
  85530. break;
  85531. }
  85532. case OE_Ignore: {
  85533. assert( seenReplace==0 );
  85534. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  85535. break;
  85536. }
  85537. default: {
  85538. Trigger *pTrigger = 0;
  85539. assert( onError==OE_Replace );
  85540. sqlite3MultiWrite(pParse);
  85541. if( db->flags&SQLITE_RecTriggers ){
  85542. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  85543. }
  85544. sqlite3GenerateRowDelete(
  85545. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  85546. );
  85547. seenReplace = 1;
  85548. break;
  85549. }
  85550. }
  85551. sqlite3VdbeJumpHere(v, j3);
  85552. sqlite3ReleaseTempReg(pParse, regR);
  85553. }
  85554. if( pbMayReplace ){
  85555. *pbMayReplace = seenReplace;
  85556. }
  85557. }
  85558. /*
  85559. ** This routine generates code to finish the INSERT or UPDATE operation
  85560. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  85561. ** A consecutive range of registers starting at regRowid contains the
  85562. ** rowid and the content to be inserted.
  85563. **
  85564. ** The arguments to this routine should be the same as the first six
  85565. ** arguments to sqlite3GenerateConstraintChecks.
  85566. */
  85567. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  85568. Parse *pParse, /* The parser context */
  85569. Table *pTab, /* the table into which we are inserting */
  85570. int baseCur, /* Index of a read/write cursor pointing at pTab */
  85571. int regRowid, /* Range of content */
  85572. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  85573. int isUpdate, /* True for UPDATE, False for INSERT */
  85574. int appendBias, /* True if this is likely to be an append */
  85575. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  85576. ){
  85577. int i;
  85578. Vdbe *v;
  85579. int nIdx;
  85580. Index *pIdx;
  85581. u8 pik_flags;
  85582. int regData;
  85583. int regRec;
  85584. v = sqlite3GetVdbe(pParse);
  85585. assert( v!=0 );
  85586. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  85587. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  85588. for(i=nIdx-1; i>=0; i--){
  85589. if( aRegIdx[i]==0 ) continue;
  85590. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  85591. if( useSeekResult ){
  85592. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  85593. }
  85594. }
  85595. regData = regRowid + 1;
  85596. regRec = sqlite3GetTempReg(pParse);
  85597. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  85598. sqlite3TableAffinityStr(v, pTab);
  85599. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  85600. if( pParse->nested ){
  85601. pik_flags = 0;
  85602. }else{
  85603. pik_flags = OPFLAG_NCHANGE;
  85604. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  85605. }
  85606. if( appendBias ){
  85607. pik_flags |= OPFLAG_APPEND;
  85608. }
  85609. if( useSeekResult ){
  85610. pik_flags |= OPFLAG_USESEEKRESULT;
  85611. }
  85612. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  85613. if( !pParse->nested ){
  85614. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  85615. }
  85616. sqlite3VdbeChangeP5(v, pik_flags);
  85617. }
  85618. /*
  85619. ** Generate code that will open cursors for a table and for all
  85620. ** indices of that table. The "baseCur" parameter is the cursor number used
  85621. ** for the table. Indices are opened on subsequent cursors.
  85622. **
  85623. ** Return the number of indices on the table.
  85624. */
  85625. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  85626. Parse *pParse, /* Parsing context */
  85627. Table *pTab, /* Table to be opened */
  85628. int baseCur, /* Cursor number assigned to the table */
  85629. int op /* OP_OpenRead or OP_OpenWrite */
  85630. ){
  85631. int i;
  85632. int iDb;
  85633. Index *pIdx;
  85634. Vdbe *v;
  85635. if( IsVirtual(pTab) ) return 0;
  85636. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85637. v = sqlite3GetVdbe(pParse);
  85638. assert( v!=0 );
  85639. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  85640. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  85641. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  85642. assert( pIdx->pSchema==pTab->pSchema );
  85643. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  85644. (char*)pKey, P4_KEYINFO_HANDOFF);
  85645. VdbeComment((v, "%s", pIdx->zName));
  85646. }
  85647. if( pParse->nTab<baseCur+i ){
  85648. pParse->nTab = baseCur+i;
  85649. }
  85650. return i-1;
  85651. }
  85652. #ifdef SQLITE_TEST
  85653. /*
  85654. ** The following global variable is incremented whenever the
  85655. ** transfer optimization is used. This is used for testing
  85656. ** purposes only - to make sure the transfer optimization really
  85657. ** is happening when it is suppose to.
  85658. */
  85659. SQLITE_API int sqlite3_xferopt_count;
  85660. #endif /* SQLITE_TEST */
  85661. #ifndef SQLITE_OMIT_XFER_OPT
  85662. /*
  85663. ** Check to collation names to see if they are compatible.
  85664. */
  85665. static int xferCompatibleCollation(const char *z1, const char *z2){
  85666. if( z1==0 ){
  85667. return z2==0;
  85668. }
  85669. if( z2==0 ){
  85670. return 0;
  85671. }
  85672. return sqlite3StrICmp(z1, z2)==0;
  85673. }
  85674. /*
  85675. ** Check to see if index pSrc is compatible as a source of data
  85676. ** for index pDest in an insert transfer optimization. The rules
  85677. ** for a compatible index:
  85678. **
  85679. ** * The index is over the same set of columns
  85680. ** * The same DESC and ASC markings occurs on all columns
  85681. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  85682. ** * The same collating sequence on each column
  85683. */
  85684. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  85685. int i;
  85686. assert( pDest && pSrc );
  85687. assert( pDest->pTable!=pSrc->pTable );
  85688. if( pDest->nColumn!=pSrc->nColumn ){
  85689. return 0; /* Different number of columns */
  85690. }
  85691. if( pDest->onError!=pSrc->onError ){
  85692. return 0; /* Different conflict resolution strategies */
  85693. }
  85694. for(i=0; i<pSrc->nColumn; i++){
  85695. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  85696. return 0; /* Different columns indexed */
  85697. }
  85698. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  85699. return 0; /* Different sort orders */
  85700. }
  85701. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  85702. return 0; /* Different collating sequences */
  85703. }
  85704. }
  85705. /* If no test above fails then the indices must be compatible */
  85706. return 1;
  85707. }
  85708. /*
  85709. ** Attempt the transfer optimization on INSERTs of the form
  85710. **
  85711. ** INSERT INTO tab1 SELECT * FROM tab2;
  85712. **
  85713. ** The xfer optimization transfers raw records from tab2 over to tab1.
  85714. ** Columns are not decoded and reassemblied, which greatly improves
  85715. ** performance. Raw index records are transferred in the same way.
  85716. **
  85717. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  85718. ** There are lots of rules for determining compatibility - see comments
  85719. ** embedded in the code for details.
  85720. **
  85721. ** This routine returns TRUE if the optimization is guaranteed to be used.
  85722. ** Sometimes the xfer optimization will only work if the destination table
  85723. ** is empty - a factor that can only be determined at run-time. In that
  85724. ** case, this routine generates code for the xfer optimization but also
  85725. ** does a test to see if the destination table is empty and jumps over the
  85726. ** xfer optimization code if the test fails. In that case, this routine
  85727. ** returns FALSE so that the caller will know to go ahead and generate
  85728. ** an unoptimized transfer. This routine also returns FALSE if there
  85729. ** is no chance that the xfer optimization can be applied.
  85730. **
  85731. ** This optimization is particularly useful at making VACUUM run faster.
  85732. */
  85733. static int xferOptimization(
  85734. Parse *pParse, /* Parser context */
  85735. Table *pDest, /* The table we are inserting into */
  85736. Select *pSelect, /* A SELECT statement to use as the data source */
  85737. int onError, /* How to handle constraint errors */
  85738. int iDbDest /* The database of pDest */
  85739. ){
  85740. ExprList *pEList; /* The result set of the SELECT */
  85741. Table *pSrc; /* The table in the FROM clause of SELECT */
  85742. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  85743. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  85744. int i; /* Loop counter */
  85745. int iDbSrc; /* The database of pSrc */
  85746. int iSrc, iDest; /* Cursors from source and destination */
  85747. int addr1, addr2; /* Loop addresses */
  85748. int emptyDestTest; /* Address of test for empty pDest */
  85749. int emptySrcTest; /* Address of test for empty pSrc */
  85750. Vdbe *v; /* The VDBE we are building */
  85751. KeyInfo *pKey; /* Key information for an index */
  85752. int regAutoinc; /* Memory register used by AUTOINC */
  85753. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  85754. int regData, regRowid; /* Registers holding data and rowid */
  85755. if( pSelect==0 ){
  85756. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  85757. }
  85758. if( sqlite3TriggerList(pParse, pDest) ){
  85759. return 0; /* tab1 must not have triggers */
  85760. }
  85761. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85762. if( pDest->tabFlags & TF_Virtual ){
  85763. return 0; /* tab1 must not be a virtual table */
  85764. }
  85765. #endif
  85766. if( onError==OE_Default ){
  85767. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  85768. if( onError==OE_Default ) onError = OE_Abort;
  85769. }
  85770. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  85771. if( pSelect->pSrc->nSrc!=1 ){
  85772. return 0; /* FROM clause must have exactly one term */
  85773. }
  85774. if( pSelect->pSrc->a[0].pSelect ){
  85775. return 0; /* FROM clause cannot contain a subquery */
  85776. }
  85777. if( pSelect->pWhere ){
  85778. return 0; /* SELECT may not have a WHERE clause */
  85779. }
  85780. if( pSelect->pOrderBy ){
  85781. return 0; /* SELECT may not have an ORDER BY clause */
  85782. }
  85783. /* Do not need to test for a HAVING clause. If HAVING is present but
  85784. ** there is no ORDER BY, we will get an error. */
  85785. if( pSelect->pGroupBy ){
  85786. return 0; /* SELECT may not have a GROUP BY clause */
  85787. }
  85788. if( pSelect->pLimit ){
  85789. return 0; /* SELECT may not have a LIMIT clause */
  85790. }
  85791. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  85792. if( pSelect->pPrior ){
  85793. return 0; /* SELECT may not be a compound query */
  85794. }
  85795. if( pSelect->selFlags & SF_Distinct ){
  85796. return 0; /* SELECT may not be DISTINCT */
  85797. }
  85798. pEList = pSelect->pEList;
  85799. assert( pEList!=0 );
  85800. if( pEList->nExpr!=1 ){
  85801. return 0; /* The result set must have exactly one column */
  85802. }
  85803. assert( pEList->a[0].pExpr );
  85804. if( pEList->a[0].pExpr->op!=TK_ALL ){
  85805. return 0; /* The result set must be the special operator "*" */
  85806. }
  85807. /* At this point we have established that the statement is of the
  85808. ** correct syntactic form to participate in this optimization. Now
  85809. ** we have to check the semantics.
  85810. */
  85811. pItem = pSelect->pSrc->a;
  85812. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  85813. if( pSrc==0 ){
  85814. return 0; /* FROM clause does not contain a real table */
  85815. }
  85816. if( pSrc==pDest ){
  85817. return 0; /* tab1 and tab2 may not be the same table */
  85818. }
  85819. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85820. if( pSrc->tabFlags & TF_Virtual ){
  85821. return 0; /* tab2 must not be a virtual table */
  85822. }
  85823. #endif
  85824. if( pSrc->pSelect ){
  85825. return 0; /* tab2 may not be a view */
  85826. }
  85827. if( pDest->nCol!=pSrc->nCol ){
  85828. return 0; /* Number of columns must be the same in tab1 and tab2 */
  85829. }
  85830. if( pDest->iPKey!=pSrc->iPKey ){
  85831. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  85832. }
  85833. for(i=0; i<pDest->nCol; i++){
  85834. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  85835. return 0; /* Affinity must be the same on all columns */
  85836. }
  85837. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  85838. return 0; /* Collating sequence must be the same on all columns */
  85839. }
  85840. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  85841. return 0; /* tab2 must be NOT NULL if tab1 is */
  85842. }
  85843. }
  85844. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  85845. if( pDestIdx->onError!=OE_None ){
  85846. destHasUniqueIdx = 1;
  85847. }
  85848. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  85849. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  85850. }
  85851. if( pSrcIdx==0 ){
  85852. return 0; /* pDestIdx has no corresponding index in pSrc */
  85853. }
  85854. }
  85855. #ifndef SQLITE_OMIT_CHECK
  85856. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
  85857. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  85858. }
  85859. #endif
  85860. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85861. /* Disallow the transfer optimization if the destination table constains
  85862. ** any foreign key constraints. This is more restrictive than necessary.
  85863. ** But the main beneficiary of the transfer optimization is the VACUUM
  85864. ** command, and the VACUUM command disables foreign key constraints. So
  85865. ** the extra complication to make this rule less restrictive is probably
  85866. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  85867. */
  85868. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  85869. return 0;
  85870. }
  85871. #endif
  85872. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  85873. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  85874. }
  85875. /* If we get this far, it means that the xfer optimization is at
  85876. ** least a possibility, though it might only work if the destination
  85877. ** table (tab1) is initially empty.
  85878. */
  85879. #ifdef SQLITE_TEST
  85880. sqlite3_xferopt_count++;
  85881. #endif
  85882. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  85883. v = sqlite3GetVdbe(pParse);
  85884. sqlite3CodeVerifySchema(pParse, iDbSrc);
  85885. iSrc = pParse->nTab++;
  85886. iDest = pParse->nTab++;
  85887. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  85888. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  85889. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  85890. || destHasUniqueIdx /* (2) */
  85891. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  85892. ){
  85893. /* In some circumstances, we are able to run the xfer optimization
  85894. ** only if the destination table is initially empty. This code makes
  85895. ** that determination. Conditions under which the destination must
  85896. ** be empty:
  85897. **
  85898. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  85899. ** (If the destination is not initially empty, the rowid fields
  85900. ** of index entries might need to change.)
  85901. **
  85902. ** (2) The destination has a unique index. (The xfer optimization
  85903. ** is unable to test uniqueness.)
  85904. **
  85905. ** (3) onError is something other than OE_Abort and OE_Rollback.
  85906. */
  85907. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  85908. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  85909. sqlite3VdbeJumpHere(v, addr1);
  85910. }else{
  85911. emptyDestTest = 0;
  85912. }
  85913. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  85914. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  85915. regData = sqlite3GetTempReg(pParse);
  85916. regRowid = sqlite3GetTempReg(pParse);
  85917. if( pDest->iPKey>=0 ){
  85918. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  85919. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  85920. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  85921. onError, "PRIMARY KEY must be unique", P4_STATIC);
  85922. sqlite3VdbeJumpHere(v, addr2);
  85923. autoIncStep(pParse, regAutoinc, regRowid);
  85924. }else if( pDest->pIndex==0 ){
  85925. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  85926. }else{
  85927. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  85928. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  85929. }
  85930. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  85931. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  85932. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  85933. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  85934. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  85935. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  85936. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  85937. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  85938. }
  85939. assert( pSrcIdx );
  85940. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  85941. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  85942. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  85943. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  85944. (char*)pKey, P4_KEYINFO_HANDOFF);
  85945. VdbeComment((v, "%s", pSrcIdx->zName));
  85946. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  85947. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  85948. (char*)pKey, P4_KEYINFO_HANDOFF);
  85949. VdbeComment((v, "%s", pDestIdx->zName));
  85950. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  85951. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  85952. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  85953. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  85954. sqlite3VdbeJumpHere(v, addr1);
  85955. }
  85956. sqlite3VdbeJumpHere(v, emptySrcTest);
  85957. sqlite3ReleaseTempReg(pParse, regRowid);
  85958. sqlite3ReleaseTempReg(pParse, regData);
  85959. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  85960. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  85961. if( emptyDestTest ){
  85962. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  85963. sqlite3VdbeJumpHere(v, emptyDestTest);
  85964. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  85965. return 0;
  85966. }else{
  85967. return 1;
  85968. }
  85969. }
  85970. #endif /* SQLITE_OMIT_XFER_OPT */
  85971. /************** End of insert.c **********************************************/
  85972. /************** Begin file legacy.c ******************************************/
  85973. /*
  85974. ** 2001 September 15
  85975. **
  85976. ** The author disclaims copyright to this source code. In place of
  85977. ** a legal notice, here is a blessing:
  85978. **
  85979. ** May you do good and not evil.
  85980. ** May you find forgiveness for yourself and forgive others.
  85981. ** May you share freely, never taking more than you give.
  85982. **
  85983. *************************************************************************
  85984. ** Main file for the SQLite library. The routines in this file
  85985. ** implement the programmer interface to the library. Routines in
  85986. ** other files are for internal use by SQLite and should not be
  85987. ** accessed by users of the library.
  85988. */
  85989. /*
  85990. ** Execute SQL code. Return one of the SQLITE_ success/failure
  85991. ** codes. Also write an error message into memory obtained from
  85992. ** malloc() and make *pzErrMsg point to that message.
  85993. **
  85994. ** If the SQL is a query, then for each row in the query result
  85995. ** the xCallback() function is called. pArg becomes the first
  85996. ** argument to xCallback(). If xCallback=NULL then no callback
  85997. ** is invoked, even for queries.
  85998. */
  85999. SQLITE_API int sqlite3_exec(
  86000. sqlite3 *db, /* The database on which the SQL executes */
  86001. const char *zSql, /* The SQL to be executed */
  86002. sqlite3_callback xCallback, /* Invoke this callback routine */
  86003. void *pArg, /* First argument to xCallback() */
  86004. char **pzErrMsg /* Write error messages here */
  86005. ){
  86006. int rc = SQLITE_OK; /* Return code */
  86007. const char *zLeftover; /* Tail of unprocessed SQL */
  86008. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  86009. char **azCols = 0; /* Names of result columns */
  86010. int callbackIsInit; /* True if callback data is initialized */
  86011. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  86012. if( zSql==0 ) zSql = "";
  86013. sqlite3_mutex_enter(db->mutex);
  86014. sqlite3Error(db, SQLITE_OK, 0);
  86015. while( rc==SQLITE_OK && zSql[0] ){
  86016. int nCol;
  86017. char **azVals = 0;
  86018. pStmt = 0;
  86019. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  86020. assert( rc==SQLITE_OK || pStmt==0 );
  86021. if( rc!=SQLITE_OK ){
  86022. continue;
  86023. }
  86024. if( !pStmt ){
  86025. /* this happens for a comment or white-space */
  86026. zSql = zLeftover;
  86027. continue;
  86028. }
  86029. callbackIsInit = 0;
  86030. nCol = sqlite3_column_count(pStmt);
  86031. while( 1 ){
  86032. int i;
  86033. rc = sqlite3_step(pStmt);
  86034. /* Invoke the callback function if required */
  86035. if( xCallback && (SQLITE_ROW==rc ||
  86036. (SQLITE_DONE==rc && !callbackIsInit
  86037. && db->flags&SQLITE_NullCallback)) ){
  86038. if( !callbackIsInit ){
  86039. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  86040. if( azCols==0 ){
  86041. goto exec_out;
  86042. }
  86043. for(i=0; i<nCol; i++){
  86044. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  86045. /* sqlite3VdbeSetColName() installs column names as UTF8
  86046. ** strings so there is no way for sqlite3_column_name() to fail. */
  86047. assert( azCols[i]!=0 );
  86048. }
  86049. callbackIsInit = 1;
  86050. }
  86051. if( rc==SQLITE_ROW ){
  86052. azVals = &azCols[nCol];
  86053. for(i=0; i<nCol; i++){
  86054. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  86055. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  86056. db->mallocFailed = 1;
  86057. goto exec_out;
  86058. }
  86059. }
  86060. }
  86061. if( xCallback(pArg, nCol, azVals, azCols) ){
  86062. rc = SQLITE_ABORT;
  86063. sqlite3VdbeFinalize((Vdbe *)pStmt);
  86064. pStmt = 0;
  86065. sqlite3Error(db, SQLITE_ABORT, 0);
  86066. goto exec_out;
  86067. }
  86068. }
  86069. if( rc!=SQLITE_ROW ){
  86070. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  86071. pStmt = 0;
  86072. zSql = zLeftover;
  86073. while( sqlite3Isspace(zSql[0]) ) zSql++;
  86074. break;
  86075. }
  86076. }
  86077. sqlite3DbFree(db, azCols);
  86078. azCols = 0;
  86079. }
  86080. exec_out:
  86081. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  86082. sqlite3DbFree(db, azCols);
  86083. rc = sqlite3ApiExit(db, rc);
  86084. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  86085. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  86086. *pzErrMsg = sqlite3Malloc(nErrMsg);
  86087. if( *pzErrMsg ){
  86088. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  86089. }else{
  86090. rc = SQLITE_NOMEM;
  86091. sqlite3Error(db, SQLITE_NOMEM, 0);
  86092. }
  86093. }else if( pzErrMsg ){
  86094. *pzErrMsg = 0;
  86095. }
  86096. assert( (rc&db->errMask)==rc );
  86097. sqlite3_mutex_leave(db->mutex);
  86098. return rc;
  86099. }
  86100. /************** End of legacy.c **********************************************/
  86101. /************** Begin file loadext.c *****************************************/
  86102. /*
  86103. ** 2006 June 7
  86104. **
  86105. ** The author disclaims copyright to this source code. In place of
  86106. ** a legal notice, here is a blessing:
  86107. **
  86108. ** May you do good and not evil.
  86109. ** May you find forgiveness for yourself and forgive others.
  86110. ** May you share freely, never taking more than you give.
  86111. **
  86112. *************************************************************************
  86113. ** This file contains code used to dynamically load extensions into
  86114. ** the SQLite library.
  86115. */
  86116. #ifndef SQLITE_CORE
  86117. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  86118. #endif
  86119. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  86120. /************** Begin file sqlite3ext.h **************************************/
  86121. /*
  86122. ** 2006 June 7
  86123. **
  86124. ** The author disclaims copyright to this source code. In place of
  86125. ** a legal notice, here is a blessing:
  86126. **
  86127. ** May you do good and not evil.
  86128. ** May you find forgiveness for yourself and forgive others.
  86129. ** May you share freely, never taking more than you give.
  86130. **
  86131. *************************************************************************
  86132. ** This header file defines the SQLite interface for use by
  86133. ** shared libraries that want to be imported as extensions into
  86134. ** an SQLite instance. Shared libraries that intend to be loaded
  86135. ** as extensions by SQLite should #include this file instead of
  86136. ** sqlite3.h.
  86137. */
  86138. #ifndef _SQLITE3EXT_H_
  86139. #define _SQLITE3EXT_H_
  86140. typedef struct sqlite3_api_routines sqlite3_api_routines;
  86141. /*
  86142. ** The following structure holds pointers to all of the SQLite API
  86143. ** routines.
  86144. **
  86145. ** WARNING: In order to maintain backwards compatibility, add new
  86146. ** interfaces to the end of this structure only. If you insert new
  86147. ** interfaces in the middle of this structure, then older different
  86148. ** versions of SQLite will not be able to load each others' shared
  86149. ** libraries!
  86150. */
  86151. struct sqlite3_api_routines {
  86152. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  86153. int (*aggregate_count)(sqlite3_context*);
  86154. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  86155. int (*bind_double)(sqlite3_stmt*,int,double);
  86156. int (*bind_int)(sqlite3_stmt*,int,int);
  86157. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  86158. int (*bind_null)(sqlite3_stmt*,int);
  86159. int (*bind_parameter_count)(sqlite3_stmt*);
  86160. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  86161. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  86162. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  86163. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  86164. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  86165. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  86166. int (*busy_timeout)(sqlite3*,int ms);
  86167. int (*changes)(sqlite3*);
  86168. int (*close)(sqlite3*);
  86169. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  86170. int eTextRep,const char*));
  86171. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  86172. int eTextRep,const void*));
  86173. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  86174. int (*column_bytes)(sqlite3_stmt*,int iCol);
  86175. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  86176. int (*column_count)(sqlite3_stmt*pStmt);
  86177. const char * (*column_database_name)(sqlite3_stmt*,int);
  86178. const void * (*column_database_name16)(sqlite3_stmt*,int);
  86179. const char * (*column_decltype)(sqlite3_stmt*,int i);
  86180. const void * (*column_decltype16)(sqlite3_stmt*,int);
  86181. double (*column_double)(sqlite3_stmt*,int iCol);
  86182. int (*column_int)(sqlite3_stmt*,int iCol);
  86183. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  86184. const char * (*column_name)(sqlite3_stmt*,int);
  86185. const void * (*column_name16)(sqlite3_stmt*,int);
  86186. const char * (*column_origin_name)(sqlite3_stmt*,int);
  86187. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  86188. const char * (*column_table_name)(sqlite3_stmt*,int);
  86189. const void * (*column_table_name16)(sqlite3_stmt*,int);
  86190. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  86191. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  86192. int (*column_type)(sqlite3_stmt*,int iCol);
  86193. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  86194. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  86195. int (*complete)(const char*sql);
  86196. int (*complete16)(const void*sql);
  86197. int (*create_collation)(sqlite3*,const char*,int,void*,
  86198. int(*)(void*,int,const void*,int,const void*));
  86199. int (*create_collation16)(sqlite3*,const void*,int,void*,
  86200. int(*)(void*,int,const void*,int,const void*));
  86201. int (*create_function)(sqlite3*,const char*,int,int,void*,
  86202. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  86203. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  86204. void (*xFinal)(sqlite3_context*));
  86205. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  86206. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  86207. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  86208. void (*xFinal)(sqlite3_context*));
  86209. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  86210. int (*data_count)(sqlite3_stmt*pStmt);
  86211. sqlite3 * (*db_handle)(sqlite3_stmt*);
  86212. int (*declare_vtab)(sqlite3*,const char*);
  86213. int (*enable_shared_cache)(int);
  86214. int (*errcode)(sqlite3*db);
  86215. const char * (*errmsg)(sqlite3*);
  86216. const void * (*errmsg16)(sqlite3*);
  86217. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  86218. int (*expired)(sqlite3_stmt*);
  86219. int (*finalize)(sqlite3_stmt*pStmt);
  86220. void (*free)(void*);
  86221. void (*free_table)(char**result);
  86222. int (*get_autocommit)(sqlite3*);
  86223. void * (*get_auxdata)(sqlite3_context*,int);
  86224. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  86225. int (*global_recover)(void);
  86226. void (*interruptx)(sqlite3*);
  86227. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  86228. const char * (*libversion)(void);
  86229. int (*libversion_number)(void);
  86230. void *(*malloc)(int);
  86231. char * (*mprintf)(const char*,...);
  86232. int (*open)(const char*,sqlite3**);
  86233. int (*open16)(const void*,sqlite3**);
  86234. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  86235. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  86236. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  86237. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  86238. void *(*realloc)(void*,int);
  86239. int (*reset)(sqlite3_stmt*pStmt);
  86240. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  86241. void (*result_double)(sqlite3_context*,double);
  86242. void (*result_error)(sqlite3_context*,const char*,int);
  86243. void (*result_error16)(sqlite3_context*,const void*,int);
  86244. void (*result_int)(sqlite3_context*,int);
  86245. void (*result_int64)(sqlite3_context*,sqlite_int64);
  86246. void (*result_null)(sqlite3_context*);
  86247. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  86248. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  86249. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  86250. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  86251. void (*result_value)(sqlite3_context*,sqlite3_value*);
  86252. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  86253. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  86254. const char*,const char*),void*);
  86255. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  86256. char * (*snprintf)(int,char*,const char*,...);
  86257. int (*step)(sqlite3_stmt*);
  86258. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  86259. char const**,char const**,int*,int*,int*);
  86260. void (*thread_cleanup)(void);
  86261. int (*total_changes)(sqlite3*);
  86262. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  86263. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  86264. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  86265. sqlite_int64),void*);
  86266. void * (*user_data)(sqlite3_context*);
  86267. const void * (*value_blob)(sqlite3_value*);
  86268. int (*value_bytes)(sqlite3_value*);
  86269. int (*value_bytes16)(sqlite3_value*);
  86270. double (*value_double)(sqlite3_value*);
  86271. int (*value_int)(sqlite3_value*);
  86272. sqlite_int64 (*value_int64)(sqlite3_value*);
  86273. int (*value_numeric_type)(sqlite3_value*);
  86274. const unsigned char * (*value_text)(sqlite3_value*);
  86275. const void * (*value_text16)(sqlite3_value*);
  86276. const void * (*value_text16be)(sqlite3_value*);
  86277. const void * (*value_text16le)(sqlite3_value*);
  86278. int (*value_type)(sqlite3_value*);
  86279. char *(*vmprintf)(const char*,va_list);
  86280. /* Added ??? */
  86281. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  86282. /* Added by 3.3.13 */
  86283. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  86284. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  86285. int (*clear_bindings)(sqlite3_stmt*);
  86286. /* Added by 3.4.1 */
  86287. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  86288. void (*xDestroy)(void *));
  86289. /* Added by 3.5.0 */
  86290. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  86291. int (*blob_bytes)(sqlite3_blob*);
  86292. int (*blob_close)(sqlite3_blob*);
  86293. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  86294. int,sqlite3_blob**);
  86295. int (*blob_read)(sqlite3_blob*,void*,int,int);
  86296. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  86297. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  86298. int(*)(void*,int,const void*,int,const void*),
  86299. void(*)(void*));
  86300. int (*file_control)(sqlite3*,const char*,int,void*);
  86301. sqlite3_int64 (*memory_highwater)(int);
  86302. sqlite3_int64 (*memory_used)(void);
  86303. sqlite3_mutex *(*mutex_alloc)(int);
  86304. void (*mutex_enter)(sqlite3_mutex*);
  86305. void (*mutex_free)(sqlite3_mutex*);
  86306. void (*mutex_leave)(sqlite3_mutex*);
  86307. int (*mutex_try)(sqlite3_mutex*);
  86308. int (*open_v2)(const char*,sqlite3**,int,const char*);
  86309. int (*release_memory)(int);
  86310. void (*result_error_nomem)(sqlite3_context*);
  86311. void (*result_error_toobig)(sqlite3_context*);
  86312. int (*sleep)(int);
  86313. void (*soft_heap_limit)(int);
  86314. sqlite3_vfs *(*vfs_find)(const char*);
  86315. int (*vfs_register)(sqlite3_vfs*,int);
  86316. int (*vfs_unregister)(sqlite3_vfs*);
  86317. int (*xthreadsafe)(void);
  86318. void (*result_zeroblob)(sqlite3_context*,int);
  86319. void (*result_error_code)(sqlite3_context*,int);
  86320. int (*test_control)(int, ...);
  86321. void (*randomness)(int,void*);
  86322. sqlite3 *(*context_db_handle)(sqlite3_context*);
  86323. int (*extended_result_codes)(sqlite3*,int);
  86324. int (*limit)(sqlite3*,int,int);
  86325. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  86326. const char *(*sql)(sqlite3_stmt*);
  86327. int (*status)(int,int*,int*,int);
  86328. int (*backup_finish)(sqlite3_backup*);
  86329. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  86330. int (*backup_pagecount)(sqlite3_backup*);
  86331. int (*backup_remaining)(sqlite3_backup*);
  86332. int (*backup_step)(sqlite3_backup*,int);
  86333. const char *(*compileoption_get)(int);
  86334. int (*compileoption_used)(const char*);
  86335. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  86336. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  86337. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  86338. void (*xFinal)(sqlite3_context*),
  86339. void(*xDestroy)(void*));
  86340. int (*db_config)(sqlite3*,int,...);
  86341. sqlite3_mutex *(*db_mutex)(sqlite3*);
  86342. int (*db_status)(sqlite3*,int,int*,int*,int);
  86343. int (*extended_errcode)(sqlite3*);
  86344. void (*log)(int,const char*,...);
  86345. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  86346. const char *(*sourceid)(void);
  86347. int (*stmt_status)(sqlite3_stmt*,int,int);
  86348. int (*strnicmp)(const char*,const char*,int);
  86349. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  86350. int (*wal_autocheckpoint)(sqlite3*,int);
  86351. int (*wal_checkpoint)(sqlite3*,const char*);
  86352. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  86353. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  86354. int (*vtab_config)(sqlite3*,int op,...);
  86355. int (*vtab_on_conflict)(sqlite3*);
  86356. /* Version 3.7.16 and later */
  86357. int (*close_v2)(sqlite3*);
  86358. const char *(*db_filename)(sqlite3*,const char*);
  86359. int (*db_readonly)(sqlite3*,const char*);
  86360. int (*db_release_memory)(sqlite3*);
  86361. const char *(*errstr)(int);
  86362. int (*stmt_busy)(sqlite3_stmt*);
  86363. int (*stmt_readonly)(sqlite3_stmt*);
  86364. int (*stricmp)(const char*,const char*);
  86365. int (*uri_boolean)(const char*,const char*,int);
  86366. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  86367. const char *(*uri_parameter)(const char*,const char*);
  86368. char *(*vsnprintf)(int,char*,const char*,va_list);
  86369. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  86370. };
  86371. /*
  86372. ** The following macros redefine the API routines so that they are
  86373. ** redirected throught the global sqlite3_api structure.
  86374. **
  86375. ** This header file is also used by the loadext.c source file
  86376. ** (part of the main SQLite library - not an extension) so that
  86377. ** it can get access to the sqlite3_api_routines structure
  86378. ** definition. But the main library does not want to redefine
  86379. ** the API. So the redefinition macros are only valid if the
  86380. ** SQLITE_CORE macros is undefined.
  86381. */
  86382. #ifndef SQLITE_CORE
  86383. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  86384. #ifndef SQLITE_OMIT_DEPRECATED
  86385. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  86386. #endif
  86387. #define sqlite3_bind_blob sqlite3_api->bind_blob
  86388. #define sqlite3_bind_double sqlite3_api->bind_double
  86389. #define sqlite3_bind_int sqlite3_api->bind_int
  86390. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  86391. #define sqlite3_bind_null sqlite3_api->bind_null
  86392. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  86393. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  86394. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  86395. #define sqlite3_bind_text sqlite3_api->bind_text
  86396. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  86397. #define sqlite3_bind_value sqlite3_api->bind_value
  86398. #define sqlite3_busy_handler sqlite3_api->busy_handler
  86399. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  86400. #define sqlite3_changes sqlite3_api->changes
  86401. #define sqlite3_close sqlite3_api->close
  86402. #define sqlite3_collation_needed sqlite3_api->collation_needed
  86403. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  86404. #define sqlite3_column_blob sqlite3_api->column_blob
  86405. #define sqlite3_column_bytes sqlite3_api->column_bytes
  86406. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  86407. #define sqlite3_column_count sqlite3_api->column_count
  86408. #define sqlite3_column_database_name sqlite3_api->column_database_name
  86409. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  86410. #define sqlite3_column_decltype sqlite3_api->column_decltype
  86411. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  86412. #define sqlite3_column_double sqlite3_api->column_double
  86413. #define sqlite3_column_int sqlite3_api->column_int
  86414. #define sqlite3_column_int64 sqlite3_api->column_int64
  86415. #define sqlite3_column_name sqlite3_api->column_name
  86416. #define sqlite3_column_name16 sqlite3_api->column_name16
  86417. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  86418. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  86419. #define sqlite3_column_table_name sqlite3_api->column_table_name
  86420. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  86421. #define sqlite3_column_text sqlite3_api->column_text
  86422. #define sqlite3_column_text16 sqlite3_api->column_text16
  86423. #define sqlite3_column_type sqlite3_api->column_type
  86424. #define sqlite3_column_value sqlite3_api->column_value
  86425. #define sqlite3_commit_hook sqlite3_api->commit_hook
  86426. #define sqlite3_complete sqlite3_api->complete
  86427. #define sqlite3_complete16 sqlite3_api->complete16
  86428. #define sqlite3_create_collation sqlite3_api->create_collation
  86429. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  86430. #define sqlite3_create_function sqlite3_api->create_function
  86431. #define sqlite3_create_function16 sqlite3_api->create_function16
  86432. #define sqlite3_create_module sqlite3_api->create_module
  86433. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  86434. #define sqlite3_data_count sqlite3_api->data_count
  86435. #define sqlite3_db_handle sqlite3_api->db_handle
  86436. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  86437. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  86438. #define sqlite3_errcode sqlite3_api->errcode
  86439. #define sqlite3_errmsg sqlite3_api->errmsg
  86440. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  86441. #define sqlite3_exec sqlite3_api->exec
  86442. #ifndef SQLITE_OMIT_DEPRECATED
  86443. #define sqlite3_expired sqlite3_api->expired
  86444. #endif
  86445. #define sqlite3_finalize sqlite3_api->finalize
  86446. #define sqlite3_free sqlite3_api->free
  86447. #define sqlite3_free_table sqlite3_api->free_table
  86448. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  86449. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  86450. #define sqlite3_get_table sqlite3_api->get_table
  86451. #ifndef SQLITE_OMIT_DEPRECATED
  86452. #define sqlite3_global_recover sqlite3_api->global_recover
  86453. #endif
  86454. #define sqlite3_interrupt sqlite3_api->interruptx
  86455. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  86456. #define sqlite3_libversion sqlite3_api->libversion
  86457. #define sqlite3_libversion_number sqlite3_api->libversion_number
  86458. #define sqlite3_malloc sqlite3_api->malloc
  86459. #define sqlite3_mprintf sqlite3_api->mprintf
  86460. #define sqlite3_open sqlite3_api->open
  86461. #define sqlite3_open16 sqlite3_api->open16
  86462. #define sqlite3_prepare sqlite3_api->prepare
  86463. #define sqlite3_prepare16 sqlite3_api->prepare16
  86464. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  86465. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  86466. #define sqlite3_profile sqlite3_api->profile
  86467. #define sqlite3_progress_handler sqlite3_api->progress_handler
  86468. #define sqlite3_realloc sqlite3_api->realloc
  86469. #define sqlite3_reset sqlite3_api->reset
  86470. #define sqlite3_result_blob sqlite3_api->result_blob
  86471. #define sqlite3_result_double sqlite3_api->result_double
  86472. #define sqlite3_result_error sqlite3_api->result_error
  86473. #define sqlite3_result_error16 sqlite3_api->result_error16
  86474. #define sqlite3_result_int sqlite3_api->result_int
  86475. #define sqlite3_result_int64 sqlite3_api->result_int64
  86476. #define sqlite3_result_null sqlite3_api->result_null
  86477. #define sqlite3_result_text sqlite3_api->result_text
  86478. #define sqlite3_result_text16 sqlite3_api->result_text16
  86479. #define sqlite3_result_text16be sqlite3_api->result_text16be
  86480. #define sqlite3_result_text16le sqlite3_api->result_text16le
  86481. #define sqlite3_result_value sqlite3_api->result_value
  86482. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  86483. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  86484. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  86485. #define sqlite3_snprintf sqlite3_api->snprintf
  86486. #define sqlite3_step sqlite3_api->step
  86487. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  86488. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  86489. #define sqlite3_total_changes sqlite3_api->total_changes
  86490. #define sqlite3_trace sqlite3_api->trace
  86491. #ifndef SQLITE_OMIT_DEPRECATED
  86492. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  86493. #endif
  86494. #define sqlite3_update_hook sqlite3_api->update_hook
  86495. #define sqlite3_user_data sqlite3_api->user_data
  86496. #define sqlite3_value_blob sqlite3_api->value_blob
  86497. #define sqlite3_value_bytes sqlite3_api->value_bytes
  86498. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  86499. #define sqlite3_value_double sqlite3_api->value_double
  86500. #define sqlite3_value_int sqlite3_api->value_int
  86501. #define sqlite3_value_int64 sqlite3_api->value_int64
  86502. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  86503. #define sqlite3_value_text sqlite3_api->value_text
  86504. #define sqlite3_value_text16 sqlite3_api->value_text16
  86505. #define sqlite3_value_text16be sqlite3_api->value_text16be
  86506. #define sqlite3_value_text16le sqlite3_api->value_text16le
  86507. #define sqlite3_value_type sqlite3_api->value_type
  86508. #define sqlite3_vmprintf sqlite3_api->vmprintf
  86509. #define sqlite3_overload_function sqlite3_api->overload_function
  86510. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  86511. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  86512. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  86513. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  86514. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  86515. #define sqlite3_blob_close sqlite3_api->blob_close
  86516. #define sqlite3_blob_open sqlite3_api->blob_open
  86517. #define sqlite3_blob_read sqlite3_api->blob_read
  86518. #define sqlite3_blob_write sqlite3_api->blob_write
  86519. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  86520. #define sqlite3_file_control sqlite3_api->file_control
  86521. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  86522. #define sqlite3_memory_used sqlite3_api->memory_used
  86523. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  86524. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  86525. #define sqlite3_mutex_free sqlite3_api->mutex_free
  86526. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  86527. #define sqlite3_mutex_try sqlite3_api->mutex_try
  86528. #define sqlite3_open_v2 sqlite3_api->open_v2
  86529. #define sqlite3_release_memory sqlite3_api->release_memory
  86530. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  86531. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  86532. #define sqlite3_sleep sqlite3_api->sleep
  86533. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  86534. #define sqlite3_vfs_find sqlite3_api->vfs_find
  86535. #define sqlite3_vfs_register sqlite3_api->vfs_register
  86536. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  86537. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  86538. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  86539. #define sqlite3_result_error_code sqlite3_api->result_error_code
  86540. #define sqlite3_test_control sqlite3_api->test_control
  86541. #define sqlite3_randomness sqlite3_api->randomness
  86542. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  86543. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  86544. #define sqlite3_limit sqlite3_api->limit
  86545. #define sqlite3_next_stmt sqlite3_api->next_stmt
  86546. #define sqlite3_sql sqlite3_api->sql
  86547. #define sqlite3_status sqlite3_api->status
  86548. #define sqlite3_backup_finish sqlite3_api->backup_finish
  86549. #define sqlite3_backup_init sqlite3_api->backup_init
  86550. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  86551. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  86552. #define sqlite3_backup_step sqlite3_api->backup_step
  86553. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  86554. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  86555. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  86556. #define sqlite3_db_config sqlite3_api->db_config
  86557. #define sqlite3_db_mutex sqlite3_api->db_mutex
  86558. #define sqlite3_db_status sqlite3_api->db_status
  86559. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  86560. #define sqlite3_log sqlite3_api->log
  86561. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  86562. #define sqlite3_sourceid sqlite3_api->sourceid
  86563. #define sqlite3_stmt_status sqlite3_api->stmt_status
  86564. #define sqlite3_strnicmp sqlite3_api->strnicmp
  86565. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  86566. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  86567. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  86568. #define sqlite3_wal_hook sqlite3_api->wal_hook
  86569. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  86570. #define sqlite3_vtab_config sqlite3_api->vtab_config
  86571. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  86572. /* Version 3.7.16 and later */
  86573. #define sqlite3_close_v2 sqlite3_api->close_v2
  86574. #define sqlite3_db_filename sqlite3_api->db_filename
  86575. #define sqlite3_db_readonly sqlite3_api->db_readonly
  86576. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  86577. #define sqlite3_errstr sqlite3_api->errstr
  86578. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  86579. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  86580. #define sqlite3_stricmp sqlite3_api->stricmp
  86581. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  86582. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  86583. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  86584. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  86585. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  86586. #endif /* SQLITE_CORE */
  86587. #ifndef SQLITE_CORE
  86588. /* This case when the file really is being compiled as a loadable
  86589. ** extension */
  86590. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  86591. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  86592. #else
  86593. /* This case when the file is being statically linked into the
  86594. ** application */
  86595. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  86596. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  86597. #endif
  86598. #endif /* _SQLITE3EXT_H_ */
  86599. /************** End of sqlite3ext.h ******************************************/
  86600. /************** Continuing where we left off in loadext.c ********************/
  86601. /* #include <string.h> */
  86602. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  86603. /*
  86604. ** Some API routines are omitted when various features are
  86605. ** excluded from a build of SQLite. Substitute a NULL pointer
  86606. ** for any missing APIs.
  86607. */
  86608. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  86609. # define sqlite3_column_database_name 0
  86610. # define sqlite3_column_database_name16 0
  86611. # define sqlite3_column_table_name 0
  86612. # define sqlite3_column_table_name16 0
  86613. # define sqlite3_column_origin_name 0
  86614. # define sqlite3_column_origin_name16 0
  86615. # define sqlite3_table_column_metadata 0
  86616. #endif
  86617. #ifdef SQLITE_OMIT_AUTHORIZATION
  86618. # define sqlite3_set_authorizer 0
  86619. #endif
  86620. #ifdef SQLITE_OMIT_UTF16
  86621. # define sqlite3_bind_text16 0
  86622. # define sqlite3_collation_needed16 0
  86623. # define sqlite3_column_decltype16 0
  86624. # define sqlite3_column_name16 0
  86625. # define sqlite3_column_text16 0
  86626. # define sqlite3_complete16 0
  86627. # define sqlite3_create_collation16 0
  86628. # define sqlite3_create_function16 0
  86629. # define sqlite3_errmsg16 0
  86630. # define sqlite3_open16 0
  86631. # define sqlite3_prepare16 0
  86632. # define sqlite3_prepare16_v2 0
  86633. # define sqlite3_result_error16 0
  86634. # define sqlite3_result_text16 0
  86635. # define sqlite3_result_text16be 0
  86636. # define sqlite3_result_text16le 0
  86637. # define sqlite3_value_text16 0
  86638. # define sqlite3_value_text16be 0
  86639. # define sqlite3_value_text16le 0
  86640. # define sqlite3_column_database_name16 0
  86641. # define sqlite3_column_table_name16 0
  86642. # define sqlite3_column_origin_name16 0
  86643. #endif
  86644. #ifdef SQLITE_OMIT_COMPLETE
  86645. # define sqlite3_complete 0
  86646. # define sqlite3_complete16 0
  86647. #endif
  86648. #ifdef SQLITE_OMIT_DECLTYPE
  86649. # define sqlite3_column_decltype16 0
  86650. # define sqlite3_column_decltype 0
  86651. #endif
  86652. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  86653. # define sqlite3_progress_handler 0
  86654. #endif
  86655. #ifdef SQLITE_OMIT_VIRTUALTABLE
  86656. # define sqlite3_create_module 0
  86657. # define sqlite3_create_module_v2 0
  86658. # define sqlite3_declare_vtab 0
  86659. # define sqlite3_vtab_config 0
  86660. # define sqlite3_vtab_on_conflict 0
  86661. #endif
  86662. #ifdef SQLITE_OMIT_SHARED_CACHE
  86663. # define sqlite3_enable_shared_cache 0
  86664. #endif
  86665. #ifdef SQLITE_OMIT_TRACE
  86666. # define sqlite3_profile 0
  86667. # define sqlite3_trace 0
  86668. #endif
  86669. #ifdef SQLITE_OMIT_GET_TABLE
  86670. # define sqlite3_free_table 0
  86671. # define sqlite3_get_table 0
  86672. #endif
  86673. #ifdef SQLITE_OMIT_INCRBLOB
  86674. #define sqlite3_bind_zeroblob 0
  86675. #define sqlite3_blob_bytes 0
  86676. #define sqlite3_blob_close 0
  86677. #define sqlite3_blob_open 0
  86678. #define sqlite3_blob_read 0
  86679. #define sqlite3_blob_write 0
  86680. #define sqlite3_blob_reopen 0
  86681. #endif
  86682. /*
  86683. ** The following structure contains pointers to all SQLite API routines.
  86684. ** A pointer to this structure is passed into extensions when they are
  86685. ** loaded so that the extension can make calls back into the SQLite
  86686. ** library.
  86687. **
  86688. ** When adding new APIs, add them to the bottom of this structure
  86689. ** in order to preserve backwards compatibility.
  86690. **
  86691. ** Extensions that use newer APIs should first call the
  86692. ** sqlite3_libversion_number() to make sure that the API they
  86693. ** intend to use is supported by the library. Extensions should
  86694. ** also check to make sure that the pointer to the function is
  86695. ** not NULL before calling it.
  86696. */
  86697. static const sqlite3_api_routines sqlite3Apis = {
  86698. sqlite3_aggregate_context,
  86699. #ifndef SQLITE_OMIT_DEPRECATED
  86700. sqlite3_aggregate_count,
  86701. #else
  86702. 0,
  86703. #endif
  86704. sqlite3_bind_blob,
  86705. sqlite3_bind_double,
  86706. sqlite3_bind_int,
  86707. sqlite3_bind_int64,
  86708. sqlite3_bind_null,
  86709. sqlite3_bind_parameter_count,
  86710. sqlite3_bind_parameter_index,
  86711. sqlite3_bind_parameter_name,
  86712. sqlite3_bind_text,
  86713. sqlite3_bind_text16,
  86714. sqlite3_bind_value,
  86715. sqlite3_busy_handler,
  86716. sqlite3_busy_timeout,
  86717. sqlite3_changes,
  86718. sqlite3_close,
  86719. sqlite3_collation_needed,
  86720. sqlite3_collation_needed16,
  86721. sqlite3_column_blob,
  86722. sqlite3_column_bytes,
  86723. sqlite3_column_bytes16,
  86724. sqlite3_column_count,
  86725. sqlite3_column_database_name,
  86726. sqlite3_column_database_name16,
  86727. sqlite3_column_decltype,
  86728. sqlite3_column_decltype16,
  86729. sqlite3_column_double,
  86730. sqlite3_column_int,
  86731. sqlite3_column_int64,
  86732. sqlite3_column_name,
  86733. sqlite3_column_name16,
  86734. sqlite3_column_origin_name,
  86735. sqlite3_column_origin_name16,
  86736. sqlite3_column_table_name,
  86737. sqlite3_column_table_name16,
  86738. sqlite3_column_text,
  86739. sqlite3_column_text16,
  86740. sqlite3_column_type,
  86741. sqlite3_column_value,
  86742. sqlite3_commit_hook,
  86743. sqlite3_complete,
  86744. sqlite3_complete16,
  86745. sqlite3_create_collation,
  86746. sqlite3_create_collation16,
  86747. sqlite3_create_function,
  86748. sqlite3_create_function16,
  86749. sqlite3_create_module,
  86750. sqlite3_data_count,
  86751. sqlite3_db_handle,
  86752. sqlite3_declare_vtab,
  86753. sqlite3_enable_shared_cache,
  86754. sqlite3_errcode,
  86755. sqlite3_errmsg,
  86756. sqlite3_errmsg16,
  86757. sqlite3_exec,
  86758. #ifndef SQLITE_OMIT_DEPRECATED
  86759. sqlite3_expired,
  86760. #else
  86761. 0,
  86762. #endif
  86763. sqlite3_finalize,
  86764. sqlite3_free,
  86765. sqlite3_free_table,
  86766. sqlite3_get_autocommit,
  86767. sqlite3_get_auxdata,
  86768. sqlite3_get_table,
  86769. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  86770. sqlite3_interrupt,
  86771. sqlite3_last_insert_rowid,
  86772. sqlite3_libversion,
  86773. sqlite3_libversion_number,
  86774. sqlite3_malloc,
  86775. sqlite3_mprintf,
  86776. sqlite3_open,
  86777. sqlite3_open16,
  86778. sqlite3_prepare,
  86779. sqlite3_prepare16,
  86780. sqlite3_profile,
  86781. sqlite3_progress_handler,
  86782. sqlite3_realloc,
  86783. sqlite3_reset,
  86784. sqlite3_result_blob,
  86785. sqlite3_result_double,
  86786. sqlite3_result_error,
  86787. sqlite3_result_error16,
  86788. sqlite3_result_int,
  86789. sqlite3_result_int64,
  86790. sqlite3_result_null,
  86791. sqlite3_result_text,
  86792. sqlite3_result_text16,
  86793. sqlite3_result_text16be,
  86794. sqlite3_result_text16le,
  86795. sqlite3_result_value,
  86796. sqlite3_rollback_hook,
  86797. sqlite3_set_authorizer,
  86798. sqlite3_set_auxdata,
  86799. sqlite3_snprintf,
  86800. sqlite3_step,
  86801. sqlite3_table_column_metadata,
  86802. #ifndef SQLITE_OMIT_DEPRECATED
  86803. sqlite3_thread_cleanup,
  86804. #else
  86805. 0,
  86806. #endif
  86807. sqlite3_total_changes,
  86808. sqlite3_trace,
  86809. #ifndef SQLITE_OMIT_DEPRECATED
  86810. sqlite3_transfer_bindings,
  86811. #else
  86812. 0,
  86813. #endif
  86814. sqlite3_update_hook,
  86815. sqlite3_user_data,
  86816. sqlite3_value_blob,
  86817. sqlite3_value_bytes,
  86818. sqlite3_value_bytes16,
  86819. sqlite3_value_double,
  86820. sqlite3_value_int,
  86821. sqlite3_value_int64,
  86822. sqlite3_value_numeric_type,
  86823. sqlite3_value_text,
  86824. sqlite3_value_text16,
  86825. sqlite3_value_text16be,
  86826. sqlite3_value_text16le,
  86827. sqlite3_value_type,
  86828. sqlite3_vmprintf,
  86829. /*
  86830. ** The original API set ends here. All extensions can call any
  86831. ** of the APIs above provided that the pointer is not NULL. But
  86832. ** before calling APIs that follow, extension should check the
  86833. ** sqlite3_libversion_number() to make sure they are dealing with
  86834. ** a library that is new enough to support that API.
  86835. *************************************************************************
  86836. */
  86837. sqlite3_overload_function,
  86838. /*
  86839. ** Added after 3.3.13
  86840. */
  86841. sqlite3_prepare_v2,
  86842. sqlite3_prepare16_v2,
  86843. sqlite3_clear_bindings,
  86844. /*
  86845. ** Added for 3.4.1
  86846. */
  86847. sqlite3_create_module_v2,
  86848. /*
  86849. ** Added for 3.5.0
  86850. */
  86851. sqlite3_bind_zeroblob,
  86852. sqlite3_blob_bytes,
  86853. sqlite3_blob_close,
  86854. sqlite3_blob_open,
  86855. sqlite3_blob_read,
  86856. sqlite3_blob_write,
  86857. sqlite3_create_collation_v2,
  86858. sqlite3_file_control,
  86859. sqlite3_memory_highwater,
  86860. sqlite3_memory_used,
  86861. #ifdef SQLITE_MUTEX_OMIT
  86862. 0,
  86863. 0,
  86864. 0,
  86865. 0,
  86866. 0,
  86867. #else
  86868. sqlite3_mutex_alloc,
  86869. sqlite3_mutex_enter,
  86870. sqlite3_mutex_free,
  86871. sqlite3_mutex_leave,
  86872. sqlite3_mutex_try,
  86873. #endif
  86874. sqlite3_open_v2,
  86875. sqlite3_release_memory,
  86876. sqlite3_result_error_nomem,
  86877. sqlite3_result_error_toobig,
  86878. sqlite3_sleep,
  86879. sqlite3_soft_heap_limit,
  86880. sqlite3_vfs_find,
  86881. sqlite3_vfs_register,
  86882. sqlite3_vfs_unregister,
  86883. /*
  86884. ** Added for 3.5.8
  86885. */
  86886. sqlite3_threadsafe,
  86887. sqlite3_result_zeroblob,
  86888. sqlite3_result_error_code,
  86889. sqlite3_test_control,
  86890. sqlite3_randomness,
  86891. sqlite3_context_db_handle,
  86892. /*
  86893. ** Added for 3.6.0
  86894. */
  86895. sqlite3_extended_result_codes,
  86896. sqlite3_limit,
  86897. sqlite3_next_stmt,
  86898. sqlite3_sql,
  86899. sqlite3_status,
  86900. /*
  86901. ** Added for 3.7.4
  86902. */
  86903. sqlite3_backup_finish,
  86904. sqlite3_backup_init,
  86905. sqlite3_backup_pagecount,
  86906. sqlite3_backup_remaining,
  86907. sqlite3_backup_step,
  86908. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  86909. sqlite3_compileoption_get,
  86910. sqlite3_compileoption_used,
  86911. #else
  86912. 0,
  86913. 0,
  86914. #endif
  86915. sqlite3_create_function_v2,
  86916. sqlite3_db_config,
  86917. sqlite3_db_mutex,
  86918. sqlite3_db_status,
  86919. sqlite3_extended_errcode,
  86920. sqlite3_log,
  86921. sqlite3_soft_heap_limit64,
  86922. sqlite3_sourceid,
  86923. sqlite3_stmt_status,
  86924. sqlite3_strnicmp,
  86925. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  86926. sqlite3_unlock_notify,
  86927. #else
  86928. 0,
  86929. #endif
  86930. #ifndef SQLITE_OMIT_WAL
  86931. sqlite3_wal_autocheckpoint,
  86932. sqlite3_wal_checkpoint,
  86933. sqlite3_wal_hook,
  86934. #else
  86935. 0,
  86936. 0,
  86937. 0,
  86938. #endif
  86939. sqlite3_blob_reopen,
  86940. sqlite3_vtab_config,
  86941. sqlite3_vtab_on_conflict,
  86942. sqlite3_close_v2,
  86943. sqlite3_db_filename,
  86944. sqlite3_db_readonly,
  86945. sqlite3_db_release_memory,
  86946. sqlite3_errstr,
  86947. sqlite3_stmt_busy,
  86948. sqlite3_stmt_readonly,
  86949. sqlite3_stricmp,
  86950. sqlite3_uri_boolean,
  86951. sqlite3_uri_int64,
  86952. sqlite3_uri_parameter,
  86953. sqlite3_vsnprintf,
  86954. sqlite3_wal_checkpoint_v2
  86955. };
  86956. /*
  86957. ** Attempt to load an SQLite extension library contained in the file
  86958. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  86959. ** default entry point name (sqlite3_extension_init) is used. Use
  86960. ** of the default name is recommended.
  86961. **
  86962. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  86963. **
  86964. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  86965. ** error message text. The calling function should free this memory
  86966. ** by calling sqlite3DbFree(db, ).
  86967. */
  86968. static int sqlite3LoadExtension(
  86969. sqlite3 *db, /* Load the extension into this database connection */
  86970. const char *zFile, /* Name of the shared library containing extension */
  86971. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  86972. char **pzErrMsg /* Put error message here if not 0 */
  86973. ){
  86974. sqlite3_vfs *pVfs = db->pVfs;
  86975. void *handle;
  86976. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  86977. char *zErrmsg = 0;
  86978. const char *zEntry;
  86979. char *zAltEntry = 0;
  86980. void **aHandle;
  86981. int nMsg = 300 + sqlite3Strlen30(zFile);
  86982. int ii;
  86983. /* Shared library endings to try if zFile cannot be loaded as written */
  86984. static const char *azEndings[] = {
  86985. #if SQLITE_OS_WIN
  86986. "dll"
  86987. #elif defined(__APPLE__)
  86988. "dylib"
  86989. #else
  86990. "so"
  86991. #endif
  86992. };
  86993. if( pzErrMsg ) *pzErrMsg = 0;
  86994. /* Ticket #1863. To avoid a creating security problems for older
  86995. ** applications that relink against newer versions of SQLite, the
  86996. ** ability to run load_extension is turned off by default. One
  86997. ** must call sqlite3_enable_load_extension() to turn on extension
  86998. ** loading. Otherwise you get the following error.
  86999. */
  87000. if( (db->flags & SQLITE_LoadExtension)==0 ){
  87001. if( pzErrMsg ){
  87002. *pzErrMsg = sqlite3_mprintf("not authorized");
  87003. }
  87004. return SQLITE_ERROR;
  87005. }
  87006. zEntry = zProc ? zProc : "sqlite3_extension_init";
  87007. handle = sqlite3OsDlOpen(pVfs, zFile);
  87008. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  87009. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  87010. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  87011. if( zAltFile==0 ) return SQLITE_NOMEM;
  87012. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  87013. sqlite3_free(zAltFile);
  87014. }
  87015. #endif
  87016. if( handle==0 ){
  87017. if( pzErrMsg ){
  87018. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  87019. if( zErrmsg ){
  87020. sqlite3_snprintf(nMsg, zErrmsg,
  87021. "unable to open shared library [%s]", zFile);
  87022. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  87023. }
  87024. }
  87025. return SQLITE_ERROR;
  87026. }
  87027. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  87028. sqlite3OsDlSym(pVfs, handle, zEntry);
  87029. /* If no entry point was specified and the default legacy
  87030. ** entry point name "sqlite3_extension_init" was not found, then
  87031. ** construct an entry point name "sqlite3_X_init" where the X is
  87032. ** replaced by the lowercase value of every ASCII alphabetic
  87033. ** character in the filename after the last "/" upto the first ".",
  87034. ** and eliding the first three characters if they are "lib".
  87035. ** Examples:
  87036. **
  87037. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  87038. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  87039. */
  87040. if( xInit==0 && zProc==0 ){
  87041. int iFile, iEntry, c;
  87042. int ncFile = sqlite3Strlen30(zFile);
  87043. zAltEntry = sqlite3_malloc(ncFile+30);
  87044. if( zAltEntry==0 ){
  87045. sqlite3OsDlClose(pVfs, handle);
  87046. return SQLITE_NOMEM;
  87047. }
  87048. memcpy(zAltEntry, "sqlite3_", 8);
  87049. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  87050. iFile++;
  87051. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  87052. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  87053. if( sqlite3Isalpha(c) ){
  87054. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  87055. }
  87056. }
  87057. memcpy(zAltEntry+iEntry, "_init", 6);
  87058. zEntry = zAltEntry;
  87059. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  87060. sqlite3OsDlSym(pVfs, handle, zEntry);
  87061. }
  87062. if( xInit==0 ){
  87063. if( pzErrMsg ){
  87064. nMsg += sqlite3Strlen30(zEntry);
  87065. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  87066. if( zErrmsg ){
  87067. sqlite3_snprintf(nMsg, zErrmsg,
  87068. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  87069. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  87070. }
  87071. }
  87072. sqlite3OsDlClose(pVfs, handle);
  87073. sqlite3_free(zAltEntry);
  87074. return SQLITE_ERROR;
  87075. }
  87076. sqlite3_free(zAltEntry);
  87077. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  87078. if( pzErrMsg ){
  87079. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  87080. }
  87081. sqlite3_free(zErrmsg);
  87082. sqlite3OsDlClose(pVfs, handle);
  87083. return SQLITE_ERROR;
  87084. }
  87085. /* Append the new shared library handle to the db->aExtension array. */
  87086. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  87087. if( aHandle==0 ){
  87088. return SQLITE_NOMEM;
  87089. }
  87090. if( db->nExtension>0 ){
  87091. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  87092. }
  87093. sqlite3DbFree(db, db->aExtension);
  87094. db->aExtension = aHandle;
  87095. db->aExtension[db->nExtension++] = handle;
  87096. return SQLITE_OK;
  87097. }
  87098. SQLITE_API int sqlite3_load_extension(
  87099. sqlite3 *db, /* Load the extension into this database connection */
  87100. const char *zFile, /* Name of the shared library containing extension */
  87101. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  87102. char **pzErrMsg /* Put error message here if not 0 */
  87103. ){
  87104. int rc;
  87105. sqlite3_mutex_enter(db->mutex);
  87106. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  87107. rc = sqlite3ApiExit(db, rc);
  87108. sqlite3_mutex_leave(db->mutex);
  87109. return rc;
  87110. }
  87111. /*
  87112. ** Call this routine when the database connection is closing in order
  87113. ** to clean up loaded extensions
  87114. */
  87115. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  87116. int i;
  87117. assert( sqlite3_mutex_held(db->mutex) );
  87118. for(i=0; i<db->nExtension; i++){
  87119. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  87120. }
  87121. sqlite3DbFree(db, db->aExtension);
  87122. }
  87123. /*
  87124. ** Enable or disable extension loading. Extension loading is disabled by
  87125. ** default so as not to open security holes in older applications.
  87126. */
  87127. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  87128. sqlite3_mutex_enter(db->mutex);
  87129. if( onoff ){
  87130. db->flags |= SQLITE_LoadExtension;
  87131. }else{
  87132. db->flags &= ~SQLITE_LoadExtension;
  87133. }
  87134. sqlite3_mutex_leave(db->mutex);
  87135. return SQLITE_OK;
  87136. }
  87137. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  87138. /*
  87139. ** The auto-extension code added regardless of whether or not extension
  87140. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  87141. ** code if regular extension loading is not available. This is that
  87142. ** dummy pointer.
  87143. */
  87144. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  87145. static const sqlite3_api_routines sqlite3Apis = { 0 };
  87146. #endif
  87147. /*
  87148. ** The following object holds the list of automatically loaded
  87149. ** extensions.
  87150. **
  87151. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  87152. ** mutex must be held while accessing this list.
  87153. */
  87154. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  87155. static SQLITE_WSD struct sqlite3AutoExtList {
  87156. int nExt; /* Number of entries in aExt[] */
  87157. void (**aExt)(void); /* Pointers to the extension init functions */
  87158. } sqlite3Autoext = { 0, 0 };
  87159. /* The "wsdAutoext" macro will resolve to the autoextension
  87160. ** state vector. If writable static data is unsupported on the target,
  87161. ** we have to locate the state vector at run-time. In the more common
  87162. ** case where writable static data is supported, wsdStat can refer directly
  87163. ** to the "sqlite3Autoext" state vector declared above.
  87164. */
  87165. #ifdef SQLITE_OMIT_WSD
  87166. # define wsdAutoextInit \
  87167. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  87168. # define wsdAutoext x[0]
  87169. #else
  87170. # define wsdAutoextInit
  87171. # define wsdAutoext sqlite3Autoext
  87172. #endif
  87173. /*
  87174. ** Register a statically linked extension that is automatically
  87175. ** loaded by every new database connection.
  87176. */
  87177. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  87178. int rc = SQLITE_OK;
  87179. #ifndef SQLITE_OMIT_AUTOINIT
  87180. rc = sqlite3_initialize();
  87181. if( rc ){
  87182. return rc;
  87183. }else
  87184. #endif
  87185. {
  87186. int i;
  87187. #if SQLITE_THREADSAFE
  87188. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  87189. #endif
  87190. wsdAutoextInit;
  87191. sqlite3_mutex_enter(mutex);
  87192. for(i=0; i<wsdAutoext.nExt; i++){
  87193. if( wsdAutoext.aExt[i]==xInit ) break;
  87194. }
  87195. if( i==wsdAutoext.nExt ){
  87196. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  87197. void (**aNew)(void);
  87198. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  87199. if( aNew==0 ){
  87200. rc = SQLITE_NOMEM;
  87201. }else{
  87202. wsdAutoext.aExt = aNew;
  87203. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  87204. wsdAutoext.nExt++;
  87205. }
  87206. }
  87207. sqlite3_mutex_leave(mutex);
  87208. assert( (rc&0xff)==rc );
  87209. return rc;
  87210. }
  87211. }
  87212. /*
  87213. ** Reset the automatic extension loading mechanism.
  87214. */
  87215. SQLITE_API void sqlite3_reset_auto_extension(void){
  87216. #ifndef SQLITE_OMIT_AUTOINIT
  87217. if( sqlite3_initialize()==SQLITE_OK )
  87218. #endif
  87219. {
  87220. #if SQLITE_THREADSAFE
  87221. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  87222. #endif
  87223. wsdAutoextInit;
  87224. sqlite3_mutex_enter(mutex);
  87225. sqlite3_free(wsdAutoext.aExt);
  87226. wsdAutoext.aExt = 0;
  87227. wsdAutoext.nExt = 0;
  87228. sqlite3_mutex_leave(mutex);
  87229. }
  87230. }
  87231. /*
  87232. ** Load all automatic extensions.
  87233. **
  87234. ** If anything goes wrong, set an error in the database connection.
  87235. */
  87236. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  87237. int i;
  87238. int go = 1;
  87239. int rc;
  87240. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  87241. wsdAutoextInit;
  87242. if( wsdAutoext.nExt==0 ){
  87243. /* Common case: early out without every having to acquire a mutex */
  87244. return;
  87245. }
  87246. for(i=0; go; i++){
  87247. char *zErrmsg;
  87248. #if SQLITE_THREADSAFE
  87249. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  87250. #endif
  87251. sqlite3_mutex_enter(mutex);
  87252. if( i>=wsdAutoext.nExt ){
  87253. xInit = 0;
  87254. go = 0;
  87255. }else{
  87256. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  87257. wsdAutoext.aExt[i];
  87258. }
  87259. sqlite3_mutex_leave(mutex);
  87260. zErrmsg = 0;
  87261. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  87262. sqlite3Error(db, rc,
  87263. "automatic extension loading failed: %s", zErrmsg);
  87264. go = 0;
  87265. }
  87266. sqlite3_free(zErrmsg);
  87267. }
  87268. }
  87269. /************** End of loadext.c *********************************************/
  87270. /************** Begin file pragma.c ******************************************/
  87271. /*
  87272. ** 2003 April 6
  87273. **
  87274. ** The author disclaims copyright to this source code. In place of
  87275. ** a legal notice, here is a blessing:
  87276. **
  87277. ** May you do good and not evil.
  87278. ** May you find forgiveness for yourself and forgive others.
  87279. ** May you share freely, never taking more than you give.
  87280. **
  87281. *************************************************************************
  87282. ** This file contains code used to implement the PRAGMA command.
  87283. */
  87284. /*
  87285. ** Interpret the given string as a safety level. Return 0 for OFF,
  87286. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  87287. ** unrecognized string argument. The FULL option is disallowed
  87288. ** if the omitFull parameter it 1.
  87289. **
  87290. ** Note that the values returned are one less that the values that
  87291. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  87292. ** to support legacy SQL code. The safety level used to be boolean
  87293. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  87294. */
  87295. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  87296. /* 123456789 123456789 */
  87297. static const char zText[] = "onoffalseyestruefull";
  87298. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  87299. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  87300. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  87301. int i, n;
  87302. if( sqlite3Isdigit(*z) ){
  87303. return (u8)sqlite3Atoi(z);
  87304. }
  87305. n = sqlite3Strlen30(z);
  87306. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  87307. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  87308. return iValue[i];
  87309. }
  87310. }
  87311. return dflt;
  87312. }
  87313. /*
  87314. ** Interpret the given string as a boolean value.
  87315. */
  87316. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  87317. return getSafetyLevel(z,1,dflt)!=0;
  87318. }
  87319. /* The sqlite3GetBoolean() function is used by other modules but the
  87320. ** remainder of this file is specific to PRAGMA processing. So omit
  87321. ** the rest of the file if PRAGMAs are omitted from the build.
  87322. */
  87323. #if !defined(SQLITE_OMIT_PRAGMA)
  87324. /*
  87325. ** Interpret the given string as a locking mode value.
  87326. */
  87327. static int getLockingMode(const char *z){
  87328. if( z ){
  87329. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  87330. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  87331. }
  87332. return PAGER_LOCKINGMODE_QUERY;
  87333. }
  87334. #ifndef SQLITE_OMIT_AUTOVACUUM
  87335. /*
  87336. ** Interpret the given string as an auto-vacuum mode value.
  87337. **
  87338. ** The following strings, "none", "full" and "incremental" are
  87339. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  87340. */
  87341. static int getAutoVacuum(const char *z){
  87342. int i;
  87343. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  87344. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  87345. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  87346. i = sqlite3Atoi(z);
  87347. return (u8)((i>=0&&i<=2)?i:0);
  87348. }
  87349. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  87350. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87351. /*
  87352. ** Interpret the given string as a temp db location. Return 1 for file
  87353. ** backed temporary databases, 2 for the Red-Black tree in memory database
  87354. ** and 0 to use the compile-time default.
  87355. */
  87356. static int getTempStore(const char *z){
  87357. if( z[0]>='0' && z[0]<='2' ){
  87358. return z[0] - '0';
  87359. }else if( sqlite3StrICmp(z, "file")==0 ){
  87360. return 1;
  87361. }else if( sqlite3StrICmp(z, "memory")==0 ){
  87362. return 2;
  87363. }else{
  87364. return 0;
  87365. }
  87366. }
  87367. #endif /* SQLITE_PAGER_PRAGMAS */
  87368. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87369. /*
  87370. ** Invalidate temp storage, either when the temp storage is changed
  87371. ** from default, or when 'file' and the temp_store_directory has changed
  87372. */
  87373. static int invalidateTempStorage(Parse *pParse){
  87374. sqlite3 *db = pParse->db;
  87375. if( db->aDb[1].pBt!=0 ){
  87376. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  87377. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  87378. "from within a transaction");
  87379. return SQLITE_ERROR;
  87380. }
  87381. sqlite3BtreeClose(db->aDb[1].pBt);
  87382. db->aDb[1].pBt = 0;
  87383. sqlite3ResetAllSchemasOfConnection(db);
  87384. }
  87385. return SQLITE_OK;
  87386. }
  87387. #endif /* SQLITE_PAGER_PRAGMAS */
  87388. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87389. /*
  87390. ** If the TEMP database is open, close it and mark the database schema
  87391. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  87392. ** or DEFAULT_TEMP_STORE pragmas.
  87393. */
  87394. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  87395. int ts = getTempStore(zStorageType);
  87396. sqlite3 *db = pParse->db;
  87397. if( db->temp_store==ts ) return SQLITE_OK;
  87398. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  87399. return SQLITE_ERROR;
  87400. }
  87401. db->temp_store = (u8)ts;
  87402. return SQLITE_OK;
  87403. }
  87404. #endif /* SQLITE_PAGER_PRAGMAS */
  87405. /*
  87406. ** Generate code to return a single integer value.
  87407. */
  87408. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  87409. Vdbe *v = sqlite3GetVdbe(pParse);
  87410. int mem = ++pParse->nMem;
  87411. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  87412. if( pI64 ){
  87413. memcpy(pI64, &value, sizeof(value));
  87414. }
  87415. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  87416. sqlite3VdbeSetNumCols(v, 1);
  87417. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  87418. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  87419. }
  87420. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  87421. /*
  87422. ** Check to see if zRight and zLeft refer to a pragma that queries
  87423. ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  87424. ** Also, implement the pragma.
  87425. */
  87426. static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  87427. static const struct sPragmaType {
  87428. const char *zName; /* Name of the pragma */
  87429. int mask; /* Mask for the db->flags value */
  87430. } aPragma[] = {
  87431. { "full_column_names", SQLITE_FullColNames },
  87432. { "short_column_names", SQLITE_ShortColNames },
  87433. { "count_changes", SQLITE_CountRows },
  87434. { "empty_result_callbacks", SQLITE_NullCallback },
  87435. { "legacy_file_format", SQLITE_LegacyFileFmt },
  87436. { "fullfsync", SQLITE_FullFSync },
  87437. { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
  87438. { "reverse_unordered_selects", SQLITE_ReverseOrder },
  87439. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  87440. { "automatic_index", SQLITE_AutoIndex },
  87441. #endif
  87442. #ifdef SQLITE_DEBUG
  87443. { "sql_trace", SQLITE_SqlTrace },
  87444. { "vdbe_listing", SQLITE_VdbeListing },
  87445. { "vdbe_trace", SQLITE_VdbeTrace },
  87446. { "vdbe_addoptrace", SQLITE_VdbeAddopTrace},
  87447. { "vdbe_debug", SQLITE_SqlTrace | SQLITE_VdbeListing
  87448. | SQLITE_VdbeTrace },
  87449. #endif
  87450. #ifndef SQLITE_OMIT_CHECK
  87451. { "ignore_check_constraints", SQLITE_IgnoreChecks },
  87452. #endif
  87453. /* The following is VERY experimental */
  87454. { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
  87455. /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
  87456. ** flag if there are any active statements. */
  87457. { "read_uncommitted", SQLITE_ReadUncommitted },
  87458. { "recursive_triggers", SQLITE_RecTriggers },
  87459. /* This flag may only be set if both foreign-key and trigger support
  87460. ** are present in the build. */
  87461. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  87462. { "foreign_keys", SQLITE_ForeignKeys },
  87463. #endif
  87464. };
  87465. int i;
  87466. const struct sPragmaType *p;
  87467. for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
  87468. if( sqlite3StrICmp(zLeft, p->zName)==0 ){
  87469. sqlite3 *db = pParse->db;
  87470. Vdbe *v;
  87471. v = sqlite3GetVdbe(pParse);
  87472. assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
  87473. if( ALWAYS(v) ){
  87474. if( zRight==0 ){
  87475. returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
  87476. }else{
  87477. int mask = p->mask; /* Mask of bits to set or clear. */
  87478. if( db->autoCommit==0 ){
  87479. /* Foreign key support may not be enabled or disabled while not
  87480. ** in auto-commit mode. */
  87481. mask &= ~(SQLITE_ForeignKeys);
  87482. }
  87483. if( sqlite3GetBoolean(zRight, 0) ){
  87484. db->flags |= mask;
  87485. }else{
  87486. db->flags &= ~mask;
  87487. }
  87488. /* Many of the flag-pragmas modify the code generated by the SQL
  87489. ** compiler (eg. count_changes). So add an opcode to expire all
  87490. ** compiled SQL statements after modifying a pragma value.
  87491. */
  87492. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  87493. }
  87494. }
  87495. return 1;
  87496. }
  87497. }
  87498. return 0;
  87499. }
  87500. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  87501. /*
  87502. ** Return a human-readable name for a constraint resolution action.
  87503. */
  87504. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87505. static const char *actionName(u8 action){
  87506. const char *zName;
  87507. switch( action ){
  87508. case OE_SetNull: zName = "SET NULL"; break;
  87509. case OE_SetDflt: zName = "SET DEFAULT"; break;
  87510. case OE_Cascade: zName = "CASCADE"; break;
  87511. case OE_Restrict: zName = "RESTRICT"; break;
  87512. default: zName = "NO ACTION";
  87513. assert( action==OE_None ); break;
  87514. }
  87515. return zName;
  87516. }
  87517. #endif
  87518. /*
  87519. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  87520. ** defined in pager.h. This function returns the associated lowercase
  87521. ** journal-mode name.
  87522. */
  87523. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  87524. static char * const azModeName[] = {
  87525. "delete", "persist", "off", "truncate", "memory"
  87526. #ifndef SQLITE_OMIT_WAL
  87527. , "wal"
  87528. #endif
  87529. };
  87530. assert( PAGER_JOURNALMODE_DELETE==0 );
  87531. assert( PAGER_JOURNALMODE_PERSIST==1 );
  87532. assert( PAGER_JOURNALMODE_OFF==2 );
  87533. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  87534. assert( PAGER_JOURNALMODE_MEMORY==4 );
  87535. assert( PAGER_JOURNALMODE_WAL==5 );
  87536. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  87537. if( eMode==ArraySize(azModeName) ) return 0;
  87538. return azModeName[eMode];
  87539. }
  87540. /*
  87541. ** Process a pragma statement.
  87542. **
  87543. ** Pragmas are of this form:
  87544. **
  87545. ** PRAGMA [database.]id [= value]
  87546. **
  87547. ** The identifier might also be a string. The value is a string, and
  87548. ** identifier, or a number. If minusFlag is true, then the value is
  87549. ** a number that was preceded by a minus sign.
  87550. **
  87551. ** If the left side is "database.id" then pId1 is the database name
  87552. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  87553. ** id and pId2 is any empty string.
  87554. */
  87555. SQLITE_PRIVATE void sqlite3Pragma(
  87556. Parse *pParse,
  87557. Token *pId1, /* First part of [database.]id field */
  87558. Token *pId2, /* Second part of [database.]id field, or NULL */
  87559. Token *pValue, /* Token for <value>, or NULL */
  87560. int minusFlag /* True if a '-' sign preceded <value> */
  87561. ){
  87562. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  87563. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  87564. const char *zDb = 0; /* The database name */
  87565. Token *pId; /* Pointer to <id> token */
  87566. int iDb; /* Database index for <database> */
  87567. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  87568. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  87569. sqlite3 *db = pParse->db; /* The database connection */
  87570. Db *pDb; /* The specific database being pragmaed */
  87571. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  87572. if( v==0 ) return;
  87573. sqlite3VdbeRunOnlyOnce(v);
  87574. pParse->nMem = 2;
  87575. /* Interpret the [database.] part of the pragma statement. iDb is the
  87576. ** index of the database this pragma is being applied to in db.aDb[]. */
  87577. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  87578. if( iDb<0 ) return;
  87579. pDb = &db->aDb[iDb];
  87580. /* If the temp database has been explicitly named as part of the
  87581. ** pragma, make sure it is open.
  87582. */
  87583. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  87584. return;
  87585. }
  87586. zLeft = sqlite3NameFromToken(db, pId);
  87587. if( !zLeft ) return;
  87588. if( minusFlag ){
  87589. zRight = sqlite3MPrintf(db, "-%T", pValue);
  87590. }else{
  87591. zRight = sqlite3NameFromToken(db, pValue);
  87592. }
  87593. assert( pId2 );
  87594. zDb = pId2->n>0 ? pDb->zName : 0;
  87595. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  87596. goto pragma_out;
  87597. }
  87598. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  87599. ** connection. If it returns SQLITE_OK, then assume that the VFS
  87600. ** handled the pragma and generate a no-op prepared statement.
  87601. */
  87602. aFcntl[0] = 0;
  87603. aFcntl[1] = zLeft;
  87604. aFcntl[2] = zRight;
  87605. aFcntl[3] = 0;
  87606. db->busyHandler.nBusy = 0;
  87607. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  87608. if( rc==SQLITE_OK ){
  87609. if( aFcntl[0] ){
  87610. int mem = ++pParse->nMem;
  87611. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  87612. sqlite3VdbeSetNumCols(v, 1);
  87613. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  87614. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  87615. sqlite3_free(aFcntl[0]);
  87616. }
  87617. }else if( rc!=SQLITE_NOTFOUND ){
  87618. if( aFcntl[0] ){
  87619. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  87620. sqlite3_free(aFcntl[0]);
  87621. }
  87622. pParse->nErr++;
  87623. pParse->rc = rc;
  87624. }else
  87625. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  87626. /*
  87627. ** PRAGMA [database.]default_cache_size
  87628. ** PRAGMA [database.]default_cache_size=N
  87629. **
  87630. ** The first form reports the current persistent setting for the
  87631. ** page cache size. The value returned is the maximum number of
  87632. ** pages in the page cache. The second form sets both the current
  87633. ** page cache size value and the persistent page cache size value
  87634. ** stored in the database file.
  87635. **
  87636. ** Older versions of SQLite would set the default cache size to a
  87637. ** negative number to indicate synchronous=OFF. These days, synchronous
  87638. ** is always on by default regardless of the sign of the default cache
  87639. ** size. But continue to take the absolute value of the default cache
  87640. ** size of historical compatibility.
  87641. */
  87642. if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
  87643. static const VdbeOpList getCacheSize[] = {
  87644. { OP_Transaction, 0, 0, 0}, /* 0 */
  87645. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  87646. { OP_IfPos, 1, 8, 0},
  87647. { OP_Integer, 0, 2, 0},
  87648. { OP_Subtract, 1, 2, 1},
  87649. { OP_IfPos, 1, 8, 0},
  87650. { OP_Integer, 0, 1, 0}, /* 6 */
  87651. { OP_Noop, 0, 0, 0},
  87652. { OP_ResultRow, 1, 1, 0},
  87653. };
  87654. int addr;
  87655. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  87656. sqlite3VdbeUsesBtree(v, iDb);
  87657. if( !zRight ){
  87658. sqlite3VdbeSetNumCols(v, 1);
  87659. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  87660. pParse->nMem += 2;
  87661. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  87662. sqlite3VdbeChangeP1(v, addr, iDb);
  87663. sqlite3VdbeChangeP1(v, addr+1, iDb);
  87664. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  87665. }else{
  87666. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  87667. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87668. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  87669. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  87670. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87671. pDb->pSchema->cache_size = size;
  87672. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  87673. }
  87674. }else
  87675. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  87676. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  87677. /*
  87678. ** PRAGMA [database.]page_size
  87679. ** PRAGMA [database.]page_size=N
  87680. **
  87681. ** The first form reports the current setting for the
  87682. ** database page size in bytes. The second form sets the
  87683. ** database page size value. The value can only be set if
  87684. ** the database has not yet been created.
  87685. */
  87686. if( sqlite3StrICmp(zLeft,"page_size")==0 ){
  87687. Btree *pBt = pDb->pBt;
  87688. assert( pBt!=0 );
  87689. if( !zRight ){
  87690. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  87691. returnSingleInt(pParse, "page_size", size);
  87692. }else{
  87693. /* Malloc may fail when setting the page-size, as there is an internal
  87694. ** buffer that the pager module resizes using sqlite3_realloc().
  87695. */
  87696. db->nextPagesize = sqlite3Atoi(zRight);
  87697. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  87698. db->mallocFailed = 1;
  87699. }
  87700. }
  87701. }else
  87702. /*
  87703. ** PRAGMA [database.]secure_delete
  87704. ** PRAGMA [database.]secure_delete=ON/OFF
  87705. **
  87706. ** The first form reports the current setting for the
  87707. ** secure_delete flag. The second form changes the secure_delete
  87708. ** flag setting and reports thenew value.
  87709. */
  87710. if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
  87711. Btree *pBt = pDb->pBt;
  87712. int b = -1;
  87713. assert( pBt!=0 );
  87714. if( zRight ){
  87715. b = sqlite3GetBoolean(zRight, 0);
  87716. }
  87717. if( pId2->n==0 && b>=0 ){
  87718. int ii;
  87719. for(ii=0; ii<db->nDb; ii++){
  87720. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  87721. }
  87722. }
  87723. b = sqlite3BtreeSecureDelete(pBt, b);
  87724. returnSingleInt(pParse, "secure_delete", b);
  87725. }else
  87726. /*
  87727. ** PRAGMA [database.]max_page_count
  87728. ** PRAGMA [database.]max_page_count=N
  87729. **
  87730. ** The first form reports the current setting for the
  87731. ** maximum number of pages in the database file. The
  87732. ** second form attempts to change this setting. Both
  87733. ** forms return the current setting.
  87734. **
  87735. ** The absolute value of N is used. This is undocumented and might
  87736. ** change. The only purpose is to provide an easy way to test
  87737. ** the sqlite3AbsInt32() function.
  87738. **
  87739. ** PRAGMA [database.]page_count
  87740. **
  87741. ** Return the number of pages in the specified database.
  87742. */
  87743. if( sqlite3StrICmp(zLeft,"page_count")==0
  87744. || sqlite3StrICmp(zLeft,"max_page_count")==0
  87745. ){
  87746. int iReg;
  87747. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  87748. sqlite3CodeVerifySchema(pParse, iDb);
  87749. iReg = ++pParse->nMem;
  87750. if( sqlite3Tolower(zLeft[0])=='p' ){
  87751. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  87752. }else{
  87753. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  87754. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  87755. }
  87756. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  87757. sqlite3VdbeSetNumCols(v, 1);
  87758. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  87759. }else
  87760. /*
  87761. ** PRAGMA [database.]locking_mode
  87762. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  87763. */
  87764. if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
  87765. const char *zRet = "normal";
  87766. int eMode = getLockingMode(zRight);
  87767. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  87768. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  87769. ** the current default locking mode (which may be different to
  87770. ** the locking-mode of the main database).
  87771. */
  87772. eMode = db->dfltLockMode;
  87773. }else{
  87774. Pager *pPager;
  87775. if( pId2->n==0 ){
  87776. /* This indicates that no database name was specified as part
  87777. ** of the PRAGMA command. In this case the locking-mode must be
  87778. ** set on all attached databases, as well as the main db file.
  87779. **
  87780. ** Also, the sqlite3.dfltLockMode variable is set so that
  87781. ** any subsequently attached databases also use the specified
  87782. ** locking mode.
  87783. */
  87784. int ii;
  87785. assert(pDb==&db->aDb[0]);
  87786. for(ii=2; ii<db->nDb; ii++){
  87787. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  87788. sqlite3PagerLockingMode(pPager, eMode);
  87789. }
  87790. db->dfltLockMode = (u8)eMode;
  87791. }
  87792. pPager = sqlite3BtreePager(pDb->pBt);
  87793. eMode = sqlite3PagerLockingMode(pPager, eMode);
  87794. }
  87795. assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
  87796. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  87797. zRet = "exclusive";
  87798. }
  87799. sqlite3VdbeSetNumCols(v, 1);
  87800. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  87801. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  87802. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  87803. }else
  87804. /*
  87805. ** PRAGMA [database.]journal_mode
  87806. ** PRAGMA [database.]journal_mode =
  87807. ** (delete|persist|off|truncate|memory|wal|off)
  87808. */
  87809. if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
  87810. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  87811. int ii; /* Loop counter */
  87812. /* Force the schema to be loaded on all databases. This causes all
  87813. ** database files to be opened and the journal_modes set. This is
  87814. ** necessary because subsequent processing must know if the databases
  87815. ** are in WAL mode. */
  87816. if( sqlite3ReadSchema(pParse) ){
  87817. goto pragma_out;
  87818. }
  87819. sqlite3VdbeSetNumCols(v, 1);
  87820. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  87821. if( zRight==0 ){
  87822. /* If there is no "=MODE" part of the pragma, do a query for the
  87823. ** current mode */
  87824. eMode = PAGER_JOURNALMODE_QUERY;
  87825. }else{
  87826. const char *zMode;
  87827. int n = sqlite3Strlen30(zRight);
  87828. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  87829. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  87830. }
  87831. if( !zMode ){
  87832. /* If the "=MODE" part does not match any known journal mode,
  87833. ** then do a query */
  87834. eMode = PAGER_JOURNALMODE_QUERY;
  87835. }
  87836. }
  87837. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  87838. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  87839. iDb = 0;
  87840. pId2->n = 1;
  87841. }
  87842. for(ii=db->nDb-1; ii>=0; ii--){
  87843. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  87844. sqlite3VdbeUsesBtree(v, ii);
  87845. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  87846. }
  87847. }
  87848. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  87849. }else
  87850. /*
  87851. ** PRAGMA [database.]journal_size_limit
  87852. ** PRAGMA [database.]journal_size_limit=N
  87853. **
  87854. ** Get or set the size limit on rollback journal files.
  87855. */
  87856. if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
  87857. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  87858. i64 iLimit = -2;
  87859. if( zRight ){
  87860. sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
  87861. if( iLimit<-1 ) iLimit = -1;
  87862. }
  87863. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  87864. returnSingleInt(pParse, "journal_size_limit", iLimit);
  87865. }else
  87866. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  87867. /*
  87868. ** PRAGMA [database.]auto_vacuum
  87869. ** PRAGMA [database.]auto_vacuum=N
  87870. **
  87871. ** Get or set the value of the database 'auto-vacuum' parameter.
  87872. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  87873. */
  87874. #ifndef SQLITE_OMIT_AUTOVACUUM
  87875. if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
  87876. Btree *pBt = pDb->pBt;
  87877. assert( pBt!=0 );
  87878. if( sqlite3ReadSchema(pParse) ){
  87879. goto pragma_out;
  87880. }
  87881. if( !zRight ){
  87882. int auto_vacuum;
  87883. if( ALWAYS(pBt) ){
  87884. auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
  87885. }else{
  87886. auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
  87887. }
  87888. returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
  87889. }else{
  87890. int eAuto = getAutoVacuum(zRight);
  87891. assert( eAuto>=0 && eAuto<=2 );
  87892. db->nextAutovac = (u8)eAuto;
  87893. if( ALWAYS(eAuto>=0) ){
  87894. /* Call SetAutoVacuum() to set initialize the internal auto and
  87895. ** incr-vacuum flags. This is required in case this connection
  87896. ** creates the database file. It is important that it is created
  87897. ** as an auto-vacuum capable db.
  87898. */
  87899. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  87900. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  87901. /* When setting the auto_vacuum mode to either "full" or
  87902. ** "incremental", write the value of meta[6] in the database
  87903. ** file. Before writing to meta[6], check that meta[3] indicates
  87904. ** that this really is an auto-vacuum capable database.
  87905. */
  87906. static const VdbeOpList setMeta6[] = {
  87907. { OP_Transaction, 0, 1, 0}, /* 0 */
  87908. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  87909. { OP_If, 1, 0, 0}, /* 2 */
  87910. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  87911. { OP_Integer, 0, 1, 0}, /* 4 */
  87912. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  87913. };
  87914. int iAddr;
  87915. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  87916. sqlite3VdbeChangeP1(v, iAddr, iDb);
  87917. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  87918. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  87919. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  87920. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  87921. sqlite3VdbeUsesBtree(v, iDb);
  87922. }
  87923. }
  87924. }
  87925. }else
  87926. #endif
  87927. /*
  87928. ** PRAGMA [database.]incremental_vacuum(N)
  87929. **
  87930. ** Do N steps of incremental vacuuming on a database.
  87931. */
  87932. #ifndef SQLITE_OMIT_AUTOVACUUM
  87933. if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
  87934. int iLimit, addr;
  87935. if( sqlite3ReadSchema(pParse) ){
  87936. goto pragma_out;
  87937. }
  87938. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  87939. iLimit = 0x7fffffff;
  87940. }
  87941. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87942. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  87943. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  87944. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  87945. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  87946. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  87947. sqlite3VdbeJumpHere(v, addr);
  87948. }else
  87949. #endif
  87950. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87951. /*
  87952. ** PRAGMA [database.]cache_size
  87953. ** PRAGMA [database.]cache_size=N
  87954. **
  87955. ** The first form reports the current local setting for the
  87956. ** page cache size. The second form sets the local
  87957. ** page cache size value. If N is positive then that is the
  87958. ** number of pages in the cache. If N is negative, then the
  87959. ** number of pages is adjusted so that the cache uses -N kibibytes
  87960. ** of memory.
  87961. */
  87962. if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
  87963. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  87964. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87965. if( !zRight ){
  87966. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  87967. }else{
  87968. int size = sqlite3Atoi(zRight);
  87969. pDb->pSchema->cache_size = size;
  87970. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  87971. }
  87972. }else
  87973. /*
  87974. ** PRAGMA [database.]mmap_size(N)
  87975. **
  87976. ** Used to set mapping size limit. The mapping size limit is
  87977. ** used to limit the aggregate size of all memory mapped regions of the
  87978. ** database file. If this parameter is set to zero, then memory mapping
  87979. ** is not used at all. If N is negative, then the default memory map
  87980. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  87981. ** The parameter N is measured in bytes.
  87982. **
  87983. ** This value is advisory. The underlying VFS is free to memory map
  87984. ** as little or as much as it wants. Except, if N is set to 0 then the
  87985. ** upper layers will never invoke the xFetch interfaces to the VFS.
  87986. */
  87987. if( sqlite3StrICmp(zLeft,"mmap_size")==0 ){
  87988. sqlite3_int64 sz;
  87989. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87990. if( zRight ){
  87991. int ii;
  87992. sqlite3Atoi64(zRight, &sz, 1000, SQLITE_UTF8);
  87993. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  87994. if( pId2->n==0 ) db->szMmap = sz;
  87995. for(ii=db->nDb-1; ii>=0; ii--){
  87996. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  87997. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  87998. }
  87999. }
  88000. }
  88001. sz = -1;
  88002. if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
  88003. #if SQLITE_MAX_MMAP_SIZE==0
  88004. sz = 0;
  88005. #endif
  88006. returnSingleInt(pParse, "mmap_size", sz);
  88007. }
  88008. }else
  88009. /*
  88010. ** PRAGMA temp_store
  88011. ** PRAGMA temp_store = "default"|"memory"|"file"
  88012. **
  88013. ** Return or set the local value of the temp_store flag. Changing
  88014. ** the local value does not make changes to the disk file and the default
  88015. ** value will be restored the next time the database is opened.
  88016. **
  88017. ** Note that it is possible for the library compile-time options to
  88018. ** override this setting
  88019. */
  88020. if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
  88021. if( !zRight ){
  88022. returnSingleInt(pParse, "temp_store", db->temp_store);
  88023. }else{
  88024. changeTempStorage(pParse, zRight);
  88025. }
  88026. }else
  88027. /*
  88028. ** PRAGMA temp_store_directory
  88029. ** PRAGMA temp_store_directory = ""|"directory_name"
  88030. **
  88031. ** Return or set the local value of the temp_store_directory flag. Changing
  88032. ** the value sets a specific directory to be used for temporary files.
  88033. ** Setting to a null string reverts to the default temporary directory search.
  88034. ** If temporary directory is changed, then invalidateTempStorage.
  88035. **
  88036. */
  88037. if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
  88038. if( !zRight ){
  88039. if( sqlite3_temp_directory ){
  88040. sqlite3VdbeSetNumCols(v, 1);
  88041. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  88042. "temp_store_directory", SQLITE_STATIC);
  88043. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  88044. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  88045. }
  88046. }else{
  88047. #ifndef SQLITE_OMIT_WSD
  88048. if( zRight[0] ){
  88049. int res;
  88050. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  88051. if( rc!=SQLITE_OK || res==0 ){
  88052. sqlite3ErrorMsg(pParse, "not a writable directory");
  88053. goto pragma_out;
  88054. }
  88055. }
  88056. if( SQLITE_TEMP_STORE==0
  88057. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  88058. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  88059. ){
  88060. invalidateTempStorage(pParse);
  88061. }
  88062. sqlite3_free(sqlite3_temp_directory);
  88063. if( zRight[0] ){
  88064. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  88065. }else{
  88066. sqlite3_temp_directory = 0;
  88067. }
  88068. #endif /* SQLITE_OMIT_WSD */
  88069. }
  88070. }else
  88071. #if SQLITE_OS_WIN
  88072. /*
  88073. ** PRAGMA data_store_directory
  88074. ** PRAGMA data_store_directory = ""|"directory_name"
  88075. **
  88076. ** Return or set the local value of the data_store_directory flag. Changing
  88077. ** the value sets a specific directory to be used for database files that
  88078. ** were specified with a relative pathname. Setting to a null string reverts
  88079. ** to the default database directory, which for database files specified with
  88080. ** a relative path will probably be based on the current directory for the
  88081. ** process. Database file specified with an absolute path are not impacted
  88082. ** by this setting, regardless of its value.
  88083. **
  88084. */
  88085. if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
  88086. if( !zRight ){
  88087. if( sqlite3_data_directory ){
  88088. sqlite3VdbeSetNumCols(v, 1);
  88089. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  88090. "data_store_directory", SQLITE_STATIC);
  88091. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  88092. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  88093. }
  88094. }else{
  88095. #ifndef SQLITE_OMIT_WSD
  88096. if( zRight[0] ){
  88097. int res;
  88098. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  88099. if( rc!=SQLITE_OK || res==0 ){
  88100. sqlite3ErrorMsg(pParse, "not a writable directory");
  88101. goto pragma_out;
  88102. }
  88103. }
  88104. sqlite3_free(sqlite3_data_directory);
  88105. if( zRight[0] ){
  88106. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  88107. }else{
  88108. sqlite3_data_directory = 0;
  88109. }
  88110. #endif /* SQLITE_OMIT_WSD */
  88111. }
  88112. }else
  88113. #endif
  88114. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  88115. # if defined(__APPLE__)
  88116. # define SQLITE_ENABLE_LOCKING_STYLE 1
  88117. # else
  88118. # define SQLITE_ENABLE_LOCKING_STYLE 0
  88119. # endif
  88120. #endif
  88121. #if SQLITE_ENABLE_LOCKING_STYLE
  88122. /*
  88123. ** PRAGMA [database.]lock_proxy_file
  88124. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  88125. **
  88126. ** Return or set the value of the lock_proxy_file flag. Changing
  88127. ** the value sets a specific file to be used for database access locks.
  88128. **
  88129. */
  88130. if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
  88131. if( !zRight ){
  88132. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  88133. char *proxy_file_path = NULL;
  88134. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  88135. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  88136. &proxy_file_path);
  88137. if( proxy_file_path ){
  88138. sqlite3VdbeSetNumCols(v, 1);
  88139. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  88140. "lock_proxy_file", SQLITE_STATIC);
  88141. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  88142. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  88143. }
  88144. }else{
  88145. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  88146. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  88147. int res;
  88148. if( zRight[0] ){
  88149. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  88150. zRight);
  88151. } else {
  88152. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  88153. NULL);
  88154. }
  88155. if( res!=SQLITE_OK ){
  88156. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  88157. goto pragma_out;
  88158. }
  88159. }
  88160. }else
  88161. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  88162. /*
  88163. ** PRAGMA [database.]synchronous
  88164. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  88165. **
  88166. ** Return or set the local value of the synchronous flag. Changing
  88167. ** the local value does not make changes to the disk file and the
  88168. ** default value will be restored the next time the database is
  88169. ** opened.
  88170. */
  88171. if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
  88172. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88173. if( !zRight ){
  88174. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  88175. }else{
  88176. if( !db->autoCommit ){
  88177. sqlite3ErrorMsg(pParse,
  88178. "Safety level may not be changed inside a transaction");
  88179. }else{
  88180. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  88181. }
  88182. }
  88183. }else
  88184. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  88185. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  88186. if( flagPragma(pParse, zLeft, zRight) ){
  88187. /* The flagPragma() subroutine also generates any necessary code
  88188. ** there is nothing more to do here */
  88189. }else
  88190. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  88191. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  88192. /*
  88193. ** PRAGMA table_info(<table>)
  88194. **
  88195. ** Return a single row for each column of the named table. The columns of
  88196. ** the returned data set are:
  88197. **
  88198. ** cid: Column id (numbered from left to right, starting at 0)
  88199. ** name: Column name
  88200. ** type: Column declaration type.
  88201. ** notnull: True if 'NOT NULL' is part of column declaration
  88202. ** dflt_value: The default value for the column, if any.
  88203. */
  88204. if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
  88205. Table *pTab;
  88206. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88207. pTab = sqlite3FindTable(db, zRight, zDb);
  88208. if( pTab ){
  88209. int i, k;
  88210. int nHidden = 0;
  88211. Column *pCol;
  88212. Index *pPk;
  88213. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  88214. sqlite3VdbeSetNumCols(v, 6);
  88215. pParse->nMem = 6;
  88216. sqlite3CodeVerifySchema(pParse, iDb);
  88217. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  88218. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  88219. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  88220. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  88221. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  88222. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  88223. sqlite3ViewGetColumnNames(pParse, pTab);
  88224. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  88225. if( IsHiddenColumn(pCol) ){
  88226. nHidden++;
  88227. continue;
  88228. }
  88229. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  88230. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  88231. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  88232. pCol->zType ? pCol->zType : "", 0);
  88233. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  88234. if( pCol->zDflt ){
  88235. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  88236. }else{
  88237. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  88238. }
  88239. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  88240. k = 0;
  88241. }else if( pPk==0 ){
  88242. k = 1;
  88243. }else{
  88244. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  88245. }
  88246. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  88247. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  88248. }
  88249. }
  88250. }else
  88251. if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
  88252. Index *pIdx;
  88253. Table *pTab;
  88254. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88255. pIdx = sqlite3FindIndex(db, zRight, zDb);
  88256. if( pIdx ){
  88257. int i;
  88258. pTab = pIdx->pTable;
  88259. sqlite3VdbeSetNumCols(v, 3);
  88260. pParse->nMem = 3;
  88261. sqlite3CodeVerifySchema(pParse, iDb);
  88262. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  88263. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  88264. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  88265. for(i=0; i<pIdx->nColumn; i++){
  88266. int cnum = pIdx->aiColumn[i];
  88267. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  88268. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  88269. assert( pTab->nCol>cnum );
  88270. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  88271. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  88272. }
  88273. }
  88274. }else
  88275. if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
  88276. Index *pIdx;
  88277. Table *pTab;
  88278. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88279. pTab = sqlite3FindTable(db, zRight, zDb);
  88280. if( pTab ){
  88281. v = sqlite3GetVdbe(pParse);
  88282. pIdx = pTab->pIndex;
  88283. if( pIdx ){
  88284. int i = 0;
  88285. sqlite3VdbeSetNumCols(v, 3);
  88286. pParse->nMem = 3;
  88287. sqlite3CodeVerifySchema(pParse, iDb);
  88288. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  88289. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  88290. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  88291. while(pIdx){
  88292. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  88293. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  88294. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  88295. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  88296. ++i;
  88297. pIdx = pIdx->pNext;
  88298. }
  88299. }
  88300. }
  88301. }else
  88302. if( sqlite3StrICmp(zLeft, "database_list")==0 ){
  88303. int i;
  88304. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88305. sqlite3VdbeSetNumCols(v, 3);
  88306. pParse->nMem = 3;
  88307. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  88308. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  88309. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  88310. for(i=0; i<db->nDb; i++){
  88311. if( db->aDb[i].pBt==0 ) continue;
  88312. assert( db->aDb[i].zName!=0 );
  88313. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  88314. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  88315. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  88316. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  88317. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  88318. }
  88319. }else
  88320. if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
  88321. int i = 0;
  88322. HashElem *p;
  88323. sqlite3VdbeSetNumCols(v, 2);
  88324. pParse->nMem = 2;
  88325. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  88326. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  88327. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  88328. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  88329. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  88330. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  88331. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  88332. }
  88333. }else
  88334. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  88335. #ifndef SQLITE_OMIT_FOREIGN_KEY
  88336. if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
  88337. FKey *pFK;
  88338. Table *pTab;
  88339. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88340. pTab = sqlite3FindTable(db, zRight, zDb);
  88341. if( pTab ){
  88342. v = sqlite3GetVdbe(pParse);
  88343. pFK = pTab->pFKey;
  88344. if( pFK ){
  88345. int i = 0;
  88346. sqlite3VdbeSetNumCols(v, 8);
  88347. pParse->nMem = 8;
  88348. sqlite3CodeVerifySchema(pParse, iDb);
  88349. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  88350. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  88351. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  88352. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  88353. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  88354. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  88355. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  88356. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  88357. while(pFK){
  88358. int j;
  88359. for(j=0; j<pFK->nCol; j++){
  88360. char *zCol = pFK->aCol[j].zCol;
  88361. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  88362. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  88363. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  88364. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  88365. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  88366. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  88367. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  88368. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  88369. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  88370. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  88371. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  88372. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  88373. }
  88374. ++i;
  88375. pFK = pFK->pNextFrom;
  88376. }
  88377. }
  88378. }
  88379. }else
  88380. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  88381. #ifndef SQLITE_OMIT_FOREIGN_KEY
  88382. #ifndef SQLITE_OMIT_TRIGGER
  88383. if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
  88384. FKey *pFK; /* A foreign key constraint */
  88385. Table *pTab; /* Child table contain "REFERENCES" keyword */
  88386. Table *pParent; /* Parent table that child points to */
  88387. Index *pIdx; /* Index in the parent table */
  88388. int i; /* Loop counter: Foreign key number for pTab */
  88389. int j; /* Loop counter: Field of the foreign key */
  88390. HashElem *k; /* Loop counter: Next table in schema */
  88391. int x; /* result variable */
  88392. int regResult; /* 3 registers to hold a result row */
  88393. int regKey; /* Register to hold key for checking the FK */
  88394. int regRow; /* Registers to hold a row from pTab */
  88395. int addrTop; /* Top of a loop checking foreign keys */
  88396. int addrOk; /* Jump here if the key is OK */
  88397. int *aiCols; /* child to parent column mapping */
  88398. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88399. regResult = pParse->nMem+1;
  88400. pParse->nMem += 4;
  88401. regKey = ++pParse->nMem;
  88402. regRow = ++pParse->nMem;
  88403. v = sqlite3GetVdbe(pParse);
  88404. sqlite3VdbeSetNumCols(v, 4);
  88405. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  88406. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  88407. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  88408. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  88409. sqlite3CodeVerifySchema(pParse, iDb);
  88410. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  88411. while( k ){
  88412. if( zRight ){
  88413. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  88414. k = 0;
  88415. }else{
  88416. pTab = (Table*)sqliteHashData(k);
  88417. k = sqliteHashNext(k);
  88418. }
  88419. if( pTab==0 || pTab->pFKey==0 ) continue;
  88420. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  88421. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  88422. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  88423. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  88424. P4_TRANSIENT);
  88425. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  88426. pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
  88427. if( pParent==0 ) break;
  88428. pIdx = 0;
  88429. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  88430. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  88431. if( x==0 ){
  88432. if( pIdx==0 ){
  88433. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  88434. }else{
  88435. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  88436. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  88437. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  88438. }
  88439. }else{
  88440. k = 0;
  88441. break;
  88442. }
  88443. }
  88444. if( pFK ) break;
  88445. if( pParse->nTab<i ) pParse->nTab = i;
  88446. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  88447. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  88448. pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
  88449. assert( pParent!=0 );
  88450. pIdx = 0;
  88451. aiCols = 0;
  88452. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  88453. assert( x==0 );
  88454. addrOk = sqlite3VdbeMakeLabel(v);
  88455. if( pIdx==0 ){
  88456. int iKey = pFK->aCol[0].iFrom;
  88457. assert( iKey>=0 && iKey<pTab->nCol );
  88458. if( iKey!=pTab->iPKey ){
  88459. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  88460. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  88461. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  88462. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  88463. sqlite3VdbeCurrentAddr(v)+3);
  88464. }else{
  88465. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  88466. }
  88467. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  88468. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  88469. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  88470. }else{
  88471. for(j=0; j<pFK->nCol; j++){
  88472. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  88473. aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
  88474. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  88475. }
  88476. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  88477. sqlite3VdbeChangeP4(v, -1,
  88478. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  88479. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  88480. }
  88481. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  88482. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  88483. pFK->zTo, P4_TRANSIENT);
  88484. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  88485. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  88486. sqlite3VdbeResolveLabel(v, addrOk);
  88487. sqlite3DbFree(db, aiCols);
  88488. }
  88489. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  88490. sqlite3VdbeJumpHere(v, addrTop);
  88491. }
  88492. }else
  88493. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  88494. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  88495. #ifndef NDEBUG
  88496. if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
  88497. if( zRight ){
  88498. if( sqlite3GetBoolean(zRight, 0) ){
  88499. sqlite3ParserTrace(stderr, "parser: ");
  88500. }else{
  88501. sqlite3ParserTrace(0, 0);
  88502. }
  88503. }
  88504. }else
  88505. #endif
  88506. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  88507. ** used will be case sensitive or not depending on the RHS.
  88508. */
  88509. if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
  88510. if( zRight ){
  88511. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  88512. }
  88513. }else
  88514. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  88515. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  88516. #endif
  88517. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  88518. /* Pragma "quick_check" is an experimental reduced version of
  88519. ** integrity_check designed to detect most database corruption
  88520. ** without most of the overhead of a full integrity-check.
  88521. */
  88522. if( sqlite3StrICmp(zLeft, "integrity_check")==0
  88523. || sqlite3StrICmp(zLeft, "quick_check")==0
  88524. ){
  88525. int i, j, addr, mxErr;
  88526. /* Code that appears at the end of the integrity check. If no error
  88527. ** messages have been generated, output OK. Otherwise output the
  88528. ** error message
  88529. */
  88530. static const VdbeOpList endCode[] = {
  88531. { OP_AddImm, 1, 0, 0}, /* 0 */
  88532. { OP_IfNeg, 1, 0, 0}, /* 1 */
  88533. { OP_String8, 0, 3, 0}, /* 2 */
  88534. { OP_ResultRow, 3, 1, 0},
  88535. };
  88536. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  88537. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  88538. ** then iDb is set to the index of the database identified by <db>.
  88539. ** In this case, the integrity of database iDb only is verified by
  88540. ** the VDBE created below.
  88541. **
  88542. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  88543. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  88544. ** to -1 here, to indicate that the VDBE should verify the integrity
  88545. ** of all attached databases. */
  88546. assert( iDb>=0 );
  88547. assert( iDb==0 || pId2->z );
  88548. if( pId2->z==0 ) iDb = -1;
  88549. /* Initialize the VDBE program */
  88550. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88551. pParse->nMem = 6;
  88552. sqlite3VdbeSetNumCols(v, 1);
  88553. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  88554. /* Set the maximum error count */
  88555. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  88556. if( zRight ){
  88557. sqlite3GetInt32(zRight, &mxErr);
  88558. if( mxErr<=0 ){
  88559. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  88560. }
  88561. }
  88562. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  88563. /* Do an integrity check on each database file */
  88564. for(i=0; i<db->nDb; i++){
  88565. HashElem *x;
  88566. Hash *pTbls;
  88567. int cnt = 0;
  88568. if( OMIT_TEMPDB && i==1 ) continue;
  88569. if( iDb>=0 && i!=iDb ) continue;
  88570. sqlite3CodeVerifySchema(pParse, i);
  88571. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  88572. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  88573. sqlite3VdbeJumpHere(v, addr);
  88574. /* Do an integrity check of the B-Tree
  88575. **
  88576. ** Begin by filling registers 2, 3, ... with the root pages numbers
  88577. ** for all tables and indices in the database.
  88578. */
  88579. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  88580. pTbls = &db->aDb[i].pSchema->tblHash;
  88581. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  88582. Table *pTab = sqliteHashData(x);
  88583. Index *pIdx;
  88584. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  88585. cnt++;
  88586. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88587. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  88588. cnt++;
  88589. }
  88590. }
  88591. /* Make sure sufficient number of registers have been allocated */
  88592. if( pParse->nMem < cnt+4 ){
  88593. pParse->nMem = cnt+4;
  88594. }
  88595. /* Do the b-tree integrity checks */
  88596. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  88597. sqlite3VdbeChangeP5(v, (u8)i);
  88598. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  88599. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  88600. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  88601. P4_DYNAMIC);
  88602. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  88603. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  88604. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  88605. sqlite3VdbeJumpHere(v, addr);
  88606. /* Make sure all the indices are constructed correctly.
  88607. */
  88608. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  88609. Table *pTab = sqliteHashData(x);
  88610. Index *pIdx;
  88611. int loopTop;
  88612. if( pTab->pIndex==0 ) continue;
  88613. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  88614. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  88615. sqlite3VdbeJumpHere(v, addr);
  88616. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  88617. sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
  88618. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  88619. sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
  88620. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  88621. int jmp2;
  88622. int r1;
  88623. static const VdbeOpList idxErr[] = {
  88624. { OP_AddImm, 1, -1, 0},
  88625. { OP_String8, 0, 3, 0}, /* 1 */
  88626. { OP_Rowid, 1, 4, 0},
  88627. { OP_String8, 0, 5, 0}, /* 3 */
  88628. { OP_String8, 0, 6, 0}, /* 4 */
  88629. { OP_Concat, 4, 3, 3},
  88630. { OP_Concat, 5, 3, 3},
  88631. { OP_Concat, 6, 3, 3},
  88632. { OP_ResultRow, 3, 1, 0},
  88633. { OP_IfPos, 1, 0, 0}, /* 9 */
  88634. { OP_Halt, 0, 0, 0},
  88635. };
  88636. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
  88637. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  88638. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  88639. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  88640. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  88641. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  88642. sqlite3VdbeJumpHere(v, addr+9);
  88643. sqlite3VdbeJumpHere(v, jmp2);
  88644. }
  88645. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  88646. sqlite3VdbeJumpHere(v, loopTop);
  88647. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  88648. static const VdbeOpList cntIdx[] = {
  88649. { OP_Integer, 0, 3, 0},
  88650. { OP_Rewind, 0, 0, 0}, /* 1 */
  88651. { OP_AddImm, 3, 1, 0},
  88652. { OP_Next, 0, 0, 0}, /* 3 */
  88653. { OP_Eq, 2, 0, 3}, /* 4 */
  88654. { OP_AddImm, 1, -1, 0},
  88655. { OP_String8, 0, 2, 0}, /* 6 */
  88656. { OP_String8, 0, 3, 0}, /* 7 */
  88657. { OP_Concat, 3, 2, 2},
  88658. { OP_ResultRow, 2, 1, 0},
  88659. };
  88660. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
  88661. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  88662. sqlite3VdbeJumpHere(v, addr);
  88663. addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  88664. sqlite3VdbeChangeP1(v, addr+1, j+2);
  88665. sqlite3VdbeChangeP2(v, addr+1, addr+4);
  88666. sqlite3VdbeChangeP1(v, addr+3, j+2);
  88667. sqlite3VdbeChangeP2(v, addr+3, addr+2);
  88668. sqlite3VdbeJumpHere(v, addr+4);
  88669. sqlite3VdbeChangeP4(v, addr+6,
  88670. "wrong # of entries in index ", P4_STATIC);
  88671. sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
  88672. }
  88673. }
  88674. }
  88675. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  88676. sqlite3VdbeChangeP2(v, addr, -mxErr);
  88677. sqlite3VdbeJumpHere(v, addr+1);
  88678. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  88679. }else
  88680. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  88681. #ifndef SQLITE_OMIT_UTF16
  88682. /*
  88683. ** PRAGMA encoding
  88684. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  88685. **
  88686. ** In its first form, this pragma returns the encoding of the main
  88687. ** database. If the database is not initialized, it is initialized now.
  88688. **
  88689. ** The second form of this pragma is a no-op if the main database file
  88690. ** has not already been initialized. In this case it sets the default
  88691. ** encoding that will be used for the main database file if a new file
  88692. ** is created. If an existing main database file is opened, then the
  88693. ** default text encoding for the existing database is used.
  88694. **
  88695. ** In all cases new databases created using the ATTACH command are
  88696. ** created to use the same default text encoding as the main database. If
  88697. ** the main database has not been initialized and/or created when ATTACH
  88698. ** is executed, this is done before the ATTACH operation.
  88699. **
  88700. ** In the second form this pragma sets the text encoding to be used in
  88701. ** new database files created using this database handle. It is only
  88702. ** useful if invoked immediately after the main database i
  88703. */
  88704. if( sqlite3StrICmp(zLeft, "encoding")==0 ){
  88705. static const struct EncName {
  88706. char *zName;
  88707. u8 enc;
  88708. } encnames[] = {
  88709. { "UTF8", SQLITE_UTF8 },
  88710. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  88711. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  88712. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  88713. { "UTF16le", SQLITE_UTF16LE },
  88714. { "UTF16be", SQLITE_UTF16BE },
  88715. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  88716. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  88717. { 0, 0 }
  88718. };
  88719. const struct EncName *pEnc;
  88720. if( !zRight ){ /* "PRAGMA encoding" */
  88721. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88722. sqlite3VdbeSetNumCols(v, 1);
  88723. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  88724. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  88725. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  88726. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  88727. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  88728. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  88729. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  88730. }else{ /* "PRAGMA encoding = XXX" */
  88731. /* Only change the value of sqlite.enc if the database handle is not
  88732. ** initialized. If the main database exists, the new sqlite.enc value
  88733. ** will be overwritten when the schema is next loaded. If it does not
  88734. ** already exists, it will be created to use the new encoding value.
  88735. */
  88736. if(
  88737. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  88738. DbHasProperty(db, 0, DB_Empty)
  88739. ){
  88740. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  88741. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  88742. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  88743. break;
  88744. }
  88745. }
  88746. if( !pEnc->zName ){
  88747. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  88748. }
  88749. }
  88750. }
  88751. }else
  88752. #endif /* SQLITE_OMIT_UTF16 */
  88753. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  88754. /*
  88755. ** PRAGMA [database.]schema_version
  88756. ** PRAGMA [database.]schema_version = <integer>
  88757. **
  88758. ** PRAGMA [database.]user_version
  88759. ** PRAGMA [database.]user_version = <integer>
  88760. **
  88761. ** PRAGMA [database.]freelist_count = <integer>
  88762. **
  88763. ** PRAGMA [database.]application_id
  88764. ** PRAGMA [database.]application_id = <integer>
  88765. **
  88766. ** The pragma's schema_version and user_version are used to set or get
  88767. ** the value of the schema-version and user-version, respectively. Both
  88768. ** the schema-version and the user-version are 32-bit signed integers
  88769. ** stored in the database header.
  88770. **
  88771. ** The schema-cookie is usually only manipulated internally by SQLite. It
  88772. ** is incremented by SQLite whenever the database schema is modified (by
  88773. ** creating or dropping a table or index). The schema version is used by
  88774. ** SQLite each time a query is executed to ensure that the internal cache
  88775. ** of the schema used when compiling the SQL query matches the schema of
  88776. ** the database against which the compiled query is actually executed.
  88777. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  88778. ** the schema-version is potentially dangerous and may lead to program
  88779. ** crashes or database corruption. Use with caution!
  88780. **
  88781. ** The user-version is not used internally by SQLite. It may be used by
  88782. ** applications for any purpose.
  88783. */
  88784. if( sqlite3StrICmp(zLeft, "schema_version")==0
  88785. || sqlite3StrICmp(zLeft, "user_version")==0
  88786. || sqlite3StrICmp(zLeft, "freelist_count")==0
  88787. || sqlite3StrICmp(zLeft, "application_id")==0
  88788. ){
  88789. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  88790. sqlite3VdbeUsesBtree(v, iDb);
  88791. switch( zLeft[0] ){
  88792. case 'a': case 'A':
  88793. iCookie = BTREE_APPLICATION_ID;
  88794. break;
  88795. case 'f': case 'F':
  88796. iCookie = BTREE_FREE_PAGE_COUNT;
  88797. break;
  88798. case 's': case 'S':
  88799. iCookie = BTREE_SCHEMA_VERSION;
  88800. break;
  88801. default:
  88802. iCookie = BTREE_USER_VERSION;
  88803. break;
  88804. }
  88805. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  88806. /* Write the specified cookie value */
  88807. static const VdbeOpList setCookie[] = {
  88808. { OP_Transaction, 0, 1, 0}, /* 0 */
  88809. { OP_Integer, 0, 1, 0}, /* 1 */
  88810. { OP_SetCookie, 0, 0, 1}, /* 2 */
  88811. };
  88812. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  88813. sqlite3VdbeChangeP1(v, addr, iDb);
  88814. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  88815. sqlite3VdbeChangeP1(v, addr+2, iDb);
  88816. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  88817. }else{
  88818. /* Read the specified cookie value */
  88819. static const VdbeOpList readCookie[] = {
  88820. { OP_Transaction, 0, 0, 0}, /* 0 */
  88821. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  88822. { OP_ResultRow, 1, 1, 0}
  88823. };
  88824. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  88825. sqlite3VdbeChangeP1(v, addr, iDb);
  88826. sqlite3VdbeChangeP1(v, addr+1, iDb);
  88827. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  88828. sqlite3VdbeSetNumCols(v, 1);
  88829. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  88830. }
  88831. }else
  88832. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  88833. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  88834. /*
  88835. ** PRAGMA compile_options
  88836. **
  88837. ** Return the names of all compile-time options used in this build,
  88838. ** one option per row.
  88839. */
  88840. if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
  88841. int i = 0;
  88842. const char *zOpt;
  88843. sqlite3VdbeSetNumCols(v, 1);
  88844. pParse->nMem = 1;
  88845. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  88846. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  88847. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  88848. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  88849. }
  88850. }else
  88851. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  88852. #ifndef SQLITE_OMIT_WAL
  88853. /*
  88854. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  88855. **
  88856. ** Checkpoint the database.
  88857. */
  88858. if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
  88859. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  88860. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  88861. if( zRight ){
  88862. if( sqlite3StrICmp(zRight, "full")==0 ){
  88863. eMode = SQLITE_CHECKPOINT_FULL;
  88864. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  88865. eMode = SQLITE_CHECKPOINT_RESTART;
  88866. }
  88867. }
  88868. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  88869. sqlite3VdbeSetNumCols(v, 3);
  88870. pParse->nMem = 3;
  88871. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  88872. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  88873. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  88874. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  88875. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  88876. }else
  88877. /*
  88878. ** PRAGMA wal_autocheckpoint
  88879. ** PRAGMA wal_autocheckpoint = N
  88880. **
  88881. ** Configure a database connection to automatically checkpoint a database
  88882. ** after accumulating N frames in the log. Or query for the current value
  88883. ** of N.
  88884. */
  88885. if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
  88886. if( zRight ){
  88887. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  88888. }
  88889. returnSingleInt(pParse, "wal_autocheckpoint",
  88890. db->xWalCallback==sqlite3WalDefaultHook ?
  88891. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  88892. }else
  88893. #endif
  88894. /*
  88895. ** PRAGMA shrink_memory
  88896. **
  88897. ** This pragma attempts to free as much memory as possible from the
  88898. ** current database connection.
  88899. */
  88900. if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
  88901. sqlite3_db_release_memory(db);
  88902. }else
  88903. /*
  88904. ** PRAGMA busy_timeout
  88905. ** PRAGMA busy_timeout = N
  88906. **
  88907. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  88908. ** if one is set. If no busy handler or a different busy handler is set
  88909. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  88910. ** disables the timeout.
  88911. */
  88912. if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
  88913. if( zRight ){
  88914. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  88915. }
  88916. returnSingleInt(pParse, "timeout", db->busyTimeout);
  88917. }else
  88918. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  88919. /*
  88920. ** Report the current state of file logs for all databases
  88921. */
  88922. if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  88923. static const char *const azLockName[] = {
  88924. "unlocked", "shared", "reserved", "pending", "exclusive"
  88925. };
  88926. int i;
  88927. sqlite3VdbeSetNumCols(v, 2);
  88928. pParse->nMem = 2;
  88929. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  88930. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  88931. for(i=0; i<db->nDb; i++){
  88932. Btree *pBt;
  88933. const char *zState = "unknown";
  88934. int j;
  88935. if( db->aDb[i].zName==0 ) continue;
  88936. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  88937. pBt = db->aDb[i].pBt;
  88938. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  88939. zState = "closed";
  88940. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  88941. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  88942. zState = azLockName[j];
  88943. }
  88944. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  88945. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  88946. }
  88947. }else
  88948. #endif
  88949. #ifdef SQLITE_HAS_CODEC
  88950. if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
  88951. sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  88952. }else
  88953. if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
  88954. sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  88955. }else
  88956. if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
  88957. sqlite3StrICmp(zLeft, "hexrekey")==0) ){
  88958. int i, h1, h2;
  88959. char zKey[40];
  88960. for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
  88961. h1 += 9*(1&(h1>>6));
  88962. h2 += 9*(1&(h2>>6));
  88963. zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
  88964. }
  88965. if( (zLeft[3] & 0xf)==0xb ){
  88966. sqlite3_key(db, zKey, i/2);
  88967. }else{
  88968. sqlite3_rekey(db, zKey, i/2);
  88969. }
  88970. }else
  88971. #endif
  88972. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  88973. if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
  88974. #ifdef SQLITE_HAS_CODEC
  88975. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  88976. sqlite3_activate_see(&zRight[4]);
  88977. }
  88978. #endif
  88979. #ifdef SQLITE_ENABLE_CEROD
  88980. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  88981. sqlite3_activate_cerod(&zRight[6]);
  88982. }
  88983. #endif
  88984. }else
  88985. #endif
  88986. {/* Empty ELSE clause */}
  88987. /*
  88988. ** Reset the safety level, in case the fullfsync flag or synchronous
  88989. ** setting changed.
  88990. */
  88991. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  88992. if( db->autoCommit ){
  88993. sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
  88994. (db->flags&SQLITE_FullFSync)!=0,
  88995. (db->flags&SQLITE_CkptFullFSync)!=0);
  88996. }
  88997. #endif
  88998. pragma_out:
  88999. sqlite3DbFree(db, zLeft);
  89000. sqlite3DbFree(db, zRight);
  89001. }
  89002. #endif /* SQLITE_OMIT_PRAGMA */
  89003. /************** End of pragma.c **********************************************/
  89004. /************** Begin file prepare.c *****************************************/
  89005. /*
  89006. ** 2005 May 25
  89007. **
  89008. ** The author disclaims copyright to this source code. In place of
  89009. ** a legal notice, here is a blessing:
  89010. **
  89011. ** May you do good and not evil.
  89012. ** May you find forgiveness for yourself and forgive others.
  89013. ** May you share freely, never taking more than you give.
  89014. **
  89015. *************************************************************************
  89016. ** This file contains the implementation of the sqlite3_prepare()
  89017. ** interface, and routines that contribute to loading the database schema
  89018. ** from disk.
  89019. */
  89020. /*
  89021. ** Fill the InitData structure with an error message that indicates
  89022. ** that the database is corrupt.
  89023. */
  89024. static void corruptSchema(
  89025. InitData *pData, /* Initialization context */
  89026. const char *zObj, /* Object being parsed at the point of error */
  89027. const char *zExtra /* Error information */
  89028. ){
  89029. sqlite3 *db = pData->db;
  89030. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  89031. if( zObj==0 ) zObj = "?";
  89032. sqlite3SetString(pData->pzErrMsg, db,
  89033. "malformed database schema (%s)", zObj);
  89034. if( zExtra ){
  89035. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  89036. "%s - %s", *pData->pzErrMsg, zExtra);
  89037. }
  89038. }
  89039. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  89040. }
  89041. /*
  89042. ** This is the callback routine for the code that initializes the
  89043. ** database. See sqlite3Init() below for additional information.
  89044. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  89045. **
  89046. ** Each callback contains the following information:
  89047. **
  89048. ** argv[0] = name of thing being created
  89049. ** argv[1] = root page number for table or index. 0 for trigger or view.
  89050. ** argv[2] = SQL text for the CREATE statement.
  89051. **
  89052. */
  89053. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  89054. InitData *pData = (InitData*)pInit;
  89055. sqlite3 *db = pData->db;
  89056. int iDb = pData->iDb;
  89057. assert( argc==3 );
  89058. UNUSED_PARAMETER2(NotUsed, argc);
  89059. assert( sqlite3_mutex_held(db->mutex) );
  89060. DbClearProperty(db, iDb, DB_Empty);
  89061. if( db->mallocFailed ){
  89062. corruptSchema(pData, argv[0], 0);
  89063. return 1;
  89064. }
  89065. assert( iDb>=0 && iDb<db->nDb );
  89066. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  89067. if( argv[1]==0 ){
  89068. corruptSchema(pData, argv[0], 0);
  89069. }else if( argv[2] && argv[2][0] ){
  89070. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  89071. ** But because db->init.busy is set to 1, no VDBE code is generated
  89072. ** or executed. All the parser does is build the internal data
  89073. ** structures that describe the table, index, or view.
  89074. */
  89075. int rc;
  89076. sqlite3_stmt *pStmt;
  89077. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  89078. assert( db->init.busy );
  89079. db->init.iDb = iDb;
  89080. db->init.newTnum = sqlite3Atoi(argv[1]);
  89081. db->init.orphanTrigger = 0;
  89082. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  89083. rc = db->errCode;
  89084. assert( (rc&0xFF)==(rcp&0xFF) );
  89085. db->init.iDb = 0;
  89086. if( SQLITE_OK!=rc ){
  89087. if( db->init.orphanTrigger ){
  89088. assert( iDb==1 );
  89089. }else{
  89090. pData->rc = rc;
  89091. if( rc==SQLITE_NOMEM ){
  89092. db->mallocFailed = 1;
  89093. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  89094. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  89095. }
  89096. }
  89097. }
  89098. sqlite3_finalize(pStmt);
  89099. }else if( argv[0]==0 ){
  89100. corruptSchema(pData, 0, 0);
  89101. }else{
  89102. /* If the SQL column is blank it means this is an index that
  89103. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  89104. ** constraint for a CREATE TABLE. The index should have already
  89105. ** been created when we processed the CREATE TABLE. All we have
  89106. ** to do here is record the root page number for that index.
  89107. */
  89108. Index *pIndex;
  89109. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  89110. if( pIndex==0 ){
  89111. /* This can occur if there exists an index on a TEMP table which
  89112. ** has the same name as another index on a permanent index. Since
  89113. ** the permanent table is hidden by the TEMP table, we can also
  89114. ** safely ignore the index on the permanent table.
  89115. */
  89116. /* Do Nothing */;
  89117. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  89118. corruptSchema(pData, argv[0], "invalid rootpage");
  89119. }
  89120. }
  89121. return 0;
  89122. }
  89123. /*
  89124. ** Attempt to read the database schema and initialize internal
  89125. ** data structures for a single database file. The index of the
  89126. ** database file is given by iDb. iDb==0 is used for the main
  89127. ** database. iDb==1 should never be used. iDb>=2 is used for
  89128. ** auxiliary databases. Return one of the SQLITE_ error codes to
  89129. ** indicate success or failure.
  89130. */
  89131. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  89132. int rc;
  89133. int i;
  89134. #ifndef SQLITE_OMIT_DEPRECATED
  89135. int size;
  89136. #endif
  89137. Table *pTab;
  89138. Db *pDb;
  89139. char const *azArg[4];
  89140. int meta[5];
  89141. InitData initData;
  89142. char const *zMasterSchema;
  89143. char const *zMasterName;
  89144. int openedTransaction = 0;
  89145. /*
  89146. ** The master database table has a structure like this
  89147. */
  89148. static const char master_schema[] =
  89149. "CREATE TABLE sqlite_master(\n"
  89150. " type text,\n"
  89151. " name text,\n"
  89152. " tbl_name text,\n"
  89153. " rootpage integer,\n"
  89154. " sql text\n"
  89155. ")"
  89156. ;
  89157. #ifndef SQLITE_OMIT_TEMPDB
  89158. static const char temp_master_schema[] =
  89159. "CREATE TEMP TABLE sqlite_temp_master(\n"
  89160. " type text,\n"
  89161. " name text,\n"
  89162. " tbl_name text,\n"
  89163. " rootpage integer,\n"
  89164. " sql text\n"
  89165. ")"
  89166. ;
  89167. #else
  89168. #define temp_master_schema 0
  89169. #endif
  89170. assert( iDb>=0 && iDb<db->nDb );
  89171. assert( db->aDb[iDb].pSchema );
  89172. assert( sqlite3_mutex_held(db->mutex) );
  89173. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  89174. /* zMasterSchema and zInitScript are set to point at the master schema
  89175. ** and initialisation script appropriate for the database being
  89176. ** initialized. zMasterName is the name of the master table.
  89177. */
  89178. if( !OMIT_TEMPDB && iDb==1 ){
  89179. zMasterSchema = temp_master_schema;
  89180. }else{
  89181. zMasterSchema = master_schema;
  89182. }
  89183. zMasterName = SCHEMA_TABLE(iDb);
  89184. /* Construct the schema tables. */
  89185. azArg[0] = zMasterName;
  89186. azArg[1] = "1";
  89187. azArg[2] = zMasterSchema;
  89188. azArg[3] = 0;
  89189. initData.db = db;
  89190. initData.iDb = iDb;
  89191. initData.rc = SQLITE_OK;
  89192. initData.pzErrMsg = pzErrMsg;
  89193. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  89194. if( initData.rc ){
  89195. rc = initData.rc;
  89196. goto error_out;
  89197. }
  89198. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  89199. if( ALWAYS(pTab) ){
  89200. pTab->tabFlags |= TF_Readonly;
  89201. }
  89202. /* Create a cursor to hold the database open
  89203. */
  89204. pDb = &db->aDb[iDb];
  89205. if( pDb->pBt==0 ){
  89206. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  89207. DbSetProperty(db, 1, DB_SchemaLoaded);
  89208. }
  89209. return SQLITE_OK;
  89210. }
  89211. /* If there is not already a read-only (or read-write) transaction opened
  89212. ** on the b-tree database, open one now. If a transaction is opened, it
  89213. ** will be closed before this function returns. */
  89214. sqlite3BtreeEnter(pDb->pBt);
  89215. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  89216. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  89217. if( rc!=SQLITE_OK ){
  89218. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  89219. goto initone_error_out;
  89220. }
  89221. openedTransaction = 1;
  89222. }
  89223. /* Get the database meta information.
  89224. **
  89225. ** Meta values are as follows:
  89226. ** meta[0] Schema cookie. Changes with each schema change.
  89227. ** meta[1] File format of schema layer.
  89228. ** meta[2] Size of the page cache.
  89229. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  89230. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  89231. ** meta[5] User version
  89232. ** meta[6] Incremental vacuum mode
  89233. ** meta[7] unused
  89234. ** meta[8] unused
  89235. ** meta[9] unused
  89236. **
  89237. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  89238. ** the possible values of meta[4].
  89239. */
  89240. for(i=0; i<ArraySize(meta); i++){
  89241. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  89242. }
  89243. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  89244. /* If opening a non-empty database, check the text encoding. For the
  89245. ** main database, set sqlite3.enc to the encoding of the main database.
  89246. ** For an attached db, it is an error if the encoding is not the same
  89247. ** as sqlite3.enc.
  89248. */
  89249. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  89250. if( iDb==0 ){
  89251. #ifndef SQLITE_OMIT_UTF16
  89252. u8 encoding;
  89253. /* If opening the main database, set ENC(db). */
  89254. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  89255. if( encoding==0 ) encoding = SQLITE_UTF8;
  89256. ENC(db) = encoding;
  89257. #else
  89258. ENC(db) = SQLITE_UTF8;
  89259. #endif
  89260. }else{
  89261. /* If opening an attached database, the encoding much match ENC(db) */
  89262. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  89263. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  89264. " text encoding as main database");
  89265. rc = SQLITE_ERROR;
  89266. goto initone_error_out;
  89267. }
  89268. }
  89269. }else{
  89270. DbSetProperty(db, iDb, DB_Empty);
  89271. }
  89272. pDb->pSchema->enc = ENC(db);
  89273. if( pDb->pSchema->cache_size==0 ){
  89274. #ifndef SQLITE_OMIT_DEPRECATED
  89275. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  89276. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  89277. pDb->pSchema->cache_size = size;
  89278. #else
  89279. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  89280. #endif
  89281. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  89282. }
  89283. /*
  89284. ** file_format==1 Version 3.0.0.
  89285. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  89286. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  89287. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  89288. */
  89289. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  89290. if( pDb->pSchema->file_format==0 ){
  89291. pDb->pSchema->file_format = 1;
  89292. }
  89293. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  89294. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  89295. rc = SQLITE_ERROR;
  89296. goto initone_error_out;
  89297. }
  89298. /* Ticket #2804: When we open a database in the newer file format,
  89299. ** clear the legacy_file_format pragma flag so that a VACUUM will
  89300. ** not downgrade the database and thus invalidate any descending
  89301. ** indices that the user might have created.
  89302. */
  89303. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  89304. db->flags &= ~SQLITE_LegacyFileFmt;
  89305. }
  89306. /* Read the schema information out of the schema tables
  89307. */
  89308. assert( db->init.busy );
  89309. {
  89310. char *zSql;
  89311. zSql = sqlite3MPrintf(db,
  89312. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  89313. db->aDb[iDb].zName, zMasterName);
  89314. #ifndef SQLITE_OMIT_AUTHORIZATION
  89315. {
  89316. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  89317. xAuth = db->xAuth;
  89318. db->xAuth = 0;
  89319. #endif
  89320. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  89321. #ifndef SQLITE_OMIT_AUTHORIZATION
  89322. db->xAuth = xAuth;
  89323. }
  89324. #endif
  89325. if( rc==SQLITE_OK ) rc = initData.rc;
  89326. sqlite3DbFree(db, zSql);
  89327. #ifndef SQLITE_OMIT_ANALYZE
  89328. if( rc==SQLITE_OK ){
  89329. sqlite3AnalysisLoad(db, iDb);
  89330. }
  89331. #endif
  89332. }
  89333. if( db->mallocFailed ){
  89334. rc = SQLITE_NOMEM;
  89335. sqlite3ResetAllSchemasOfConnection(db);
  89336. }
  89337. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  89338. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  89339. ** the schema loaded, even if errors occurred. In this situation the
  89340. ** current sqlite3_prepare() operation will fail, but the following one
  89341. ** will attempt to compile the supplied statement against whatever subset
  89342. ** of the schema was loaded before the error occurred. The primary
  89343. ** purpose of this is to allow access to the sqlite_master table
  89344. ** even when its contents have been corrupted.
  89345. */
  89346. DbSetProperty(db, iDb, DB_SchemaLoaded);
  89347. rc = SQLITE_OK;
  89348. }
  89349. /* Jump here for an error that occurs after successfully allocating
  89350. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  89351. ** before that point, jump to error_out.
  89352. */
  89353. initone_error_out:
  89354. if( openedTransaction ){
  89355. sqlite3BtreeCommit(pDb->pBt);
  89356. }
  89357. sqlite3BtreeLeave(pDb->pBt);
  89358. error_out:
  89359. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  89360. db->mallocFailed = 1;
  89361. }
  89362. return rc;
  89363. }
  89364. /*
  89365. ** Initialize all database files - the main database file, the file
  89366. ** used to store temporary tables, and any additional database files
  89367. ** created using ATTACH statements. Return a success code. If an
  89368. ** error occurs, write an error message into *pzErrMsg.
  89369. **
  89370. ** After a database is initialized, the DB_SchemaLoaded bit is set
  89371. ** bit is set in the flags field of the Db structure. If the database
  89372. ** file was of zero-length, then the DB_Empty flag is also set.
  89373. */
  89374. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  89375. int i, rc;
  89376. int commit_internal = !(db->flags&SQLITE_InternChanges);
  89377. assert( sqlite3_mutex_held(db->mutex) );
  89378. rc = SQLITE_OK;
  89379. db->init.busy = 1;
  89380. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  89381. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  89382. rc = sqlite3InitOne(db, i, pzErrMsg);
  89383. if( rc ){
  89384. sqlite3ResetOneSchema(db, i);
  89385. }
  89386. }
  89387. /* Once all the other databases have been initialized, load the schema
  89388. ** for the TEMP database. This is loaded last, as the TEMP database
  89389. ** schema may contain references to objects in other databases.
  89390. */
  89391. #ifndef SQLITE_OMIT_TEMPDB
  89392. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  89393. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  89394. rc = sqlite3InitOne(db, 1, pzErrMsg);
  89395. if( rc ){
  89396. sqlite3ResetOneSchema(db, 1);
  89397. }
  89398. }
  89399. #endif
  89400. db->init.busy = 0;
  89401. if( rc==SQLITE_OK && commit_internal ){
  89402. sqlite3CommitInternalChanges(db);
  89403. }
  89404. return rc;
  89405. }
  89406. /*
  89407. ** This routine is a no-op if the database schema is already initialized.
  89408. ** Otherwise, the schema is loaded. An error code is returned.
  89409. */
  89410. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  89411. int rc = SQLITE_OK;
  89412. sqlite3 *db = pParse->db;
  89413. assert( sqlite3_mutex_held(db->mutex) );
  89414. if( !db->init.busy ){
  89415. rc = sqlite3Init(db, &pParse->zErrMsg);
  89416. }
  89417. if( rc!=SQLITE_OK ){
  89418. pParse->rc = rc;
  89419. pParse->nErr++;
  89420. }
  89421. return rc;
  89422. }
  89423. /*
  89424. ** Check schema cookies in all databases. If any cookie is out
  89425. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  89426. ** make no changes to pParse->rc.
  89427. */
  89428. static void schemaIsValid(Parse *pParse){
  89429. sqlite3 *db = pParse->db;
  89430. int iDb;
  89431. int rc;
  89432. int cookie;
  89433. assert( pParse->checkSchema );
  89434. assert( sqlite3_mutex_held(db->mutex) );
  89435. for(iDb=0; iDb<db->nDb; iDb++){
  89436. int openedTransaction = 0; /* True if a transaction is opened */
  89437. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  89438. if( pBt==0 ) continue;
  89439. /* If there is not already a read-only (or read-write) transaction opened
  89440. ** on the b-tree database, open one now. If a transaction is opened, it
  89441. ** will be closed immediately after reading the meta-value. */
  89442. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  89443. rc = sqlite3BtreeBeginTrans(pBt, 0);
  89444. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  89445. db->mallocFailed = 1;
  89446. }
  89447. if( rc!=SQLITE_OK ) return;
  89448. openedTransaction = 1;
  89449. }
  89450. /* Read the schema cookie from the database. If it does not match the
  89451. ** value stored as part of the in-memory schema representation,
  89452. ** set Parse.rc to SQLITE_SCHEMA. */
  89453. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  89454. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89455. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  89456. sqlite3ResetOneSchema(db, iDb);
  89457. pParse->rc = SQLITE_SCHEMA;
  89458. }
  89459. /* Close the transaction, if one was opened. */
  89460. if( openedTransaction ){
  89461. sqlite3BtreeCommit(pBt);
  89462. }
  89463. }
  89464. }
  89465. /*
  89466. ** Convert a schema pointer into the iDb index that indicates
  89467. ** which database file in db->aDb[] the schema refers to.
  89468. **
  89469. ** If the same database is attached more than once, the first
  89470. ** attached database is returned.
  89471. */
  89472. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  89473. int i = -1000000;
  89474. /* If pSchema is NULL, then return -1000000. This happens when code in
  89475. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  89476. ** created by a sub-select). In this case the return value of this
  89477. ** function should never be used.
  89478. **
  89479. ** We return -1000000 instead of the more usual -1 simply because using
  89480. ** -1000000 as the incorrect index into db->aDb[] is much
  89481. ** more likely to cause a segfault than -1 (of course there are assert()
  89482. ** statements too, but it never hurts to play the odds).
  89483. */
  89484. assert( sqlite3_mutex_held(db->mutex) );
  89485. if( pSchema ){
  89486. for(i=0; ALWAYS(i<db->nDb); i++){
  89487. if( db->aDb[i].pSchema==pSchema ){
  89488. break;
  89489. }
  89490. }
  89491. assert( i>=0 && i<db->nDb );
  89492. }
  89493. return i;
  89494. }
  89495. /*
  89496. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  89497. */
  89498. static int sqlite3Prepare(
  89499. sqlite3 *db, /* Database handle. */
  89500. const char *zSql, /* UTF-8 encoded SQL statement. */
  89501. int nBytes, /* Length of zSql in bytes. */
  89502. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  89503. Vdbe *pReprepare, /* VM being reprepared */
  89504. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89505. const char **pzTail /* OUT: End of parsed string */
  89506. ){
  89507. Parse *pParse; /* Parsing context */
  89508. char *zErrMsg = 0; /* Error message */
  89509. int rc = SQLITE_OK; /* Result code */
  89510. int i; /* Loop counter */
  89511. /* Allocate the parsing context */
  89512. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  89513. if( pParse==0 ){
  89514. rc = SQLITE_NOMEM;
  89515. goto end_prepare;
  89516. }
  89517. pParse->pReprepare = pReprepare;
  89518. assert( ppStmt && *ppStmt==0 );
  89519. assert( !db->mallocFailed );
  89520. assert( sqlite3_mutex_held(db->mutex) );
  89521. /* Check to verify that it is possible to get a read lock on all
  89522. ** database schemas. The inability to get a read lock indicates that
  89523. ** some other database connection is holding a write-lock, which in
  89524. ** turn means that the other connection has made uncommitted changes
  89525. ** to the schema.
  89526. **
  89527. ** Were we to proceed and prepare the statement against the uncommitted
  89528. ** schema changes and if those schema changes are subsequently rolled
  89529. ** back and different changes are made in their place, then when this
  89530. ** prepared statement goes to run the schema cookie would fail to detect
  89531. ** the schema change. Disaster would follow.
  89532. **
  89533. ** This thread is currently holding mutexes on all Btrees (because
  89534. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  89535. ** is not possible for another thread to start a new schema change
  89536. ** while this routine is running. Hence, we do not need to hold
  89537. ** locks on the schema, we just need to make sure nobody else is
  89538. ** holding them.
  89539. **
  89540. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  89541. ** but it does *not* override schema lock detection, so this all still
  89542. ** works even if READ_UNCOMMITTED is set.
  89543. */
  89544. for(i=0; i<db->nDb; i++) {
  89545. Btree *pBt = db->aDb[i].pBt;
  89546. if( pBt ){
  89547. assert( sqlite3BtreeHoldsMutex(pBt) );
  89548. rc = sqlite3BtreeSchemaLocked(pBt);
  89549. if( rc ){
  89550. const char *zDb = db->aDb[i].zName;
  89551. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  89552. testcase( db->flags & SQLITE_ReadUncommitted );
  89553. goto end_prepare;
  89554. }
  89555. }
  89556. }
  89557. sqlite3VtabUnlockList(db);
  89558. pParse->db = db;
  89559. pParse->nQueryLoop = (double)1;
  89560. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  89561. char *zSqlCopy;
  89562. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  89563. testcase( nBytes==mxLen );
  89564. testcase( nBytes==mxLen+1 );
  89565. if( nBytes>mxLen ){
  89566. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  89567. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  89568. goto end_prepare;
  89569. }
  89570. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  89571. if( zSqlCopy ){
  89572. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  89573. sqlite3DbFree(db, zSqlCopy);
  89574. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  89575. }else{
  89576. pParse->zTail = &zSql[nBytes];
  89577. }
  89578. }else{
  89579. sqlite3RunParser(pParse, zSql, &zErrMsg);
  89580. }
  89581. assert( 1==(int)pParse->nQueryLoop );
  89582. if( db->mallocFailed ){
  89583. pParse->rc = SQLITE_NOMEM;
  89584. }
  89585. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  89586. if( pParse->checkSchema ){
  89587. schemaIsValid(pParse);
  89588. }
  89589. if( db->mallocFailed ){
  89590. pParse->rc = SQLITE_NOMEM;
  89591. }
  89592. if( pzTail ){
  89593. *pzTail = pParse->zTail;
  89594. }
  89595. rc = pParse->rc;
  89596. #ifndef SQLITE_OMIT_EXPLAIN
  89597. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  89598. static const char * const azColName[] = {
  89599. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  89600. "selectid", "order", "from", "detail"
  89601. };
  89602. int iFirst, mx;
  89603. if( pParse->explain==2 ){
  89604. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  89605. iFirst = 8;
  89606. mx = 12;
  89607. }else{
  89608. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  89609. iFirst = 0;
  89610. mx = 8;
  89611. }
  89612. for(i=iFirst; i<mx; i++){
  89613. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  89614. azColName[i], SQLITE_STATIC);
  89615. }
  89616. }
  89617. #endif
  89618. if( db->init.busy==0 ){
  89619. Vdbe *pVdbe = pParse->pVdbe;
  89620. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  89621. }
  89622. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  89623. sqlite3VdbeFinalize(pParse->pVdbe);
  89624. assert(!(*ppStmt));
  89625. }else{
  89626. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  89627. }
  89628. if( zErrMsg ){
  89629. sqlite3Error(db, rc, "%s", zErrMsg);
  89630. sqlite3DbFree(db, zErrMsg);
  89631. }else{
  89632. sqlite3Error(db, rc, 0);
  89633. }
  89634. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  89635. while( pParse->pTriggerPrg ){
  89636. TriggerPrg *pT = pParse->pTriggerPrg;
  89637. pParse->pTriggerPrg = pT->pNext;
  89638. sqlite3DbFree(db, pT);
  89639. }
  89640. end_prepare:
  89641. sqlite3StackFree(db, pParse);
  89642. rc = sqlite3ApiExit(db, rc);
  89643. assert( (rc&db->errMask)==rc );
  89644. return rc;
  89645. }
  89646. static int sqlite3LockAndPrepare(
  89647. sqlite3 *db, /* Database handle. */
  89648. const char *zSql, /* UTF-8 encoded SQL statement. */
  89649. int nBytes, /* Length of zSql in bytes. */
  89650. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  89651. Vdbe *pOld, /* VM being reprepared */
  89652. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89653. const char **pzTail /* OUT: End of parsed string */
  89654. ){
  89655. int rc;
  89656. assert( ppStmt!=0 );
  89657. *ppStmt = 0;
  89658. if( !sqlite3SafetyCheckOk(db) ){
  89659. return SQLITE_MISUSE_BKPT;
  89660. }
  89661. sqlite3_mutex_enter(db->mutex);
  89662. sqlite3BtreeEnterAll(db);
  89663. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  89664. if( rc==SQLITE_SCHEMA ){
  89665. sqlite3_finalize(*ppStmt);
  89666. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  89667. }
  89668. sqlite3BtreeLeaveAll(db);
  89669. sqlite3_mutex_leave(db->mutex);
  89670. assert( rc==SQLITE_OK || *ppStmt==0 );
  89671. return rc;
  89672. }
  89673. /*
  89674. ** Rerun the compilation of a statement after a schema change.
  89675. **
  89676. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  89677. ** if the statement cannot be recompiled because another connection has
  89678. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  89679. ** occurs, return SQLITE_SCHEMA.
  89680. */
  89681. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  89682. int rc;
  89683. sqlite3_stmt *pNew;
  89684. const char *zSql;
  89685. sqlite3 *db;
  89686. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  89687. zSql = sqlite3_sql((sqlite3_stmt *)p);
  89688. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  89689. db = sqlite3VdbeDb(p);
  89690. assert( sqlite3_mutex_held(db->mutex) );
  89691. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  89692. if( rc ){
  89693. if( rc==SQLITE_NOMEM ){
  89694. db->mallocFailed = 1;
  89695. }
  89696. assert( pNew==0 );
  89697. return rc;
  89698. }else{
  89699. assert( pNew!=0 );
  89700. }
  89701. sqlite3VdbeSwap((Vdbe*)pNew, p);
  89702. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  89703. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  89704. sqlite3VdbeFinalize((Vdbe*)pNew);
  89705. return SQLITE_OK;
  89706. }
  89707. /*
  89708. ** Two versions of the official API. Legacy and new use. In the legacy
  89709. ** version, the original SQL text is not saved in the prepared statement
  89710. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  89711. ** sqlite3_step(). In the new version, the original SQL text is retained
  89712. ** and the statement is automatically recompiled if an schema change
  89713. ** occurs.
  89714. */
  89715. SQLITE_API int sqlite3_prepare(
  89716. sqlite3 *db, /* Database handle. */
  89717. const char *zSql, /* UTF-8 encoded SQL statement. */
  89718. int nBytes, /* Length of zSql in bytes. */
  89719. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89720. const char **pzTail /* OUT: End of parsed string */
  89721. ){
  89722. int rc;
  89723. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  89724. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  89725. return rc;
  89726. }
  89727. SQLITE_API int sqlite3_prepare_v2(
  89728. sqlite3 *db, /* Database handle. */
  89729. const char *zSql, /* UTF-8 encoded SQL statement. */
  89730. int nBytes, /* Length of zSql in bytes. */
  89731. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89732. const char **pzTail /* OUT: End of parsed string */
  89733. ){
  89734. int rc;
  89735. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  89736. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  89737. return rc;
  89738. }
  89739. #ifndef SQLITE_OMIT_UTF16
  89740. /*
  89741. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  89742. */
  89743. static int sqlite3Prepare16(
  89744. sqlite3 *db, /* Database handle. */
  89745. const void *zSql, /* UTF-16 encoded SQL statement. */
  89746. int nBytes, /* Length of zSql in bytes. */
  89747. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  89748. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89749. const void **pzTail /* OUT: End of parsed string */
  89750. ){
  89751. /* This function currently works by first transforming the UTF-16
  89752. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  89753. ** tricky bit is figuring out the pointer to return in *pzTail.
  89754. */
  89755. char *zSql8;
  89756. const char *zTail8 = 0;
  89757. int rc = SQLITE_OK;
  89758. assert( ppStmt );
  89759. *ppStmt = 0;
  89760. if( !sqlite3SafetyCheckOk(db) ){
  89761. return SQLITE_MISUSE_BKPT;
  89762. }
  89763. sqlite3_mutex_enter(db->mutex);
  89764. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  89765. if( zSql8 ){
  89766. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  89767. }
  89768. if( zTail8 && pzTail ){
  89769. /* If sqlite3_prepare returns a tail pointer, we calculate the
  89770. ** equivalent pointer into the UTF-16 string by counting the unicode
  89771. ** characters between zSql8 and zTail8, and then returning a pointer
  89772. ** the same number of characters into the UTF-16 string.
  89773. */
  89774. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  89775. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  89776. }
  89777. sqlite3DbFree(db, zSql8);
  89778. rc = sqlite3ApiExit(db, rc);
  89779. sqlite3_mutex_leave(db->mutex);
  89780. return rc;
  89781. }
  89782. /*
  89783. ** Two versions of the official API. Legacy and new use. In the legacy
  89784. ** version, the original SQL text is not saved in the prepared statement
  89785. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  89786. ** sqlite3_step(). In the new version, the original SQL text is retained
  89787. ** and the statement is automatically recompiled if an schema change
  89788. ** occurs.
  89789. */
  89790. SQLITE_API int sqlite3_prepare16(
  89791. sqlite3 *db, /* Database handle. */
  89792. const void *zSql, /* UTF-16 encoded SQL statement. */
  89793. int nBytes, /* Length of zSql in bytes. */
  89794. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89795. const void **pzTail /* OUT: End of parsed string */
  89796. ){
  89797. int rc;
  89798. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  89799. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  89800. return rc;
  89801. }
  89802. SQLITE_API int sqlite3_prepare16_v2(
  89803. sqlite3 *db, /* Database handle. */
  89804. const void *zSql, /* UTF-16 encoded SQL statement. */
  89805. int nBytes, /* Length of zSql in bytes. */
  89806. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  89807. const void **pzTail /* OUT: End of parsed string */
  89808. ){
  89809. int rc;
  89810. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  89811. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  89812. return rc;
  89813. }
  89814. #endif /* SQLITE_OMIT_UTF16 */
  89815. /************** End of prepare.c *********************************************/
  89816. /************** Begin file select.c ******************************************/
  89817. /*
  89818. ** 2001 September 15
  89819. **
  89820. ** The author disclaims copyright to this source code. In place of
  89821. ** a legal notice, here is a blessing:
  89822. **
  89823. ** May you do good and not evil.
  89824. ** May you find forgiveness for yourself and forgive others.
  89825. ** May you share freely, never taking more than you give.
  89826. **
  89827. *************************************************************************
  89828. ** This file contains C code routines that are called by the parser
  89829. ** to handle SELECT statements in SQLite.
  89830. */
  89831. /*
  89832. ** Delete all the content of a Select structure but do not deallocate
  89833. ** the select structure itself.
  89834. */
  89835. static void clearSelect(sqlite3 *db, Select *p){
  89836. sqlite3ExprListDelete(db, p->pEList);
  89837. sqlite3SrcListDelete(db, p->pSrc);
  89838. sqlite3ExprDelete(db, p->pWhere);
  89839. sqlite3ExprListDelete(db, p->pGroupBy);
  89840. sqlite3ExprDelete(db, p->pHaving);
  89841. sqlite3ExprListDelete(db, p->pOrderBy);
  89842. sqlite3SelectDelete(db, p->pPrior);
  89843. sqlite3ExprDelete(db, p->pLimit);
  89844. sqlite3ExprDelete(db, p->pOffset);
  89845. }
  89846. /*
  89847. ** Initialize a SelectDest structure.
  89848. */
  89849. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  89850. pDest->eDest = (u8)eDest;
  89851. pDest->iSDParm = iParm;
  89852. pDest->affSdst = 0;
  89853. pDest->iSdst = 0;
  89854. pDest->nSdst = 0;
  89855. }
  89856. /*
  89857. ** Allocate a new Select structure and return a pointer to that
  89858. ** structure.
  89859. */
  89860. SQLITE_PRIVATE Select *sqlite3SelectNew(
  89861. Parse *pParse, /* Parsing context */
  89862. ExprList *pEList, /* which columns to include in the result */
  89863. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  89864. Expr *pWhere, /* the WHERE clause */
  89865. ExprList *pGroupBy, /* the GROUP BY clause */
  89866. Expr *pHaving, /* the HAVING clause */
  89867. ExprList *pOrderBy, /* the ORDER BY clause */
  89868. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  89869. Expr *pLimit, /* LIMIT value. NULL means not used */
  89870. Expr *pOffset /* OFFSET value. NULL means no offset */
  89871. ){
  89872. Select *pNew;
  89873. Select standin;
  89874. sqlite3 *db = pParse->db;
  89875. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  89876. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  89877. if( pNew==0 ){
  89878. assert( db->mallocFailed );
  89879. pNew = &standin;
  89880. memset(pNew, 0, sizeof(*pNew));
  89881. }
  89882. if( pEList==0 ){
  89883. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  89884. }
  89885. pNew->pEList = pEList;
  89886. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  89887. pNew->pSrc = pSrc;
  89888. pNew->pWhere = pWhere;
  89889. pNew->pGroupBy = pGroupBy;
  89890. pNew->pHaving = pHaving;
  89891. pNew->pOrderBy = pOrderBy;
  89892. pNew->selFlags = selFlags;
  89893. pNew->op = TK_SELECT;
  89894. pNew->pLimit = pLimit;
  89895. pNew->pOffset = pOffset;
  89896. assert( pOffset==0 || pLimit!=0 );
  89897. pNew->addrOpenEphm[0] = -1;
  89898. pNew->addrOpenEphm[1] = -1;
  89899. pNew->addrOpenEphm[2] = -1;
  89900. if( db->mallocFailed ) {
  89901. clearSelect(db, pNew);
  89902. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  89903. pNew = 0;
  89904. }else{
  89905. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  89906. }
  89907. assert( pNew!=&standin );
  89908. return pNew;
  89909. }
  89910. /*
  89911. ** Delete the given Select structure and all of its substructures.
  89912. */
  89913. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  89914. if( p ){
  89915. clearSelect(db, p);
  89916. sqlite3DbFree(db, p);
  89917. }
  89918. }
  89919. /*
  89920. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  89921. ** type of join. Return an integer constant that expresses that type
  89922. ** in terms of the following bit values:
  89923. **
  89924. ** JT_INNER
  89925. ** JT_CROSS
  89926. ** JT_OUTER
  89927. ** JT_NATURAL
  89928. ** JT_LEFT
  89929. ** JT_RIGHT
  89930. **
  89931. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  89932. **
  89933. ** If an illegal or unsupported join type is seen, then still return
  89934. ** a join type, but put an error in the pParse structure.
  89935. */
  89936. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  89937. int jointype = 0;
  89938. Token *apAll[3];
  89939. Token *p;
  89940. /* 0123456789 123456789 123456789 123 */
  89941. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  89942. static const struct {
  89943. u8 i; /* Beginning of keyword text in zKeyText[] */
  89944. u8 nChar; /* Length of the keyword in characters */
  89945. u8 code; /* Join type mask */
  89946. } aKeyword[] = {
  89947. /* natural */ { 0, 7, JT_NATURAL },
  89948. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  89949. /* outer */ { 10, 5, JT_OUTER },
  89950. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  89951. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  89952. /* inner */ { 23, 5, JT_INNER },
  89953. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  89954. };
  89955. int i, j;
  89956. apAll[0] = pA;
  89957. apAll[1] = pB;
  89958. apAll[2] = pC;
  89959. for(i=0; i<3 && apAll[i]; i++){
  89960. p = apAll[i];
  89961. for(j=0; j<ArraySize(aKeyword); j++){
  89962. if( p->n==aKeyword[j].nChar
  89963. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  89964. jointype |= aKeyword[j].code;
  89965. break;
  89966. }
  89967. }
  89968. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  89969. if( j>=ArraySize(aKeyword) ){
  89970. jointype |= JT_ERROR;
  89971. break;
  89972. }
  89973. }
  89974. if(
  89975. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  89976. (jointype & JT_ERROR)!=0
  89977. ){
  89978. const char *zSp = " ";
  89979. assert( pB!=0 );
  89980. if( pC==0 ){ zSp++; }
  89981. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  89982. "%T %T%s%T", pA, pB, zSp, pC);
  89983. jointype = JT_INNER;
  89984. }else if( (jointype & JT_OUTER)!=0
  89985. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  89986. sqlite3ErrorMsg(pParse,
  89987. "RIGHT and FULL OUTER JOINs are not currently supported");
  89988. jointype = JT_INNER;
  89989. }
  89990. return jointype;
  89991. }
  89992. /*
  89993. ** Return the index of a column in a table. Return -1 if the column
  89994. ** is not contained in the table.
  89995. */
  89996. static int columnIndex(Table *pTab, const char *zCol){
  89997. int i;
  89998. for(i=0; i<pTab->nCol; i++){
  89999. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  90000. }
  90001. return -1;
  90002. }
  90003. /*
  90004. ** Search the first N tables in pSrc, from left to right, looking for a
  90005. ** table that has a column named zCol.
  90006. **
  90007. ** When found, set *piTab and *piCol to the table index and column index
  90008. ** of the matching column and return TRUE.
  90009. **
  90010. ** If not found, return FALSE.
  90011. */
  90012. static int tableAndColumnIndex(
  90013. SrcList *pSrc, /* Array of tables to search */
  90014. int N, /* Number of tables in pSrc->a[] to search */
  90015. const char *zCol, /* Name of the column we are looking for */
  90016. int *piTab, /* Write index of pSrc->a[] here */
  90017. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  90018. ){
  90019. int i; /* For looping over tables in pSrc */
  90020. int iCol; /* Index of column matching zCol */
  90021. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  90022. for(i=0; i<N; i++){
  90023. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  90024. if( iCol>=0 ){
  90025. if( piTab ){
  90026. *piTab = i;
  90027. *piCol = iCol;
  90028. }
  90029. return 1;
  90030. }
  90031. }
  90032. return 0;
  90033. }
  90034. /*
  90035. ** This function is used to add terms implied by JOIN syntax to the
  90036. ** WHERE clause expression of a SELECT statement. The new term, which
  90037. ** is ANDed with the existing WHERE clause, is of the form:
  90038. **
  90039. ** (tab1.col1 = tab2.col2)
  90040. **
  90041. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  90042. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  90043. ** column iColRight of tab2.
  90044. */
  90045. static void addWhereTerm(
  90046. Parse *pParse, /* Parsing context */
  90047. SrcList *pSrc, /* List of tables in FROM clause */
  90048. int iLeft, /* Index of first table to join in pSrc */
  90049. int iColLeft, /* Index of column in first table */
  90050. int iRight, /* Index of second table in pSrc */
  90051. int iColRight, /* Index of column in second table */
  90052. int isOuterJoin, /* True if this is an OUTER join */
  90053. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  90054. ){
  90055. sqlite3 *db = pParse->db;
  90056. Expr *pE1;
  90057. Expr *pE2;
  90058. Expr *pEq;
  90059. assert( iLeft<iRight );
  90060. assert( pSrc->nSrc>iRight );
  90061. assert( pSrc->a[iLeft].pTab );
  90062. assert( pSrc->a[iRight].pTab );
  90063. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  90064. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  90065. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  90066. if( pEq && isOuterJoin ){
  90067. ExprSetProperty(pEq, EP_FromJoin);
  90068. assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
  90069. ExprSetIrreducible(pEq);
  90070. pEq->iRightJoinTable = (i16)pE2->iTable;
  90071. }
  90072. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  90073. }
  90074. /*
  90075. ** Set the EP_FromJoin property on all terms of the given expression.
  90076. ** And set the Expr.iRightJoinTable to iTable for every term in the
  90077. ** expression.
  90078. **
  90079. ** The EP_FromJoin property is used on terms of an expression to tell
  90080. ** the LEFT OUTER JOIN processing logic that this term is part of the
  90081. ** join restriction specified in the ON or USING clause and not a part
  90082. ** of the more general WHERE clause. These terms are moved over to the
  90083. ** WHERE clause during join processing but we need to remember that they
  90084. ** originated in the ON or USING clause.
  90085. **
  90086. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  90087. ** expression depends on table iRightJoinTable even if that table is not
  90088. ** explicitly mentioned in the expression. That information is needed
  90089. ** for cases like this:
  90090. **
  90091. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  90092. **
  90093. ** The where clause needs to defer the handling of the t1.x=5
  90094. ** term until after the t2 loop of the join. In that way, a
  90095. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  90096. ** defer the handling of t1.x=5, it will be processed immediately
  90097. ** after the t1 loop and rows with t1.x!=5 will never appear in
  90098. ** the output, which is incorrect.
  90099. */
  90100. static void setJoinExpr(Expr *p, int iTable){
  90101. while( p ){
  90102. ExprSetProperty(p, EP_FromJoin);
  90103. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  90104. ExprSetIrreducible(p);
  90105. p->iRightJoinTable = (i16)iTable;
  90106. setJoinExpr(p->pLeft, iTable);
  90107. p = p->pRight;
  90108. }
  90109. }
  90110. /*
  90111. ** This routine processes the join information for a SELECT statement.
  90112. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  90113. ** NATURAL joins also create extra WHERE clause terms.
  90114. **
  90115. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  90116. ** The left most table is the first entry in Select.pSrc. The right-most
  90117. ** table is the last entry. The join operator is held in the entry to
  90118. ** the left. Thus entry 0 contains the join operator for the join between
  90119. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  90120. ** also attached to the left entry.
  90121. **
  90122. ** This routine returns the number of errors encountered.
  90123. */
  90124. static int sqliteProcessJoin(Parse *pParse, Select *p){
  90125. SrcList *pSrc; /* All tables in the FROM clause */
  90126. int i, j; /* Loop counters */
  90127. struct SrcList_item *pLeft; /* Left table being joined */
  90128. struct SrcList_item *pRight; /* Right table being joined */
  90129. pSrc = p->pSrc;
  90130. pLeft = &pSrc->a[0];
  90131. pRight = &pLeft[1];
  90132. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  90133. Table *pLeftTab = pLeft->pTab;
  90134. Table *pRightTab = pRight->pTab;
  90135. int isOuter;
  90136. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  90137. isOuter = (pRight->jointype & JT_OUTER)!=0;
  90138. /* When the NATURAL keyword is present, add WHERE clause terms for
  90139. ** every column that the two tables have in common.
  90140. */
  90141. if( pRight->jointype & JT_NATURAL ){
  90142. if( pRight->pOn || pRight->pUsing ){
  90143. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  90144. "an ON or USING clause", 0);
  90145. return 1;
  90146. }
  90147. for(j=0; j<pRightTab->nCol; j++){
  90148. char *zName; /* Name of column in the right table */
  90149. int iLeft; /* Matching left table */
  90150. int iLeftCol; /* Matching column in the left table */
  90151. zName = pRightTab->aCol[j].zName;
  90152. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  90153. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  90154. isOuter, &p->pWhere);
  90155. }
  90156. }
  90157. }
  90158. /* Disallow both ON and USING clauses in the same join
  90159. */
  90160. if( pRight->pOn && pRight->pUsing ){
  90161. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  90162. "clauses in the same join");
  90163. return 1;
  90164. }
  90165. /* Add the ON clause to the end of the WHERE clause, connected by
  90166. ** an AND operator.
  90167. */
  90168. if( pRight->pOn ){
  90169. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  90170. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  90171. pRight->pOn = 0;
  90172. }
  90173. /* Create extra terms on the WHERE clause for each column named
  90174. ** in the USING clause. Example: If the two tables to be joined are
  90175. ** A and B and the USING clause names X, Y, and Z, then add this
  90176. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  90177. ** Report an error if any column mentioned in the USING clause is
  90178. ** not contained in both tables to be joined.
  90179. */
  90180. if( pRight->pUsing ){
  90181. IdList *pList = pRight->pUsing;
  90182. for(j=0; j<pList->nId; j++){
  90183. char *zName; /* Name of the term in the USING clause */
  90184. int iLeft; /* Table on the left with matching column name */
  90185. int iLeftCol; /* Column number of matching column on the left */
  90186. int iRightCol; /* Column number of matching column on the right */
  90187. zName = pList->a[j].zName;
  90188. iRightCol = columnIndex(pRightTab, zName);
  90189. if( iRightCol<0
  90190. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  90191. ){
  90192. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  90193. "not present in both tables", zName);
  90194. return 1;
  90195. }
  90196. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  90197. isOuter, &p->pWhere);
  90198. }
  90199. }
  90200. }
  90201. return 0;
  90202. }
  90203. /*
  90204. ** Insert code into "v" that will push the record on the top of the
  90205. ** stack into the sorter.
  90206. */
  90207. static void pushOntoSorter(
  90208. Parse *pParse, /* Parser context */
  90209. ExprList *pOrderBy, /* The ORDER BY clause */
  90210. Select *pSelect, /* The whole SELECT statement */
  90211. int regData /* Register holding data to be sorted */
  90212. ){
  90213. Vdbe *v = pParse->pVdbe;
  90214. int nExpr = pOrderBy->nExpr;
  90215. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  90216. int regRecord = sqlite3GetTempReg(pParse);
  90217. int op;
  90218. sqlite3ExprCacheClear(pParse);
  90219. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  90220. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  90221. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  90222. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  90223. if( pSelect->selFlags & SF_UseSorter ){
  90224. op = OP_SorterInsert;
  90225. }else{
  90226. op = OP_IdxInsert;
  90227. }
  90228. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  90229. sqlite3ReleaseTempReg(pParse, regRecord);
  90230. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  90231. if( pSelect->iLimit ){
  90232. int addr1, addr2;
  90233. int iLimit;
  90234. if( pSelect->iOffset ){
  90235. iLimit = pSelect->iOffset+1;
  90236. }else{
  90237. iLimit = pSelect->iLimit;
  90238. }
  90239. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  90240. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  90241. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  90242. sqlite3VdbeJumpHere(v, addr1);
  90243. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  90244. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  90245. sqlite3VdbeJumpHere(v, addr2);
  90246. }
  90247. }
  90248. /*
  90249. ** Add code to implement the OFFSET
  90250. */
  90251. static void codeOffset(
  90252. Vdbe *v, /* Generate code into this VM */
  90253. Select *p, /* The SELECT statement being coded */
  90254. int iContinue /* Jump here to skip the current record */
  90255. ){
  90256. if( p->iOffset && iContinue!=0 ){
  90257. int addr;
  90258. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  90259. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  90260. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  90261. VdbeComment((v, "skip OFFSET records"));
  90262. sqlite3VdbeJumpHere(v, addr);
  90263. }
  90264. }
  90265. /*
  90266. ** Add code that will check to make sure the N registers starting at iMem
  90267. ** form a distinct entry. iTab is a sorting index that holds previously
  90268. ** seen combinations of the N values. A new entry is made in iTab
  90269. ** if the current N values are new.
  90270. **
  90271. ** A jump to addrRepeat is made and the N+1 values are popped from the
  90272. ** stack if the top N elements are not distinct.
  90273. */
  90274. static void codeDistinct(
  90275. Parse *pParse, /* Parsing and code generating context */
  90276. int iTab, /* A sorting index used to test for distinctness */
  90277. int addrRepeat, /* Jump to here if not distinct */
  90278. int N, /* Number of elements */
  90279. int iMem /* First element */
  90280. ){
  90281. Vdbe *v;
  90282. int r1;
  90283. v = pParse->pVdbe;
  90284. r1 = sqlite3GetTempReg(pParse);
  90285. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  90286. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  90287. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  90288. sqlite3ReleaseTempReg(pParse, r1);
  90289. }
  90290. #ifndef SQLITE_OMIT_SUBQUERY
  90291. /*
  90292. ** Generate an error message when a SELECT is used within a subexpression
  90293. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  90294. ** column. We do this in a subroutine because the error used to occur
  90295. ** in multiple places. (The error only occurs in one place now, but we
  90296. ** retain the subroutine to minimize code disruption.)
  90297. */
  90298. static int checkForMultiColumnSelectError(
  90299. Parse *pParse, /* Parse context. */
  90300. SelectDest *pDest, /* Destination of SELECT results */
  90301. int nExpr /* Number of result columns returned by SELECT */
  90302. ){
  90303. int eDest = pDest->eDest;
  90304. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  90305. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  90306. "a SELECT that is part of an expression");
  90307. return 1;
  90308. }else{
  90309. return 0;
  90310. }
  90311. }
  90312. #endif
  90313. /*
  90314. ** An instance of the following object is used to record information about
  90315. ** how to process the DISTINCT keyword, to simplify passing that information
  90316. ** into the selectInnerLoop() routine.
  90317. */
  90318. typedef struct DistinctCtx DistinctCtx;
  90319. struct DistinctCtx {
  90320. u8 isTnct; /* True if the DISTINCT keyword is present */
  90321. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  90322. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  90323. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  90324. };
  90325. /*
  90326. ** This routine generates the code for the inside of the inner loop
  90327. ** of a SELECT.
  90328. **
  90329. ** If srcTab and nColumn are both zero, then the pEList expressions
  90330. ** are evaluated in order to get the data for this row. If nColumn>0
  90331. ** then data is pulled from srcTab and pEList is used only to get the
  90332. ** datatypes for each column.
  90333. */
  90334. static void selectInnerLoop(
  90335. Parse *pParse, /* The parser context */
  90336. Select *p, /* The complete select statement being coded */
  90337. ExprList *pEList, /* List of values being extracted */
  90338. int srcTab, /* Pull data from this table */
  90339. int nColumn, /* Number of columns in the source table */
  90340. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  90341. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  90342. SelectDest *pDest, /* How to dispose of the results */
  90343. int iContinue, /* Jump here to continue with next row */
  90344. int iBreak /* Jump here to break out of the inner loop */
  90345. ){
  90346. Vdbe *v = pParse->pVdbe;
  90347. int i;
  90348. int hasDistinct; /* True if the DISTINCT keyword is present */
  90349. int regResult; /* Start of memory holding result set */
  90350. int eDest = pDest->eDest; /* How to dispose of results */
  90351. int iParm = pDest->iSDParm; /* First argument to disposal method */
  90352. int nResultCol; /* Number of result columns */
  90353. assert( v );
  90354. if( NEVER(v==0) ) return;
  90355. assert( pEList!=0 );
  90356. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  90357. if( pOrderBy==0 && !hasDistinct ){
  90358. codeOffset(v, p, iContinue);
  90359. }
  90360. /* Pull the requested columns.
  90361. */
  90362. if( nColumn>0 ){
  90363. nResultCol = nColumn;
  90364. }else{
  90365. nResultCol = pEList->nExpr;
  90366. }
  90367. if( pDest->iSdst==0 ){
  90368. pDest->iSdst = pParse->nMem+1;
  90369. pDest->nSdst = nResultCol;
  90370. pParse->nMem += nResultCol;
  90371. }else{
  90372. assert( pDest->nSdst==nResultCol );
  90373. }
  90374. regResult = pDest->iSdst;
  90375. if( nColumn>0 ){
  90376. for(i=0; i<nColumn; i++){
  90377. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  90378. }
  90379. }else if( eDest!=SRT_Exists ){
  90380. /* If the destination is an EXISTS(...) expression, the actual
  90381. ** values returned by the SELECT are not required.
  90382. */
  90383. sqlite3ExprCacheClear(pParse);
  90384. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  90385. }
  90386. nColumn = nResultCol;
  90387. /* If the DISTINCT keyword was present on the SELECT statement
  90388. ** and this row has been seen before, then do not make this row
  90389. ** part of the result.
  90390. */
  90391. if( hasDistinct ){
  90392. assert( pEList!=0 );
  90393. assert( pEList->nExpr==nColumn );
  90394. switch( pDistinct->eTnctType ){
  90395. case WHERE_DISTINCT_ORDERED: {
  90396. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  90397. int iJump; /* Jump destination */
  90398. int regPrev; /* Previous row content */
  90399. /* Allocate space for the previous row */
  90400. regPrev = pParse->nMem+1;
  90401. pParse->nMem += nColumn;
  90402. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  90403. ** sets the MEM_Cleared bit on the first register of the
  90404. ** previous value. This will cause the OP_Ne below to always
  90405. ** fail on the first iteration of the loop even if the first
  90406. ** row is all NULLs.
  90407. */
  90408. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  90409. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  90410. pOp->opcode = OP_Null;
  90411. pOp->p1 = 1;
  90412. pOp->p2 = regPrev;
  90413. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  90414. for(i=0; i<nColumn; i++){
  90415. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  90416. if( i<nColumn-1 ){
  90417. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  90418. }else{
  90419. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  90420. }
  90421. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  90422. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  90423. }
  90424. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  90425. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  90426. break;
  90427. }
  90428. case WHERE_DISTINCT_UNIQUE: {
  90429. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  90430. break;
  90431. }
  90432. default: {
  90433. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  90434. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  90435. break;
  90436. }
  90437. }
  90438. if( pOrderBy==0 ){
  90439. codeOffset(v, p, iContinue);
  90440. }
  90441. }
  90442. switch( eDest ){
  90443. /* In this mode, write each query result to the key of the temporary
  90444. ** table iParm.
  90445. */
  90446. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  90447. case SRT_Union: {
  90448. int r1;
  90449. r1 = sqlite3GetTempReg(pParse);
  90450. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  90451. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  90452. sqlite3ReleaseTempReg(pParse, r1);
  90453. break;
  90454. }
  90455. /* Construct a record from the query result, but instead of
  90456. ** saving that record, use it as a key to delete elements from
  90457. ** the temporary table iParm.
  90458. */
  90459. case SRT_Except: {
  90460. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  90461. break;
  90462. }
  90463. #endif
  90464. /* Store the result as data using a unique key.
  90465. */
  90466. case SRT_Table:
  90467. case SRT_EphemTab: {
  90468. int r1 = sqlite3GetTempReg(pParse);
  90469. testcase( eDest==SRT_Table );
  90470. testcase( eDest==SRT_EphemTab );
  90471. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  90472. if( pOrderBy ){
  90473. pushOntoSorter(pParse, pOrderBy, p, r1);
  90474. }else{
  90475. int r2 = sqlite3GetTempReg(pParse);
  90476. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  90477. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  90478. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  90479. sqlite3ReleaseTempReg(pParse, r2);
  90480. }
  90481. sqlite3ReleaseTempReg(pParse, r1);
  90482. break;
  90483. }
  90484. #ifndef SQLITE_OMIT_SUBQUERY
  90485. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  90486. ** then there should be a single item on the stack. Write this
  90487. ** item into the set table with bogus data.
  90488. */
  90489. case SRT_Set: {
  90490. assert( nColumn==1 );
  90491. pDest->affSdst =
  90492. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  90493. if( pOrderBy ){
  90494. /* At first glance you would think we could optimize out the
  90495. ** ORDER BY in this case since the order of entries in the set
  90496. ** does not matter. But there might be a LIMIT clause, in which
  90497. ** case the order does matter */
  90498. pushOntoSorter(pParse, pOrderBy, p, regResult);
  90499. }else{
  90500. int r1 = sqlite3GetTempReg(pParse);
  90501. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  90502. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  90503. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  90504. sqlite3ReleaseTempReg(pParse, r1);
  90505. }
  90506. break;
  90507. }
  90508. /* If any row exist in the result set, record that fact and abort.
  90509. */
  90510. case SRT_Exists: {
  90511. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  90512. /* The LIMIT clause will terminate the loop for us */
  90513. break;
  90514. }
  90515. /* If this is a scalar select that is part of an expression, then
  90516. ** store the results in the appropriate memory cell and break out
  90517. ** of the scan loop.
  90518. */
  90519. case SRT_Mem: {
  90520. assert( nColumn==1 );
  90521. if( pOrderBy ){
  90522. pushOntoSorter(pParse, pOrderBy, p, regResult);
  90523. }else{
  90524. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  90525. /* The LIMIT clause will jump out of the loop for us */
  90526. }
  90527. break;
  90528. }
  90529. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  90530. /* Send the data to the callback function or to a subroutine. In the
  90531. ** case of a subroutine, the subroutine itself is responsible for
  90532. ** popping the data from the stack.
  90533. */
  90534. case SRT_Coroutine:
  90535. case SRT_Output: {
  90536. testcase( eDest==SRT_Coroutine );
  90537. testcase( eDest==SRT_Output );
  90538. if( pOrderBy ){
  90539. int r1 = sqlite3GetTempReg(pParse);
  90540. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  90541. pushOntoSorter(pParse, pOrderBy, p, r1);
  90542. sqlite3ReleaseTempReg(pParse, r1);
  90543. }else if( eDest==SRT_Coroutine ){
  90544. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  90545. }else{
  90546. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  90547. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  90548. }
  90549. break;
  90550. }
  90551. #if !defined(SQLITE_OMIT_TRIGGER)
  90552. /* Discard the results. This is used for SELECT statements inside
  90553. ** the body of a TRIGGER. The purpose of such selects is to call
  90554. ** user-defined functions that have side effects. We do not care
  90555. ** about the actual results of the select.
  90556. */
  90557. default: {
  90558. assert( eDest==SRT_Discard );
  90559. break;
  90560. }
  90561. #endif
  90562. }
  90563. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  90564. ** there is a sorter, in which case the sorter has already limited
  90565. ** the output for us.
  90566. */
  90567. if( pOrderBy==0 && p->iLimit ){
  90568. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  90569. }
  90570. }
  90571. /*
  90572. ** Given an expression list, generate a KeyInfo structure that records
  90573. ** the collating sequence for each expression in that expression list.
  90574. **
  90575. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  90576. ** KeyInfo structure is appropriate for initializing a virtual index to
  90577. ** implement that clause. If the ExprList is the result set of a SELECT
  90578. ** then the KeyInfo structure is appropriate for initializing a virtual
  90579. ** index to implement a DISTINCT test.
  90580. **
  90581. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  90582. ** function is responsible for seeing that this structure is eventually
  90583. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  90584. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  90585. */
  90586. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  90587. sqlite3 *db = pParse->db;
  90588. int nExpr;
  90589. KeyInfo *pInfo;
  90590. struct ExprList_item *pItem;
  90591. int i;
  90592. nExpr = pList->nExpr;
  90593. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  90594. if( pInfo ){
  90595. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  90596. pInfo->nField = (u16)nExpr;
  90597. pInfo->enc = ENC(db);
  90598. pInfo->db = db;
  90599. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  90600. CollSeq *pColl;
  90601. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  90602. if( !pColl ){
  90603. pColl = db->pDfltColl;
  90604. }
  90605. pInfo->aColl[i] = pColl;
  90606. pInfo->aSortOrder[i] = pItem->sortOrder;
  90607. }
  90608. }
  90609. return pInfo;
  90610. }
  90611. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  90612. /*
  90613. ** Name of the connection operator, used for error messages.
  90614. */
  90615. static const char *selectOpName(int id){
  90616. char *z;
  90617. switch( id ){
  90618. case TK_ALL: z = "UNION ALL"; break;
  90619. case TK_INTERSECT: z = "INTERSECT"; break;
  90620. case TK_EXCEPT: z = "EXCEPT"; break;
  90621. default: z = "UNION"; break;
  90622. }
  90623. return z;
  90624. }
  90625. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  90626. #ifndef SQLITE_OMIT_EXPLAIN
  90627. /*
  90628. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  90629. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  90630. ** where the caption is of the form:
  90631. **
  90632. ** "USE TEMP B-TREE FOR xxx"
  90633. **
  90634. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  90635. ** is determined by the zUsage argument.
  90636. */
  90637. static void explainTempTable(Parse *pParse, const char *zUsage){
  90638. if( pParse->explain==2 ){
  90639. Vdbe *v = pParse->pVdbe;
  90640. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  90641. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  90642. }
  90643. }
  90644. /*
  90645. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  90646. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  90647. ** in sqlite3Select() to assign values to structure member variables that
  90648. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  90649. ** code with #ifndef directives.
  90650. */
  90651. # define explainSetInteger(a, b) a = b
  90652. #else
  90653. /* No-op versions of the explainXXX() functions and macros. */
  90654. # define explainTempTable(y,z)
  90655. # define explainSetInteger(y,z)
  90656. #endif
  90657. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  90658. /*
  90659. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  90660. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  90661. ** where the caption is of one of the two forms:
  90662. **
  90663. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  90664. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  90665. **
  90666. ** where iSub1 and iSub2 are the integers passed as the corresponding
  90667. ** function parameters, and op is the text representation of the parameter
  90668. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  90669. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  90670. ** false, or the second form if it is true.
  90671. */
  90672. static void explainComposite(
  90673. Parse *pParse, /* Parse context */
  90674. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  90675. int iSub1, /* Subquery id 1 */
  90676. int iSub2, /* Subquery id 2 */
  90677. int bUseTmp /* True if a temp table was used */
  90678. ){
  90679. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  90680. if( pParse->explain==2 ){
  90681. Vdbe *v = pParse->pVdbe;
  90682. char *zMsg = sqlite3MPrintf(
  90683. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  90684. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  90685. );
  90686. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  90687. }
  90688. }
  90689. #else
  90690. /* No-op versions of the explainXXX() functions and macros. */
  90691. # define explainComposite(v,w,x,y,z)
  90692. #endif
  90693. /*
  90694. ** If the inner loop was generated using a non-null pOrderBy argument,
  90695. ** then the results were placed in a sorter. After the loop is terminated
  90696. ** we need to run the sorter and output the results. The following
  90697. ** routine generates the code needed to do that.
  90698. */
  90699. static void generateSortTail(
  90700. Parse *pParse, /* Parsing context */
  90701. Select *p, /* The SELECT statement */
  90702. Vdbe *v, /* Generate code into this VDBE */
  90703. int nColumn, /* Number of columns of data */
  90704. SelectDest *pDest /* Write the sorted results here */
  90705. ){
  90706. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  90707. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  90708. int addr;
  90709. int iTab;
  90710. int pseudoTab = 0;
  90711. ExprList *pOrderBy = p->pOrderBy;
  90712. int eDest = pDest->eDest;
  90713. int iParm = pDest->iSDParm;
  90714. int regRow;
  90715. int regRowid;
  90716. iTab = pOrderBy->iECursor;
  90717. regRow = sqlite3GetTempReg(pParse);
  90718. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  90719. pseudoTab = pParse->nTab++;
  90720. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  90721. regRowid = 0;
  90722. }else{
  90723. regRowid = sqlite3GetTempReg(pParse);
  90724. }
  90725. if( p->selFlags & SF_UseSorter ){
  90726. int regSortOut = ++pParse->nMem;
  90727. int ptab2 = pParse->nTab++;
  90728. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  90729. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  90730. codeOffset(v, p, addrContinue);
  90731. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  90732. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  90733. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  90734. }else{
  90735. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  90736. codeOffset(v, p, addrContinue);
  90737. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  90738. }
  90739. switch( eDest ){
  90740. case SRT_Table:
  90741. case SRT_EphemTab: {
  90742. testcase( eDest==SRT_Table );
  90743. testcase( eDest==SRT_EphemTab );
  90744. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  90745. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  90746. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  90747. break;
  90748. }
  90749. #ifndef SQLITE_OMIT_SUBQUERY
  90750. case SRT_Set: {
  90751. assert( nColumn==1 );
  90752. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  90753. &pDest->affSdst, 1);
  90754. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  90755. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  90756. break;
  90757. }
  90758. case SRT_Mem: {
  90759. assert( nColumn==1 );
  90760. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  90761. /* The LIMIT clause will terminate the loop for us */
  90762. break;
  90763. }
  90764. #endif
  90765. default: {
  90766. int i;
  90767. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  90768. testcase( eDest==SRT_Output );
  90769. testcase( eDest==SRT_Coroutine );
  90770. for(i=0; i<nColumn; i++){
  90771. assert( regRow!=pDest->iSdst+i );
  90772. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  90773. if( i==0 ){
  90774. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  90775. }
  90776. }
  90777. if( eDest==SRT_Output ){
  90778. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  90779. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  90780. }else{
  90781. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  90782. }
  90783. break;
  90784. }
  90785. }
  90786. sqlite3ReleaseTempReg(pParse, regRow);
  90787. sqlite3ReleaseTempReg(pParse, regRowid);
  90788. /* The bottom of the loop
  90789. */
  90790. sqlite3VdbeResolveLabel(v, addrContinue);
  90791. if( p->selFlags & SF_UseSorter ){
  90792. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  90793. }else{
  90794. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  90795. }
  90796. sqlite3VdbeResolveLabel(v, addrBreak);
  90797. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  90798. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  90799. }
  90800. }
  90801. /*
  90802. ** Return a pointer to a string containing the 'declaration type' of the
  90803. ** expression pExpr. The string may be treated as static by the caller.
  90804. **
  90805. ** The declaration type is the exact datatype definition extracted from the
  90806. ** original CREATE TABLE statement if the expression is a column. The
  90807. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  90808. ** is considered a column can be complex in the presence of subqueries. The
  90809. ** result-set expression in all of the following SELECT statements is
  90810. ** considered a column by this function.
  90811. **
  90812. ** SELECT col FROM tbl;
  90813. ** SELECT (SELECT col FROM tbl;
  90814. ** SELECT (SELECT col FROM tbl);
  90815. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  90816. **
  90817. ** The declaration type for any expression other than a column is NULL.
  90818. */
  90819. static const char *columnType(
  90820. NameContext *pNC,
  90821. Expr *pExpr,
  90822. const char **pzOriginDb,
  90823. const char **pzOriginTab,
  90824. const char **pzOriginCol
  90825. ){
  90826. char const *zType = 0;
  90827. char const *zOriginDb = 0;
  90828. char const *zOriginTab = 0;
  90829. char const *zOriginCol = 0;
  90830. int j;
  90831. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  90832. switch( pExpr->op ){
  90833. case TK_AGG_COLUMN:
  90834. case TK_COLUMN: {
  90835. /* The expression is a column. Locate the table the column is being
  90836. ** extracted from in NameContext.pSrcList. This table may be real
  90837. ** database table or a subquery.
  90838. */
  90839. Table *pTab = 0; /* Table structure column is extracted from */
  90840. Select *pS = 0; /* Select the column is extracted from */
  90841. int iCol = pExpr->iColumn; /* Index of column in pTab */
  90842. testcase( pExpr->op==TK_AGG_COLUMN );
  90843. testcase( pExpr->op==TK_COLUMN );
  90844. while( pNC && !pTab ){
  90845. SrcList *pTabList = pNC->pSrcList;
  90846. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  90847. if( j<pTabList->nSrc ){
  90848. pTab = pTabList->a[j].pTab;
  90849. pS = pTabList->a[j].pSelect;
  90850. }else{
  90851. pNC = pNC->pNext;
  90852. }
  90853. }
  90854. if( pTab==0 ){
  90855. /* At one time, code such as "SELECT new.x" within a trigger would
  90856. ** cause this condition to run. Since then, we have restructured how
  90857. ** trigger code is generated and so this condition is no longer
  90858. ** possible. However, it can still be true for statements like
  90859. ** the following:
  90860. **
  90861. ** CREATE TABLE t1(col INTEGER);
  90862. ** SELECT (SELECT t1.col) FROM FROM t1;
  90863. **
  90864. ** when columnType() is called on the expression "t1.col" in the
  90865. ** sub-select. In this case, set the column type to NULL, even
  90866. ** though it should really be "INTEGER".
  90867. **
  90868. ** This is not a problem, as the column type of "t1.col" is never
  90869. ** used. When columnType() is called on the expression
  90870. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  90871. ** branch below. */
  90872. break;
  90873. }
  90874. assert( pTab && pExpr->pTab==pTab );
  90875. if( pS ){
  90876. /* The "table" is actually a sub-select or a view in the FROM clause
  90877. ** of the SELECT statement. Return the declaration type and origin
  90878. ** data for the result-set column of the sub-select.
  90879. */
  90880. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  90881. /* If iCol is less than zero, then the expression requests the
  90882. ** rowid of the sub-select or view. This expression is legal (see
  90883. ** test case misc2.2.2) - it always evaluates to NULL.
  90884. */
  90885. NameContext sNC;
  90886. Expr *p = pS->pEList->a[iCol].pExpr;
  90887. sNC.pSrcList = pS->pSrc;
  90888. sNC.pNext = pNC;
  90889. sNC.pParse = pNC->pParse;
  90890. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  90891. }
  90892. }else if( ALWAYS(pTab->pSchema) ){
  90893. /* A real table */
  90894. assert( !pS );
  90895. if( iCol<0 ) iCol = pTab->iPKey;
  90896. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  90897. if( iCol<0 ){
  90898. zType = "INTEGER";
  90899. zOriginCol = "rowid";
  90900. }else{
  90901. zType = pTab->aCol[iCol].zType;
  90902. zOriginCol = pTab->aCol[iCol].zName;
  90903. }
  90904. zOriginTab = pTab->zName;
  90905. if( pNC->pParse ){
  90906. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  90907. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  90908. }
  90909. }
  90910. break;
  90911. }
  90912. #ifndef SQLITE_OMIT_SUBQUERY
  90913. case TK_SELECT: {
  90914. /* The expression is a sub-select. Return the declaration type and
  90915. ** origin info for the single column in the result set of the SELECT
  90916. ** statement.
  90917. */
  90918. NameContext sNC;
  90919. Select *pS = pExpr->x.pSelect;
  90920. Expr *p = pS->pEList->a[0].pExpr;
  90921. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  90922. sNC.pSrcList = pS->pSrc;
  90923. sNC.pNext = pNC;
  90924. sNC.pParse = pNC->pParse;
  90925. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  90926. break;
  90927. }
  90928. #endif
  90929. }
  90930. if( pzOriginDb ){
  90931. assert( pzOriginTab && pzOriginCol );
  90932. *pzOriginDb = zOriginDb;
  90933. *pzOriginTab = zOriginTab;
  90934. *pzOriginCol = zOriginCol;
  90935. }
  90936. return zType;
  90937. }
  90938. /*
  90939. ** Generate code that will tell the VDBE the declaration types of columns
  90940. ** in the result set.
  90941. */
  90942. static void generateColumnTypes(
  90943. Parse *pParse, /* Parser context */
  90944. SrcList *pTabList, /* List of tables */
  90945. ExprList *pEList /* Expressions defining the result set */
  90946. ){
  90947. #ifndef SQLITE_OMIT_DECLTYPE
  90948. Vdbe *v = pParse->pVdbe;
  90949. int i;
  90950. NameContext sNC;
  90951. sNC.pSrcList = pTabList;
  90952. sNC.pParse = pParse;
  90953. for(i=0; i<pEList->nExpr; i++){
  90954. Expr *p = pEList->a[i].pExpr;
  90955. const char *zType;
  90956. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  90957. const char *zOrigDb = 0;
  90958. const char *zOrigTab = 0;
  90959. const char *zOrigCol = 0;
  90960. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  90961. /* The vdbe must make its own copy of the column-type and other
  90962. ** column specific strings, in case the schema is reset before this
  90963. ** virtual machine is deleted.
  90964. */
  90965. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  90966. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  90967. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  90968. #else
  90969. zType = columnType(&sNC, p, 0, 0, 0);
  90970. #endif
  90971. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  90972. }
  90973. #endif /* SQLITE_OMIT_DECLTYPE */
  90974. }
  90975. /*
  90976. ** Generate code that will tell the VDBE the names of columns
  90977. ** in the result set. This information is used to provide the
  90978. ** azCol[] values in the callback.
  90979. */
  90980. static void generateColumnNames(
  90981. Parse *pParse, /* Parser context */
  90982. SrcList *pTabList, /* List of tables */
  90983. ExprList *pEList /* Expressions defining the result set */
  90984. ){
  90985. Vdbe *v = pParse->pVdbe;
  90986. int i, j;
  90987. sqlite3 *db = pParse->db;
  90988. int fullNames, shortNames;
  90989. #ifndef SQLITE_OMIT_EXPLAIN
  90990. /* If this is an EXPLAIN, skip this step */
  90991. if( pParse->explain ){
  90992. return;
  90993. }
  90994. #endif
  90995. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  90996. pParse->colNamesSet = 1;
  90997. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  90998. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  90999. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  91000. for(i=0; i<pEList->nExpr; i++){
  91001. Expr *p;
  91002. p = pEList->a[i].pExpr;
  91003. if( NEVER(p==0) ) continue;
  91004. if( pEList->a[i].zName ){
  91005. char *zName = pEList->a[i].zName;
  91006. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  91007. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  91008. Table *pTab;
  91009. char *zCol;
  91010. int iCol = p->iColumn;
  91011. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  91012. if( pTabList->a[j].iCursor==p->iTable ) break;
  91013. }
  91014. assert( j<pTabList->nSrc );
  91015. pTab = pTabList->a[j].pTab;
  91016. if( iCol<0 ) iCol = pTab->iPKey;
  91017. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  91018. if( iCol<0 ){
  91019. zCol = "rowid";
  91020. }else{
  91021. zCol = pTab->aCol[iCol].zName;
  91022. }
  91023. if( !shortNames && !fullNames ){
  91024. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  91025. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  91026. }else if( fullNames ){
  91027. char *zName = 0;
  91028. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  91029. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  91030. }else{
  91031. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  91032. }
  91033. }else{
  91034. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  91035. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  91036. }
  91037. }
  91038. generateColumnTypes(pParse, pTabList, pEList);
  91039. }
  91040. /*
  91041. ** Given a an expression list (which is really the list of expressions
  91042. ** that form the result set of a SELECT statement) compute appropriate
  91043. ** column names for a table that would hold the expression list.
  91044. **
  91045. ** All column names will be unique.
  91046. **
  91047. ** Only the column names are computed. Column.zType, Column.zColl,
  91048. ** and other fields of Column are zeroed.
  91049. **
  91050. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  91051. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  91052. */
  91053. static int selectColumnsFromExprList(
  91054. Parse *pParse, /* Parsing context */
  91055. ExprList *pEList, /* Expr list from which to derive column names */
  91056. i16 *pnCol, /* Write the number of columns here */
  91057. Column **paCol /* Write the new column list here */
  91058. ){
  91059. sqlite3 *db = pParse->db; /* Database connection */
  91060. int i, j; /* Loop counters */
  91061. int cnt; /* Index added to make the name unique */
  91062. Column *aCol, *pCol; /* For looping over result columns */
  91063. int nCol; /* Number of columns in the result set */
  91064. Expr *p; /* Expression for a single result column */
  91065. char *zName; /* Column name */
  91066. int nName; /* Size of name in zName[] */
  91067. if( pEList ){
  91068. nCol = pEList->nExpr;
  91069. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  91070. testcase( aCol==0 );
  91071. }else{
  91072. nCol = 0;
  91073. aCol = 0;
  91074. }
  91075. *pnCol = nCol;
  91076. *paCol = aCol;
  91077. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  91078. /* Get an appropriate name for the column
  91079. */
  91080. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  91081. if( (zName = pEList->a[i].zName)!=0 ){
  91082. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  91083. zName = sqlite3DbStrDup(db, zName);
  91084. }else{
  91085. Expr *pColExpr = p; /* The expression that is the result column name */
  91086. Table *pTab; /* Table associated with this expression */
  91087. while( pColExpr->op==TK_DOT ){
  91088. pColExpr = pColExpr->pRight;
  91089. assert( pColExpr!=0 );
  91090. }
  91091. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  91092. /* For columns use the column name name */
  91093. int iCol = pColExpr->iColumn;
  91094. pTab = pColExpr->pTab;
  91095. if( iCol<0 ) iCol = pTab->iPKey;
  91096. zName = sqlite3MPrintf(db, "%s",
  91097. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  91098. }else if( pColExpr->op==TK_ID ){
  91099. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  91100. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  91101. }else{
  91102. /* Use the original text of the column expression as its name */
  91103. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  91104. }
  91105. }
  91106. if( db->mallocFailed ){
  91107. sqlite3DbFree(db, zName);
  91108. break;
  91109. }
  91110. /* Make sure the column name is unique. If the name is not unique,
  91111. ** append a integer to the name so that it becomes unique.
  91112. */
  91113. nName = sqlite3Strlen30(zName);
  91114. for(j=cnt=0; j<i; j++){
  91115. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  91116. char *zNewName;
  91117. int k;
  91118. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  91119. if( zName[k]==':' ) nName = k;
  91120. zName[nName] = 0;
  91121. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  91122. sqlite3DbFree(db, zName);
  91123. zName = zNewName;
  91124. j = -1;
  91125. if( zName==0 ) break;
  91126. }
  91127. }
  91128. pCol->zName = zName;
  91129. }
  91130. if( db->mallocFailed ){
  91131. for(j=0; j<i; j++){
  91132. sqlite3DbFree(db, aCol[j].zName);
  91133. }
  91134. sqlite3DbFree(db, aCol);
  91135. *paCol = 0;
  91136. *pnCol = 0;
  91137. return SQLITE_NOMEM;
  91138. }
  91139. return SQLITE_OK;
  91140. }
  91141. /*
  91142. ** Add type and collation information to a column list based on
  91143. ** a SELECT statement.
  91144. **
  91145. ** The column list presumably came from selectColumnNamesFromExprList().
  91146. ** The column list has only names, not types or collations. This
  91147. ** routine goes through and adds the types and collations.
  91148. **
  91149. ** This routine requires that all identifiers in the SELECT
  91150. ** statement be resolved.
  91151. */
  91152. static void selectAddColumnTypeAndCollation(
  91153. Parse *pParse, /* Parsing contexts */
  91154. int nCol, /* Number of columns */
  91155. Column *aCol, /* List of columns */
  91156. Select *pSelect /* SELECT used to determine types and collations */
  91157. ){
  91158. sqlite3 *db = pParse->db;
  91159. NameContext sNC;
  91160. Column *pCol;
  91161. CollSeq *pColl;
  91162. int i;
  91163. Expr *p;
  91164. struct ExprList_item *a;
  91165. assert( pSelect!=0 );
  91166. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  91167. assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  91168. if( db->mallocFailed ) return;
  91169. memset(&sNC, 0, sizeof(sNC));
  91170. sNC.pSrcList = pSelect->pSrc;
  91171. a = pSelect->pEList->a;
  91172. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  91173. p = a[i].pExpr;
  91174. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  91175. pCol->affinity = sqlite3ExprAffinity(p);
  91176. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  91177. pColl = sqlite3ExprCollSeq(pParse, p);
  91178. if( pColl ){
  91179. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  91180. }
  91181. }
  91182. }
  91183. /*
  91184. ** Given a SELECT statement, generate a Table structure that describes
  91185. ** the result set of that SELECT.
  91186. */
  91187. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  91188. Table *pTab;
  91189. sqlite3 *db = pParse->db;
  91190. int savedFlags;
  91191. savedFlags = db->flags;
  91192. db->flags &= ~SQLITE_FullColNames;
  91193. db->flags |= SQLITE_ShortColNames;
  91194. sqlite3SelectPrep(pParse, pSelect, 0);
  91195. if( pParse->nErr ) return 0;
  91196. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  91197. db->flags = savedFlags;
  91198. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  91199. if( pTab==0 ){
  91200. return 0;
  91201. }
  91202. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  91203. ** is disabled */
  91204. assert( db->lookaside.bEnabled==0 );
  91205. pTab->nRef = 1;
  91206. pTab->zName = 0;
  91207. pTab->nRowEst = 1000000;
  91208. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  91209. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  91210. pTab->iPKey = -1;
  91211. if( db->mallocFailed ){
  91212. sqlite3DeleteTable(db, pTab);
  91213. return 0;
  91214. }
  91215. return pTab;
  91216. }
  91217. /*
  91218. ** Get a VDBE for the given parser context. Create a new one if necessary.
  91219. ** If an error occurs, return NULL and leave a message in pParse.
  91220. */
  91221. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  91222. Vdbe *v = pParse->pVdbe;
  91223. if( v==0 ){
  91224. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  91225. #ifndef SQLITE_OMIT_TRACE
  91226. if( v ){
  91227. sqlite3VdbeAddOp0(v, OP_Trace);
  91228. }
  91229. #endif
  91230. }
  91231. return v;
  91232. }
  91233. /*
  91234. ** Compute the iLimit and iOffset fields of the SELECT based on the
  91235. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  91236. ** that appear in the original SQL statement after the LIMIT and OFFSET
  91237. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  91238. ** are the integer memory register numbers for counters used to compute
  91239. ** the limit and offset. If there is no limit and/or offset, then
  91240. ** iLimit and iOffset are negative.
  91241. **
  91242. ** This routine changes the values of iLimit and iOffset only if
  91243. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  91244. ** iOffset should have been preset to appropriate default values
  91245. ** (usually but not always -1) prior to calling this routine.
  91246. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  91247. ** redefined. The UNION ALL operator uses this property to force
  91248. ** the reuse of the same limit and offset registers across multiple
  91249. ** SELECT statements.
  91250. */
  91251. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  91252. Vdbe *v = 0;
  91253. int iLimit = 0;
  91254. int iOffset;
  91255. int addr1, n;
  91256. if( p->iLimit ) return;
  91257. /*
  91258. ** "LIMIT -1" always shows all rows. There is some
  91259. ** contraversy about what the correct behavior should be.
  91260. ** The current implementation interprets "LIMIT 0" to mean
  91261. ** no rows.
  91262. */
  91263. sqlite3ExprCacheClear(pParse);
  91264. assert( p->pOffset==0 || p->pLimit!=0 );
  91265. if( p->pLimit ){
  91266. p->iLimit = iLimit = ++pParse->nMem;
  91267. v = sqlite3GetVdbe(pParse);
  91268. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  91269. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  91270. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  91271. VdbeComment((v, "LIMIT counter"));
  91272. if( n==0 ){
  91273. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  91274. }else{
  91275. if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
  91276. }
  91277. }else{
  91278. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  91279. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  91280. VdbeComment((v, "LIMIT counter"));
  91281. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  91282. }
  91283. if( p->pOffset ){
  91284. p->iOffset = iOffset = ++pParse->nMem;
  91285. pParse->nMem++; /* Allocate an extra register for limit+offset */
  91286. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  91287. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  91288. VdbeComment((v, "OFFSET counter"));
  91289. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  91290. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  91291. sqlite3VdbeJumpHere(v, addr1);
  91292. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  91293. VdbeComment((v, "LIMIT+OFFSET"));
  91294. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  91295. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  91296. sqlite3VdbeJumpHere(v, addr1);
  91297. }
  91298. }
  91299. }
  91300. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  91301. /*
  91302. ** Return the appropriate collating sequence for the iCol-th column of
  91303. ** the result set for the compound-select statement "p". Return NULL if
  91304. ** the column has no default collating sequence.
  91305. **
  91306. ** The collating sequence for the compound select is taken from the
  91307. ** left-most term of the select that has a collating sequence.
  91308. */
  91309. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  91310. CollSeq *pRet;
  91311. if( p->pPrior ){
  91312. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  91313. }else{
  91314. pRet = 0;
  91315. }
  91316. assert( iCol>=0 );
  91317. if( pRet==0 && iCol<p->pEList->nExpr ){
  91318. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  91319. }
  91320. return pRet;
  91321. }
  91322. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  91323. /* Forward reference */
  91324. static int multiSelectOrderBy(
  91325. Parse *pParse, /* Parsing context */
  91326. Select *p, /* The right-most of SELECTs to be coded */
  91327. SelectDest *pDest /* What to do with query results */
  91328. );
  91329. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  91330. /*
  91331. ** This routine is called to process a compound query form from
  91332. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  91333. ** INTERSECT
  91334. **
  91335. ** "p" points to the right-most of the two queries. the query on the
  91336. ** left is p->pPrior. The left query could also be a compound query
  91337. ** in which case this routine will be called recursively.
  91338. **
  91339. ** The results of the total query are to be written into a destination
  91340. ** of type eDest with parameter iParm.
  91341. **
  91342. ** Example 1: Consider a three-way compound SQL statement.
  91343. **
  91344. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  91345. **
  91346. ** This statement is parsed up as follows:
  91347. **
  91348. ** SELECT c FROM t3
  91349. ** |
  91350. ** `-----> SELECT b FROM t2
  91351. ** |
  91352. ** `------> SELECT a FROM t1
  91353. **
  91354. ** The arrows in the diagram above represent the Select.pPrior pointer.
  91355. ** So if this routine is called with p equal to the t3 query, then
  91356. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  91357. **
  91358. ** Notice that because of the way SQLite parses compound SELECTs, the
  91359. ** individual selects always group from left to right.
  91360. */
  91361. static int multiSelect(
  91362. Parse *pParse, /* Parsing context */
  91363. Select *p, /* The right-most of SELECTs to be coded */
  91364. SelectDest *pDest /* What to do with query results */
  91365. ){
  91366. int rc = SQLITE_OK; /* Success code from a subroutine */
  91367. Select *pPrior; /* Another SELECT immediately to our left */
  91368. Vdbe *v; /* Generate code to this VDBE */
  91369. SelectDest dest; /* Alternative data destination */
  91370. Select *pDelete = 0; /* Chain of simple selects to delete */
  91371. sqlite3 *db; /* Database connection */
  91372. #ifndef SQLITE_OMIT_EXPLAIN
  91373. int iSub1; /* EQP id of left-hand query */
  91374. int iSub2; /* EQP id of right-hand query */
  91375. #endif
  91376. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  91377. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  91378. */
  91379. assert( p && p->pPrior ); /* Calling function guarantees this much */
  91380. db = pParse->db;
  91381. pPrior = p->pPrior;
  91382. assert( pPrior->pRightmost!=pPrior );
  91383. assert( pPrior->pRightmost==p->pRightmost );
  91384. dest = *pDest;
  91385. if( pPrior->pOrderBy ){
  91386. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  91387. selectOpName(p->op));
  91388. rc = 1;
  91389. goto multi_select_end;
  91390. }
  91391. if( pPrior->pLimit ){
  91392. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  91393. selectOpName(p->op));
  91394. rc = 1;
  91395. goto multi_select_end;
  91396. }
  91397. v = sqlite3GetVdbe(pParse);
  91398. assert( v!=0 ); /* The VDBE already created by calling function */
  91399. /* Create the destination temporary table if necessary
  91400. */
  91401. if( dest.eDest==SRT_EphemTab ){
  91402. assert( p->pEList );
  91403. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  91404. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  91405. dest.eDest = SRT_Table;
  91406. }
  91407. /* Make sure all SELECTs in the statement have the same number of elements
  91408. ** in their result sets.
  91409. */
  91410. assert( p->pEList && pPrior->pEList );
  91411. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  91412. if( p->selFlags & SF_Values ){
  91413. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  91414. }else{
  91415. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  91416. " do not have the same number of result columns", selectOpName(p->op));
  91417. }
  91418. rc = 1;
  91419. goto multi_select_end;
  91420. }
  91421. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  91422. */
  91423. if( p->pOrderBy ){
  91424. return multiSelectOrderBy(pParse, p, pDest);
  91425. }
  91426. /* Generate code for the left and right SELECT statements.
  91427. */
  91428. switch( p->op ){
  91429. case TK_ALL: {
  91430. int addr = 0;
  91431. int nLimit;
  91432. assert( !pPrior->pLimit );
  91433. pPrior->iLimit = p->iLimit;
  91434. pPrior->iOffset = p->iOffset;
  91435. pPrior->pLimit = p->pLimit;
  91436. pPrior->pOffset = p->pOffset;
  91437. explainSetInteger(iSub1, pParse->iNextSelectId);
  91438. rc = sqlite3Select(pParse, pPrior, &dest);
  91439. p->pLimit = 0;
  91440. p->pOffset = 0;
  91441. if( rc ){
  91442. goto multi_select_end;
  91443. }
  91444. p->pPrior = 0;
  91445. p->iLimit = pPrior->iLimit;
  91446. p->iOffset = pPrior->iOffset;
  91447. if( p->iLimit ){
  91448. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  91449. VdbeComment((v, "Jump ahead if LIMIT reached"));
  91450. }
  91451. explainSetInteger(iSub2, pParse->iNextSelectId);
  91452. rc = sqlite3Select(pParse, p, &dest);
  91453. testcase( rc!=SQLITE_OK );
  91454. pDelete = p->pPrior;
  91455. p->pPrior = pPrior;
  91456. p->nSelectRow += pPrior->nSelectRow;
  91457. if( pPrior->pLimit
  91458. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  91459. && p->nSelectRow > (double)nLimit
  91460. ){
  91461. p->nSelectRow = (double)nLimit;
  91462. }
  91463. if( addr ){
  91464. sqlite3VdbeJumpHere(v, addr);
  91465. }
  91466. break;
  91467. }
  91468. case TK_EXCEPT:
  91469. case TK_UNION: {
  91470. int unionTab; /* Cursor number of the temporary table holding result */
  91471. u8 op = 0; /* One of the SRT_ operations to apply to self */
  91472. int priorOp; /* The SRT_ operation to apply to prior selects */
  91473. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  91474. int addr;
  91475. SelectDest uniondest;
  91476. testcase( p->op==TK_EXCEPT );
  91477. testcase( p->op==TK_UNION );
  91478. priorOp = SRT_Union;
  91479. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  91480. /* We can reuse a temporary table generated by a SELECT to our
  91481. ** right.
  91482. */
  91483. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  91484. ** of a 3-way or more compound */
  91485. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  91486. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  91487. unionTab = dest.iSDParm;
  91488. }else{
  91489. /* We will need to create our own temporary table to hold the
  91490. ** intermediate results.
  91491. */
  91492. unionTab = pParse->nTab++;
  91493. assert( p->pOrderBy==0 );
  91494. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  91495. assert( p->addrOpenEphm[0] == -1 );
  91496. p->addrOpenEphm[0] = addr;
  91497. p->pRightmost->selFlags |= SF_UsesEphemeral;
  91498. assert( p->pEList );
  91499. }
  91500. /* Code the SELECT statements to our left
  91501. */
  91502. assert( !pPrior->pOrderBy );
  91503. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  91504. explainSetInteger(iSub1, pParse->iNextSelectId);
  91505. rc = sqlite3Select(pParse, pPrior, &uniondest);
  91506. if( rc ){
  91507. goto multi_select_end;
  91508. }
  91509. /* Code the current SELECT statement
  91510. */
  91511. if( p->op==TK_EXCEPT ){
  91512. op = SRT_Except;
  91513. }else{
  91514. assert( p->op==TK_UNION );
  91515. op = SRT_Union;
  91516. }
  91517. p->pPrior = 0;
  91518. pLimit = p->pLimit;
  91519. p->pLimit = 0;
  91520. pOffset = p->pOffset;
  91521. p->pOffset = 0;
  91522. uniondest.eDest = op;
  91523. explainSetInteger(iSub2, pParse->iNextSelectId);
  91524. rc = sqlite3Select(pParse, p, &uniondest);
  91525. testcase( rc!=SQLITE_OK );
  91526. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  91527. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  91528. sqlite3ExprListDelete(db, p->pOrderBy);
  91529. pDelete = p->pPrior;
  91530. p->pPrior = pPrior;
  91531. p->pOrderBy = 0;
  91532. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  91533. sqlite3ExprDelete(db, p->pLimit);
  91534. p->pLimit = pLimit;
  91535. p->pOffset = pOffset;
  91536. p->iLimit = 0;
  91537. p->iOffset = 0;
  91538. /* Convert the data in the temporary table into whatever form
  91539. ** it is that we currently need.
  91540. */
  91541. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  91542. if( dest.eDest!=priorOp ){
  91543. int iCont, iBreak, iStart;
  91544. assert( p->pEList );
  91545. if( dest.eDest==SRT_Output ){
  91546. Select *pFirst = p;
  91547. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  91548. generateColumnNames(pParse, 0, pFirst->pEList);
  91549. }
  91550. iBreak = sqlite3VdbeMakeLabel(v);
  91551. iCont = sqlite3VdbeMakeLabel(v);
  91552. computeLimitRegisters(pParse, p, iBreak);
  91553. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  91554. iStart = sqlite3VdbeCurrentAddr(v);
  91555. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  91556. 0, 0, &dest, iCont, iBreak);
  91557. sqlite3VdbeResolveLabel(v, iCont);
  91558. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  91559. sqlite3VdbeResolveLabel(v, iBreak);
  91560. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  91561. }
  91562. break;
  91563. }
  91564. default: assert( p->op==TK_INTERSECT ); {
  91565. int tab1, tab2;
  91566. int iCont, iBreak, iStart;
  91567. Expr *pLimit, *pOffset;
  91568. int addr;
  91569. SelectDest intersectdest;
  91570. int r1;
  91571. /* INTERSECT is different from the others since it requires
  91572. ** two temporary tables. Hence it has its own case. Begin
  91573. ** by allocating the tables we will need.
  91574. */
  91575. tab1 = pParse->nTab++;
  91576. tab2 = pParse->nTab++;
  91577. assert( p->pOrderBy==0 );
  91578. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  91579. assert( p->addrOpenEphm[0] == -1 );
  91580. p->addrOpenEphm[0] = addr;
  91581. p->pRightmost->selFlags |= SF_UsesEphemeral;
  91582. assert( p->pEList );
  91583. /* Code the SELECTs to our left into temporary table "tab1".
  91584. */
  91585. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  91586. explainSetInteger(iSub1, pParse->iNextSelectId);
  91587. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  91588. if( rc ){
  91589. goto multi_select_end;
  91590. }
  91591. /* Code the current SELECT into temporary table "tab2"
  91592. */
  91593. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  91594. assert( p->addrOpenEphm[1] == -1 );
  91595. p->addrOpenEphm[1] = addr;
  91596. p->pPrior = 0;
  91597. pLimit = p->pLimit;
  91598. p->pLimit = 0;
  91599. pOffset = p->pOffset;
  91600. p->pOffset = 0;
  91601. intersectdest.iSDParm = tab2;
  91602. explainSetInteger(iSub2, pParse->iNextSelectId);
  91603. rc = sqlite3Select(pParse, p, &intersectdest);
  91604. testcase( rc!=SQLITE_OK );
  91605. pDelete = p->pPrior;
  91606. p->pPrior = pPrior;
  91607. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  91608. sqlite3ExprDelete(db, p->pLimit);
  91609. p->pLimit = pLimit;
  91610. p->pOffset = pOffset;
  91611. /* Generate code to take the intersection of the two temporary
  91612. ** tables.
  91613. */
  91614. assert( p->pEList );
  91615. if( dest.eDest==SRT_Output ){
  91616. Select *pFirst = p;
  91617. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  91618. generateColumnNames(pParse, 0, pFirst->pEList);
  91619. }
  91620. iBreak = sqlite3VdbeMakeLabel(v);
  91621. iCont = sqlite3VdbeMakeLabel(v);
  91622. computeLimitRegisters(pParse, p, iBreak);
  91623. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  91624. r1 = sqlite3GetTempReg(pParse);
  91625. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  91626. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  91627. sqlite3ReleaseTempReg(pParse, r1);
  91628. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  91629. 0, 0, &dest, iCont, iBreak);
  91630. sqlite3VdbeResolveLabel(v, iCont);
  91631. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  91632. sqlite3VdbeResolveLabel(v, iBreak);
  91633. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  91634. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  91635. break;
  91636. }
  91637. }
  91638. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  91639. /* Compute collating sequences used by
  91640. ** temporary tables needed to implement the compound select.
  91641. ** Attach the KeyInfo structure to all temporary tables.
  91642. **
  91643. ** This section is run by the right-most SELECT statement only.
  91644. ** SELECT statements to the left always skip this part. The right-most
  91645. ** SELECT might also skip this part if it has no ORDER BY clause and
  91646. ** no temp tables are required.
  91647. */
  91648. if( p->selFlags & SF_UsesEphemeral ){
  91649. int i; /* Loop counter */
  91650. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  91651. Select *pLoop; /* For looping through SELECT statements */
  91652. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  91653. int nCol; /* Number of columns in result set */
  91654. assert( p->pRightmost==p );
  91655. nCol = p->pEList->nExpr;
  91656. pKeyInfo = sqlite3DbMallocZero(db,
  91657. sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  91658. if( !pKeyInfo ){
  91659. rc = SQLITE_NOMEM;
  91660. goto multi_select_end;
  91661. }
  91662. pKeyInfo->enc = ENC(db);
  91663. pKeyInfo->nField = (u16)nCol;
  91664. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  91665. *apColl = multiSelectCollSeq(pParse, p, i);
  91666. if( 0==*apColl ){
  91667. *apColl = db->pDfltColl;
  91668. }
  91669. }
  91670. pKeyInfo->aSortOrder = (u8*)apColl;
  91671. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  91672. for(i=0; i<2; i++){
  91673. int addr = pLoop->addrOpenEphm[i];
  91674. if( addr<0 ){
  91675. /* If [0] is unused then [1] is also unused. So we can
  91676. ** always safely abort as soon as the first unused slot is found */
  91677. assert( pLoop->addrOpenEphm[1]<0 );
  91678. break;
  91679. }
  91680. sqlite3VdbeChangeP2(v, addr, nCol);
  91681. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  91682. pLoop->addrOpenEphm[i] = -1;
  91683. }
  91684. }
  91685. sqlite3DbFree(db, pKeyInfo);
  91686. }
  91687. multi_select_end:
  91688. pDest->iSdst = dest.iSdst;
  91689. pDest->nSdst = dest.nSdst;
  91690. sqlite3SelectDelete(db, pDelete);
  91691. return rc;
  91692. }
  91693. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  91694. /*
  91695. ** Code an output subroutine for a coroutine implementation of a
  91696. ** SELECT statment.
  91697. **
  91698. ** The data to be output is contained in pIn->iSdst. There are
  91699. ** pIn->nSdst columns to be output. pDest is where the output should
  91700. ** be sent.
  91701. **
  91702. ** regReturn is the number of the register holding the subroutine
  91703. ** return address.
  91704. **
  91705. ** If regPrev>0 then it is the first register in a vector that
  91706. ** records the previous output. mem[regPrev] is a flag that is false
  91707. ** if there has been no previous output. If regPrev>0 then code is
  91708. ** generated to suppress duplicates. pKeyInfo is used for comparing
  91709. ** keys.
  91710. **
  91711. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  91712. ** iBreak.
  91713. */
  91714. static int generateOutputSubroutine(
  91715. Parse *pParse, /* Parsing context */
  91716. Select *p, /* The SELECT statement */
  91717. SelectDest *pIn, /* Coroutine supplying data */
  91718. SelectDest *pDest, /* Where to send the data */
  91719. int regReturn, /* The return address register */
  91720. int regPrev, /* Previous result register. No uniqueness if 0 */
  91721. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  91722. int p4type, /* The p4 type for pKeyInfo */
  91723. int iBreak /* Jump here if we hit the LIMIT */
  91724. ){
  91725. Vdbe *v = pParse->pVdbe;
  91726. int iContinue;
  91727. int addr;
  91728. addr = sqlite3VdbeCurrentAddr(v);
  91729. iContinue = sqlite3VdbeMakeLabel(v);
  91730. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  91731. */
  91732. if( regPrev ){
  91733. int j1, j2;
  91734. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  91735. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  91736. (char*)pKeyInfo, p4type);
  91737. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  91738. sqlite3VdbeJumpHere(v, j1);
  91739. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  91740. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  91741. }
  91742. if( pParse->db->mallocFailed ) return 0;
  91743. /* Suppress the first OFFSET entries if there is an OFFSET clause
  91744. */
  91745. codeOffset(v, p, iContinue);
  91746. switch( pDest->eDest ){
  91747. /* Store the result as data using a unique key.
  91748. */
  91749. case SRT_Table:
  91750. case SRT_EphemTab: {
  91751. int r1 = sqlite3GetTempReg(pParse);
  91752. int r2 = sqlite3GetTempReg(pParse);
  91753. testcase( pDest->eDest==SRT_Table );
  91754. testcase( pDest->eDest==SRT_EphemTab );
  91755. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  91756. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  91757. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  91758. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91759. sqlite3ReleaseTempReg(pParse, r2);
  91760. sqlite3ReleaseTempReg(pParse, r1);
  91761. break;
  91762. }
  91763. #ifndef SQLITE_OMIT_SUBQUERY
  91764. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  91765. ** then there should be a single item on the stack. Write this
  91766. ** item into the set table with bogus data.
  91767. */
  91768. case SRT_Set: {
  91769. int r1;
  91770. assert( pIn->nSdst==1 );
  91771. pDest->affSdst =
  91772. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  91773. r1 = sqlite3GetTempReg(pParse);
  91774. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  91775. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  91776. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  91777. sqlite3ReleaseTempReg(pParse, r1);
  91778. break;
  91779. }
  91780. #if 0 /* Never occurs on an ORDER BY query */
  91781. /* If any row exist in the result set, record that fact and abort.
  91782. */
  91783. case SRT_Exists: {
  91784. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  91785. /* The LIMIT clause will terminate the loop for us */
  91786. break;
  91787. }
  91788. #endif
  91789. /* If this is a scalar select that is part of an expression, then
  91790. ** store the results in the appropriate memory cell and break out
  91791. ** of the scan loop.
  91792. */
  91793. case SRT_Mem: {
  91794. assert( pIn->nSdst==1 );
  91795. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  91796. /* The LIMIT clause will jump out of the loop for us */
  91797. break;
  91798. }
  91799. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  91800. /* The results are stored in a sequence of registers
  91801. ** starting at pDest->iSdst. Then the co-routine yields.
  91802. */
  91803. case SRT_Coroutine: {
  91804. if( pDest->iSdst==0 ){
  91805. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  91806. pDest->nSdst = pIn->nSdst;
  91807. }
  91808. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  91809. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  91810. break;
  91811. }
  91812. /* If none of the above, then the result destination must be
  91813. ** SRT_Output. This routine is never called with any other
  91814. ** destination other than the ones handled above or SRT_Output.
  91815. **
  91816. ** For SRT_Output, results are stored in a sequence of registers.
  91817. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  91818. ** return the next row of result.
  91819. */
  91820. default: {
  91821. assert( pDest->eDest==SRT_Output );
  91822. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  91823. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  91824. break;
  91825. }
  91826. }
  91827. /* Jump to the end of the loop if the LIMIT is reached.
  91828. */
  91829. if( p->iLimit ){
  91830. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  91831. }
  91832. /* Generate the subroutine return
  91833. */
  91834. sqlite3VdbeResolveLabel(v, iContinue);
  91835. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  91836. return addr;
  91837. }
  91838. /*
  91839. ** Alternative compound select code generator for cases when there
  91840. ** is an ORDER BY clause.
  91841. **
  91842. ** We assume a query of the following form:
  91843. **
  91844. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  91845. **
  91846. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  91847. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  91848. ** co-routines. Then run the co-routines in parallel and merge the results
  91849. ** into the output. In addition to the two coroutines (called selectA and
  91850. ** selectB) there are 7 subroutines:
  91851. **
  91852. ** outA: Move the output of the selectA coroutine into the output
  91853. ** of the compound query.
  91854. **
  91855. ** outB: Move the output of the selectB coroutine into the output
  91856. ** of the compound query. (Only generated for UNION and
  91857. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  91858. ** appears only in B.)
  91859. **
  91860. ** AltB: Called when there is data from both coroutines and A<B.
  91861. **
  91862. ** AeqB: Called when there is data from both coroutines and A==B.
  91863. **
  91864. ** AgtB: Called when there is data from both coroutines and A>B.
  91865. **
  91866. ** EofA: Called when data is exhausted from selectA.
  91867. **
  91868. ** EofB: Called when data is exhausted from selectB.
  91869. **
  91870. ** The implementation of the latter five subroutines depend on which
  91871. ** <operator> is used:
  91872. **
  91873. **
  91874. ** UNION ALL UNION EXCEPT INTERSECT
  91875. ** ------------- ----------------- -------------- -----------------
  91876. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  91877. **
  91878. ** AeqB: outA, nextA nextA nextA outA, nextA
  91879. **
  91880. ** AgtB: outB, nextB outB, nextB nextB nextB
  91881. **
  91882. ** EofA: outB, nextB outB, nextB halt halt
  91883. **
  91884. ** EofB: outA, nextA outA, nextA outA, nextA halt
  91885. **
  91886. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  91887. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  91888. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  91889. ** following nextX causes a jump to the end of the select processing.
  91890. **
  91891. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  91892. ** within the output subroutine. The regPrev register set holds the previously
  91893. ** output value. A comparison is made against this value and the output
  91894. ** is skipped if the next results would be the same as the previous.
  91895. **
  91896. ** The implementation plan is to implement the two coroutines and seven
  91897. ** subroutines first, then put the control logic at the bottom. Like this:
  91898. **
  91899. ** goto Init
  91900. ** coA: coroutine for left query (A)
  91901. ** coB: coroutine for right query (B)
  91902. ** outA: output one row of A
  91903. ** outB: output one row of B (UNION and UNION ALL only)
  91904. ** EofA: ...
  91905. ** EofB: ...
  91906. ** AltB: ...
  91907. ** AeqB: ...
  91908. ** AgtB: ...
  91909. ** Init: initialize coroutine registers
  91910. ** yield coA
  91911. ** if eof(A) goto EofA
  91912. ** yield coB
  91913. ** if eof(B) goto EofB
  91914. ** Cmpr: Compare A, B
  91915. ** Jump AltB, AeqB, AgtB
  91916. ** End: ...
  91917. **
  91918. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  91919. ** actually called using Gosub and they do not Return. EofA and EofB loop
  91920. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  91921. ** and AgtB jump to either L2 or to one of EofA or EofB.
  91922. */
  91923. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  91924. static int multiSelectOrderBy(
  91925. Parse *pParse, /* Parsing context */
  91926. Select *p, /* The right-most of SELECTs to be coded */
  91927. SelectDest *pDest /* What to do with query results */
  91928. ){
  91929. int i, j; /* Loop counters */
  91930. Select *pPrior; /* Another SELECT immediately to our left */
  91931. Vdbe *v; /* Generate code to this VDBE */
  91932. SelectDest destA; /* Destination for coroutine A */
  91933. SelectDest destB; /* Destination for coroutine B */
  91934. int regAddrA; /* Address register for select-A coroutine */
  91935. int regEofA; /* Flag to indicate when select-A is complete */
  91936. int regAddrB; /* Address register for select-B coroutine */
  91937. int regEofB; /* Flag to indicate when select-B is complete */
  91938. int addrSelectA; /* Address of the select-A coroutine */
  91939. int addrSelectB; /* Address of the select-B coroutine */
  91940. int regOutA; /* Address register for the output-A subroutine */
  91941. int regOutB; /* Address register for the output-B subroutine */
  91942. int addrOutA; /* Address of the output-A subroutine */
  91943. int addrOutB = 0; /* Address of the output-B subroutine */
  91944. int addrEofA; /* Address of the select-A-exhausted subroutine */
  91945. int addrEofB; /* Address of the select-B-exhausted subroutine */
  91946. int addrAltB; /* Address of the A<B subroutine */
  91947. int addrAeqB; /* Address of the A==B subroutine */
  91948. int addrAgtB; /* Address of the A>B subroutine */
  91949. int regLimitA; /* Limit register for select-A */
  91950. int regLimitB; /* Limit register for select-A */
  91951. int regPrev; /* A range of registers to hold previous output */
  91952. int savedLimit; /* Saved value of p->iLimit */
  91953. int savedOffset; /* Saved value of p->iOffset */
  91954. int labelCmpr; /* Label for the start of the merge algorithm */
  91955. int labelEnd; /* Label for the end of the overall SELECT stmt */
  91956. int j1; /* Jump instructions that get retargetted */
  91957. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  91958. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  91959. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  91960. sqlite3 *db; /* Database connection */
  91961. ExprList *pOrderBy; /* The ORDER BY clause */
  91962. int nOrderBy; /* Number of terms in the ORDER BY clause */
  91963. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  91964. #ifndef SQLITE_OMIT_EXPLAIN
  91965. int iSub1; /* EQP id of left-hand query */
  91966. int iSub2; /* EQP id of right-hand query */
  91967. #endif
  91968. assert( p->pOrderBy!=0 );
  91969. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  91970. db = pParse->db;
  91971. v = pParse->pVdbe;
  91972. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  91973. labelEnd = sqlite3VdbeMakeLabel(v);
  91974. labelCmpr = sqlite3VdbeMakeLabel(v);
  91975. /* Patch up the ORDER BY clause
  91976. */
  91977. op = p->op;
  91978. pPrior = p->pPrior;
  91979. assert( pPrior->pOrderBy==0 );
  91980. pOrderBy = p->pOrderBy;
  91981. assert( pOrderBy );
  91982. nOrderBy = pOrderBy->nExpr;
  91983. /* For operators other than UNION ALL we have to make sure that
  91984. ** the ORDER BY clause covers every term of the result set. Add
  91985. ** terms to the ORDER BY clause as necessary.
  91986. */
  91987. if( op!=TK_ALL ){
  91988. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  91989. struct ExprList_item *pItem;
  91990. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  91991. assert( pItem->iOrderByCol>0 );
  91992. if( pItem->iOrderByCol==i ) break;
  91993. }
  91994. if( j==nOrderBy ){
  91995. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  91996. if( pNew==0 ) return SQLITE_NOMEM;
  91997. pNew->flags |= EP_IntValue;
  91998. pNew->u.iValue = i;
  91999. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  92000. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  92001. }
  92002. }
  92003. }
  92004. /* Compute the comparison permutation and keyinfo that is used with
  92005. ** the permutation used to determine if the next
  92006. ** row of results comes from selectA or selectB. Also add explicit
  92007. ** collations to the ORDER BY clause terms so that when the subqueries
  92008. ** to the right and the left are evaluated, they use the correct
  92009. ** collation.
  92010. */
  92011. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  92012. if( aPermute ){
  92013. struct ExprList_item *pItem;
  92014. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  92015. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  92016. aPermute[i] = pItem->iOrderByCol - 1;
  92017. }
  92018. pKeyMerge =
  92019. sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  92020. if( pKeyMerge ){
  92021. pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  92022. pKeyMerge->nField = (u16)nOrderBy;
  92023. pKeyMerge->enc = ENC(db);
  92024. for(i=0; i<nOrderBy; i++){
  92025. CollSeq *pColl;
  92026. Expr *pTerm = pOrderBy->a[i].pExpr;
  92027. if( pTerm->flags & EP_Collate ){
  92028. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  92029. }else{
  92030. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  92031. if( pColl==0 ) pColl = db->pDfltColl;
  92032. pOrderBy->a[i].pExpr =
  92033. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  92034. }
  92035. pKeyMerge->aColl[i] = pColl;
  92036. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  92037. }
  92038. }
  92039. }else{
  92040. pKeyMerge = 0;
  92041. }
  92042. /* Reattach the ORDER BY clause to the query.
  92043. */
  92044. p->pOrderBy = pOrderBy;
  92045. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  92046. /* Allocate a range of temporary registers and the KeyInfo needed
  92047. ** for the logic that removes duplicate result rows when the
  92048. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  92049. */
  92050. if( op==TK_ALL ){
  92051. regPrev = 0;
  92052. }else{
  92053. int nExpr = p->pEList->nExpr;
  92054. assert( nOrderBy>=nExpr || db->mallocFailed );
  92055. regPrev = pParse->nMem+1;
  92056. pParse->nMem += nExpr+1;
  92057. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  92058. pKeyDup = sqlite3DbMallocZero(db,
  92059. sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  92060. if( pKeyDup ){
  92061. pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  92062. pKeyDup->nField = (u16)nExpr;
  92063. pKeyDup->enc = ENC(db);
  92064. for(i=0; i<nExpr; i++){
  92065. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  92066. pKeyDup->aSortOrder[i] = 0;
  92067. }
  92068. }
  92069. }
  92070. /* Separate the left and the right query from one another
  92071. */
  92072. p->pPrior = 0;
  92073. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  92074. if( pPrior->pPrior==0 ){
  92075. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  92076. }
  92077. /* Compute the limit registers */
  92078. computeLimitRegisters(pParse, p, labelEnd);
  92079. if( p->iLimit && op==TK_ALL ){
  92080. regLimitA = ++pParse->nMem;
  92081. regLimitB = ++pParse->nMem;
  92082. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  92083. regLimitA);
  92084. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  92085. }else{
  92086. regLimitA = regLimitB = 0;
  92087. }
  92088. sqlite3ExprDelete(db, p->pLimit);
  92089. p->pLimit = 0;
  92090. sqlite3ExprDelete(db, p->pOffset);
  92091. p->pOffset = 0;
  92092. regAddrA = ++pParse->nMem;
  92093. regEofA = ++pParse->nMem;
  92094. regAddrB = ++pParse->nMem;
  92095. regEofB = ++pParse->nMem;
  92096. regOutA = ++pParse->nMem;
  92097. regOutB = ++pParse->nMem;
  92098. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  92099. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  92100. /* Jump past the various subroutines and coroutines to the main
  92101. ** merge loop
  92102. */
  92103. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  92104. addrSelectA = sqlite3VdbeCurrentAddr(v);
  92105. /* Generate a coroutine to evaluate the SELECT statement to the
  92106. ** left of the compound operator - the "A" select.
  92107. */
  92108. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  92109. pPrior->iLimit = regLimitA;
  92110. explainSetInteger(iSub1, pParse->iNextSelectId);
  92111. sqlite3Select(pParse, pPrior, &destA);
  92112. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  92113. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  92114. VdbeNoopComment((v, "End coroutine for left SELECT"));
  92115. /* Generate a coroutine to evaluate the SELECT statement on
  92116. ** the right - the "B" select
  92117. */
  92118. addrSelectB = sqlite3VdbeCurrentAddr(v);
  92119. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  92120. savedLimit = p->iLimit;
  92121. savedOffset = p->iOffset;
  92122. p->iLimit = regLimitB;
  92123. p->iOffset = 0;
  92124. explainSetInteger(iSub2, pParse->iNextSelectId);
  92125. sqlite3Select(pParse, p, &destB);
  92126. p->iLimit = savedLimit;
  92127. p->iOffset = savedOffset;
  92128. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  92129. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  92130. VdbeNoopComment((v, "End coroutine for right SELECT"));
  92131. /* Generate a subroutine that outputs the current row of the A
  92132. ** select as the next output row of the compound select.
  92133. */
  92134. VdbeNoopComment((v, "Output routine for A"));
  92135. addrOutA = generateOutputSubroutine(pParse,
  92136. p, &destA, pDest, regOutA,
  92137. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  92138. /* Generate a subroutine that outputs the current row of the B
  92139. ** select as the next output row of the compound select.
  92140. */
  92141. if( op==TK_ALL || op==TK_UNION ){
  92142. VdbeNoopComment((v, "Output routine for B"));
  92143. addrOutB = generateOutputSubroutine(pParse,
  92144. p, &destB, pDest, regOutB,
  92145. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  92146. }
  92147. /* Generate a subroutine to run when the results from select A
  92148. ** are exhausted and only data in select B remains.
  92149. */
  92150. VdbeNoopComment((v, "eof-A subroutine"));
  92151. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  92152. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  92153. }else{
  92154. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  92155. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  92156. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  92157. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  92158. p->nSelectRow += pPrior->nSelectRow;
  92159. }
  92160. /* Generate a subroutine to run when the results from select B
  92161. ** are exhausted and only data in select A remains.
  92162. */
  92163. if( op==TK_INTERSECT ){
  92164. addrEofB = addrEofA;
  92165. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  92166. }else{
  92167. VdbeNoopComment((v, "eof-B subroutine"));
  92168. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  92169. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  92170. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  92171. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  92172. }
  92173. /* Generate code to handle the case of A<B
  92174. */
  92175. VdbeNoopComment((v, "A-lt-B subroutine"));
  92176. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  92177. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  92178. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  92179. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  92180. /* Generate code to handle the case of A==B
  92181. */
  92182. if( op==TK_ALL ){
  92183. addrAeqB = addrAltB;
  92184. }else if( op==TK_INTERSECT ){
  92185. addrAeqB = addrAltB;
  92186. addrAltB++;
  92187. }else{
  92188. VdbeNoopComment((v, "A-eq-B subroutine"));
  92189. addrAeqB =
  92190. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  92191. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  92192. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  92193. }
  92194. /* Generate code to handle the case of A>B
  92195. */
  92196. VdbeNoopComment((v, "A-gt-B subroutine"));
  92197. addrAgtB = sqlite3VdbeCurrentAddr(v);
  92198. if( op==TK_ALL || op==TK_UNION ){
  92199. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  92200. }
  92201. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  92202. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  92203. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  92204. /* This code runs once to initialize everything.
  92205. */
  92206. sqlite3VdbeJumpHere(v, j1);
  92207. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  92208. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  92209. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  92210. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  92211. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  92212. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  92213. /* Implement the main merge loop
  92214. */
  92215. sqlite3VdbeResolveLabel(v, labelCmpr);
  92216. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  92217. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  92218. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  92219. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  92220. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  92221. /* Jump to the this point in order to terminate the query.
  92222. */
  92223. sqlite3VdbeResolveLabel(v, labelEnd);
  92224. /* Set the number of output columns
  92225. */
  92226. if( pDest->eDest==SRT_Output ){
  92227. Select *pFirst = pPrior;
  92228. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  92229. generateColumnNames(pParse, 0, pFirst->pEList);
  92230. }
  92231. /* Reassembly the compound query so that it will be freed correctly
  92232. ** by the calling function */
  92233. if( p->pPrior ){
  92234. sqlite3SelectDelete(db, p->pPrior);
  92235. }
  92236. p->pPrior = pPrior;
  92237. /*** TBD: Insert subroutine calls to close cursors on incomplete
  92238. **** subqueries ****/
  92239. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  92240. return SQLITE_OK;
  92241. }
  92242. #endif
  92243. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  92244. /* Forward Declarations */
  92245. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  92246. static void substSelect(sqlite3*, Select *, int, ExprList *);
  92247. /*
  92248. ** Scan through the expression pExpr. Replace every reference to
  92249. ** a column in table number iTable with a copy of the iColumn-th
  92250. ** entry in pEList. (But leave references to the ROWID column
  92251. ** unchanged.)
  92252. **
  92253. ** This routine is part of the flattening procedure. A subquery
  92254. ** whose result set is defined by pEList appears as entry in the
  92255. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  92256. ** FORM clause entry is iTable. This routine make the necessary
  92257. ** changes to pExpr so that it refers directly to the source table
  92258. ** of the subquery rather the result set of the subquery.
  92259. */
  92260. static Expr *substExpr(
  92261. sqlite3 *db, /* Report malloc errors to this connection */
  92262. Expr *pExpr, /* Expr in which substitution occurs */
  92263. int iTable, /* Table to be substituted */
  92264. ExprList *pEList /* Substitute expressions */
  92265. ){
  92266. if( pExpr==0 ) return 0;
  92267. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  92268. if( pExpr->iColumn<0 ){
  92269. pExpr->op = TK_NULL;
  92270. }else{
  92271. Expr *pNew;
  92272. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  92273. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  92274. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  92275. sqlite3ExprDelete(db, pExpr);
  92276. pExpr = pNew;
  92277. }
  92278. }else{
  92279. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  92280. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  92281. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  92282. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  92283. }else{
  92284. substExprList(db, pExpr->x.pList, iTable, pEList);
  92285. }
  92286. }
  92287. return pExpr;
  92288. }
  92289. static void substExprList(
  92290. sqlite3 *db, /* Report malloc errors here */
  92291. ExprList *pList, /* List to scan and in which to make substitutes */
  92292. int iTable, /* Table to be substituted */
  92293. ExprList *pEList /* Substitute values */
  92294. ){
  92295. int i;
  92296. if( pList==0 ) return;
  92297. for(i=0; i<pList->nExpr; i++){
  92298. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  92299. }
  92300. }
  92301. static void substSelect(
  92302. sqlite3 *db, /* Report malloc errors here */
  92303. Select *p, /* SELECT statement in which to make substitutions */
  92304. int iTable, /* Table to be replaced */
  92305. ExprList *pEList /* Substitute values */
  92306. ){
  92307. SrcList *pSrc;
  92308. struct SrcList_item *pItem;
  92309. int i;
  92310. if( !p ) return;
  92311. substExprList(db, p->pEList, iTable, pEList);
  92312. substExprList(db, p->pGroupBy, iTable, pEList);
  92313. substExprList(db, p->pOrderBy, iTable, pEList);
  92314. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  92315. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  92316. substSelect(db, p->pPrior, iTable, pEList);
  92317. pSrc = p->pSrc;
  92318. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  92319. if( ALWAYS(pSrc) ){
  92320. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  92321. substSelect(db, pItem->pSelect, iTable, pEList);
  92322. }
  92323. }
  92324. }
  92325. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  92326. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  92327. /*
  92328. ** This routine attempts to flatten subqueries as a performance optimization.
  92329. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  92330. **
  92331. ** To understand the concept of flattening, consider the following
  92332. ** query:
  92333. **
  92334. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  92335. **
  92336. ** The default way of implementing this query is to execute the
  92337. ** subquery first and store the results in a temporary table, then
  92338. ** run the outer query on that temporary table. This requires two
  92339. ** passes over the data. Furthermore, because the temporary table
  92340. ** has no indices, the WHERE clause on the outer query cannot be
  92341. ** optimized.
  92342. **
  92343. ** This routine attempts to rewrite queries such as the above into
  92344. ** a single flat select, like this:
  92345. **
  92346. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  92347. **
  92348. ** The code generated for this simpification gives the same result
  92349. ** but only has to scan the data once. And because indices might
  92350. ** exist on the table t1, a complete scan of the data might be
  92351. ** avoided.
  92352. **
  92353. ** Flattening is only attempted if all of the following are true:
  92354. **
  92355. ** (1) The subquery and the outer query do not both use aggregates.
  92356. **
  92357. ** (2) The subquery is not an aggregate or the outer query is not a join.
  92358. **
  92359. ** (3) The subquery is not the right operand of a left outer join
  92360. ** (Originally ticket #306. Strengthened by ticket #3300)
  92361. **
  92362. ** (4) The subquery is not DISTINCT.
  92363. **
  92364. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  92365. ** sub-queries that were excluded from this optimization. Restriction
  92366. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  92367. **
  92368. ** (6) The subquery does not use aggregates or the outer query is not
  92369. ** DISTINCT.
  92370. **
  92371. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  92372. ** A FROM clause, consider adding a FROM close with the special
  92373. ** table sqlite_once that consists of a single row containing a
  92374. ** single NULL.
  92375. **
  92376. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  92377. **
  92378. ** (9) The subquery does not use LIMIT or the outer query does not use
  92379. ** aggregates.
  92380. **
  92381. ** (10) The subquery does not use aggregates or the outer query does not
  92382. ** use LIMIT.
  92383. **
  92384. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  92385. **
  92386. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  92387. ** a separate restriction deriving from ticket #350.
  92388. **
  92389. ** (13) The subquery and outer query do not both use LIMIT.
  92390. **
  92391. ** (14) The subquery does not use OFFSET.
  92392. **
  92393. ** (15) The outer query is not part of a compound select or the
  92394. ** subquery does not have a LIMIT clause.
  92395. ** (See ticket #2339 and ticket [02a8e81d44]).
  92396. **
  92397. ** (16) The outer query is not an aggregate or the subquery does
  92398. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  92399. ** until we introduced the group_concat() function.
  92400. **
  92401. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  92402. ** compound clause made up entirely of non-aggregate queries, and
  92403. ** the parent query:
  92404. **
  92405. ** * is not itself part of a compound select,
  92406. ** * is not an aggregate or DISTINCT query, and
  92407. ** * is not a join
  92408. **
  92409. ** The parent and sub-query may contain WHERE clauses. Subject to
  92410. ** rules (11), (13) and (14), they may also contain ORDER BY,
  92411. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  92412. ** operator other than UNION ALL because all the other compound
  92413. ** operators have an implied DISTINCT which is disallowed by
  92414. ** restriction (4).
  92415. **
  92416. ** Also, each component of the sub-query must return the same number
  92417. ** of result columns. This is actually a requirement for any compound
  92418. ** SELECT statement, but all the code here does is make sure that no
  92419. ** such (illegal) sub-query is flattened. The caller will detect the
  92420. ** syntax error and return a detailed message.
  92421. **
  92422. ** (18) If the sub-query is a compound select, then all terms of the
  92423. ** ORDER by clause of the parent must be simple references to
  92424. ** columns of the sub-query.
  92425. **
  92426. ** (19) The subquery does not use LIMIT or the outer query does not
  92427. ** have a WHERE clause.
  92428. **
  92429. ** (20) If the sub-query is a compound select, then it must not use
  92430. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  92431. ** somewhat by saying that the terms of the ORDER BY clause must
  92432. ** appear as unmodified result columns in the outer query. But we
  92433. ** have other optimizations in mind to deal with that case.
  92434. **
  92435. ** (21) The subquery does not use LIMIT or the outer query is not
  92436. ** DISTINCT. (See ticket [752e1646fc]).
  92437. **
  92438. ** In this routine, the "p" parameter is a pointer to the outer query.
  92439. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  92440. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  92441. **
  92442. ** If flattening is not attempted, this routine is a no-op and returns 0.
  92443. ** If flattening is attempted this routine returns 1.
  92444. **
  92445. ** All of the expression analysis must occur on both the outer query and
  92446. ** the subquery before this routine runs.
  92447. */
  92448. static int flattenSubquery(
  92449. Parse *pParse, /* Parsing context */
  92450. Select *p, /* The parent or outer SELECT statement */
  92451. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  92452. int isAgg, /* True if outer SELECT uses aggregate functions */
  92453. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  92454. ){
  92455. const char *zSavedAuthContext = pParse->zAuthContext;
  92456. Select *pParent;
  92457. Select *pSub; /* The inner query or "subquery" */
  92458. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  92459. SrcList *pSrc; /* The FROM clause of the outer query */
  92460. SrcList *pSubSrc; /* The FROM clause of the subquery */
  92461. ExprList *pList; /* The result set of the outer query */
  92462. int iParent; /* VDBE cursor number of the pSub result set temp table */
  92463. int i; /* Loop counter */
  92464. Expr *pWhere; /* The WHERE clause */
  92465. struct SrcList_item *pSubitem; /* The subquery */
  92466. sqlite3 *db = pParse->db;
  92467. /* Check to see if flattening is permitted. Return 0 if not.
  92468. */
  92469. assert( p!=0 );
  92470. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  92471. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  92472. pSrc = p->pSrc;
  92473. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  92474. pSubitem = &pSrc->a[iFrom];
  92475. iParent = pSubitem->iCursor;
  92476. pSub = pSubitem->pSelect;
  92477. assert( pSub!=0 );
  92478. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  92479. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  92480. pSubSrc = pSub->pSrc;
  92481. assert( pSubSrc );
  92482. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  92483. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  92484. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  92485. ** became arbitrary expressions, we were forced to add restrictions (13)
  92486. ** and (14). */
  92487. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  92488. if( pSub->pOffset ) return 0; /* Restriction (14) */
  92489. if( p->pRightmost && pSub->pLimit ){
  92490. return 0; /* Restriction (15) */
  92491. }
  92492. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  92493. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  92494. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  92495. return 0; /* Restrictions (8)(9) */
  92496. }
  92497. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  92498. return 0; /* Restriction (6) */
  92499. }
  92500. if( p->pOrderBy && pSub->pOrderBy ){
  92501. return 0; /* Restriction (11) */
  92502. }
  92503. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  92504. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  92505. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  92506. return 0; /* Restriction (21) */
  92507. }
  92508. /* OBSOLETE COMMENT 1:
  92509. ** Restriction 3: If the subquery is a join, make sure the subquery is
  92510. ** not used as the right operand of an outer join. Examples of why this
  92511. ** is not allowed:
  92512. **
  92513. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  92514. **
  92515. ** If we flatten the above, we would get
  92516. **
  92517. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  92518. **
  92519. ** which is not at all the same thing.
  92520. **
  92521. ** OBSOLETE COMMENT 2:
  92522. ** Restriction 12: If the subquery is the right operand of a left outer
  92523. ** join, make sure the subquery has no WHERE clause.
  92524. ** An examples of why this is not allowed:
  92525. **
  92526. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  92527. **
  92528. ** If we flatten the above, we would get
  92529. **
  92530. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  92531. **
  92532. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  92533. ** effectively converts the OUTER JOIN into an INNER JOIN.
  92534. **
  92535. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  92536. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  92537. ** is fraught with danger. Best to avoid the whole thing. If the
  92538. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  92539. */
  92540. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  92541. return 0;
  92542. }
  92543. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  92544. ** use only the UNION ALL operator. And none of the simple select queries
  92545. ** that make up the compound SELECT are allowed to be aggregate or distinct
  92546. ** queries.
  92547. */
  92548. if( pSub->pPrior ){
  92549. if( pSub->pOrderBy ){
  92550. return 0; /* Restriction 20 */
  92551. }
  92552. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  92553. return 0;
  92554. }
  92555. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  92556. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  92557. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  92558. assert( pSub->pSrc!=0 );
  92559. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  92560. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  92561. || pSub1->pSrc->nSrc<1
  92562. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  92563. ){
  92564. return 0;
  92565. }
  92566. testcase( pSub1->pSrc->nSrc>1 );
  92567. }
  92568. /* Restriction 18. */
  92569. if( p->pOrderBy ){
  92570. int ii;
  92571. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  92572. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  92573. }
  92574. }
  92575. }
  92576. /***** If we reach this point, flattening is permitted. *****/
  92577. /* Authorize the subquery */
  92578. pParse->zAuthContext = pSubitem->zName;
  92579. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  92580. testcase( i==SQLITE_DENY );
  92581. pParse->zAuthContext = zSavedAuthContext;
  92582. /* If the sub-query is a compound SELECT statement, then (by restrictions
  92583. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  92584. ** be of the form:
  92585. **
  92586. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  92587. **
  92588. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  92589. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  92590. ** OFFSET clauses and joins them to the left-hand-side of the original
  92591. ** using UNION ALL operators. In this case N is the number of simple
  92592. ** select statements in the compound sub-query.
  92593. **
  92594. ** Example:
  92595. **
  92596. ** SELECT a+1 FROM (
  92597. ** SELECT x FROM tab
  92598. ** UNION ALL
  92599. ** SELECT y FROM tab
  92600. ** UNION ALL
  92601. ** SELECT abs(z*2) FROM tab2
  92602. ** ) WHERE a!=5 ORDER BY 1
  92603. **
  92604. ** Transformed into:
  92605. **
  92606. ** SELECT x+1 FROM tab WHERE x+1!=5
  92607. ** UNION ALL
  92608. ** SELECT y+1 FROM tab WHERE y+1!=5
  92609. ** UNION ALL
  92610. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  92611. ** ORDER BY 1
  92612. **
  92613. ** We call this the "compound-subquery flattening".
  92614. */
  92615. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  92616. Select *pNew;
  92617. ExprList *pOrderBy = p->pOrderBy;
  92618. Expr *pLimit = p->pLimit;
  92619. Expr *pOffset = p->pOffset;
  92620. Select *pPrior = p->pPrior;
  92621. p->pOrderBy = 0;
  92622. p->pSrc = 0;
  92623. p->pPrior = 0;
  92624. p->pLimit = 0;
  92625. p->pOffset = 0;
  92626. pNew = sqlite3SelectDup(db, p, 0);
  92627. p->pOffset = pOffset;
  92628. p->pLimit = pLimit;
  92629. p->pOrderBy = pOrderBy;
  92630. p->pSrc = pSrc;
  92631. p->op = TK_ALL;
  92632. p->pRightmost = 0;
  92633. if( pNew==0 ){
  92634. pNew = pPrior;
  92635. }else{
  92636. pNew->pPrior = pPrior;
  92637. pNew->pRightmost = 0;
  92638. }
  92639. p->pPrior = pNew;
  92640. if( db->mallocFailed ) return 1;
  92641. }
  92642. /* Begin flattening the iFrom-th entry of the FROM clause
  92643. ** in the outer query.
  92644. */
  92645. pSub = pSub1 = pSubitem->pSelect;
  92646. /* Delete the transient table structure associated with the
  92647. ** subquery
  92648. */
  92649. sqlite3DbFree(db, pSubitem->zDatabase);
  92650. sqlite3DbFree(db, pSubitem->zName);
  92651. sqlite3DbFree(db, pSubitem->zAlias);
  92652. pSubitem->zDatabase = 0;
  92653. pSubitem->zName = 0;
  92654. pSubitem->zAlias = 0;
  92655. pSubitem->pSelect = 0;
  92656. /* Defer deleting the Table object associated with the
  92657. ** subquery until code generation is
  92658. ** complete, since there may still exist Expr.pTab entries that
  92659. ** refer to the subquery even after flattening. Ticket #3346.
  92660. **
  92661. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  92662. */
  92663. if( ALWAYS(pSubitem->pTab!=0) ){
  92664. Table *pTabToDel = pSubitem->pTab;
  92665. if( pTabToDel->nRef==1 ){
  92666. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  92667. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  92668. pToplevel->pZombieTab = pTabToDel;
  92669. }else{
  92670. pTabToDel->nRef--;
  92671. }
  92672. pSubitem->pTab = 0;
  92673. }
  92674. /* The following loop runs once for each term in a compound-subquery
  92675. ** flattening (as described above). If we are doing a different kind
  92676. ** of flattening - a flattening other than a compound-subquery flattening -
  92677. ** then this loop only runs once.
  92678. **
  92679. ** This loop moves all of the FROM elements of the subquery into the
  92680. ** the FROM clause of the outer query. Before doing this, remember
  92681. ** the cursor number for the original outer query FROM element in
  92682. ** iParent. The iParent cursor will never be used. Subsequent code
  92683. ** will scan expressions looking for iParent references and replace
  92684. ** those references with expressions that resolve to the subquery FROM
  92685. ** elements we are now copying in.
  92686. */
  92687. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  92688. int nSubSrc;
  92689. u8 jointype = 0;
  92690. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  92691. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  92692. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  92693. if( pSrc ){
  92694. assert( pParent==p ); /* First time through the loop */
  92695. jointype = pSubitem->jointype;
  92696. }else{
  92697. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  92698. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  92699. if( pSrc==0 ){
  92700. assert( db->mallocFailed );
  92701. break;
  92702. }
  92703. }
  92704. /* The subquery uses a single slot of the FROM clause of the outer
  92705. ** query. If the subquery has more than one element in its FROM clause,
  92706. ** then expand the outer query to make space for it to hold all elements
  92707. ** of the subquery.
  92708. **
  92709. ** Example:
  92710. **
  92711. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  92712. **
  92713. ** The outer query has 3 slots in its FROM clause. One slot of the
  92714. ** outer query (the middle slot) is used by the subquery. The next
  92715. ** block of code will expand the out query to 4 slots. The middle
  92716. ** slot is expanded to two slots in order to make space for the
  92717. ** two elements in the FROM clause of the subquery.
  92718. */
  92719. if( nSubSrc>1 ){
  92720. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  92721. if( db->mallocFailed ){
  92722. break;
  92723. }
  92724. }
  92725. /* Transfer the FROM clause terms from the subquery into the
  92726. ** outer query.
  92727. */
  92728. for(i=0; i<nSubSrc; i++){
  92729. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  92730. pSrc->a[i+iFrom] = pSubSrc->a[i];
  92731. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  92732. }
  92733. pSrc->a[iFrom].jointype = jointype;
  92734. /* Now begin substituting subquery result set expressions for
  92735. ** references to the iParent in the outer query.
  92736. **
  92737. ** Example:
  92738. **
  92739. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  92740. ** \ \_____________ subquery __________/ /
  92741. ** \_____________________ outer query ______________________________/
  92742. **
  92743. ** We look at every expression in the outer query and every place we see
  92744. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  92745. */
  92746. pList = pParent->pEList;
  92747. for(i=0; i<pList->nExpr; i++){
  92748. if( pList->a[i].zName==0 ){
  92749. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  92750. sqlite3Dequote(zName);
  92751. pList->a[i].zName = zName;
  92752. }
  92753. }
  92754. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  92755. if( isAgg ){
  92756. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  92757. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  92758. }
  92759. if( pSub->pOrderBy ){
  92760. assert( pParent->pOrderBy==0 );
  92761. pParent->pOrderBy = pSub->pOrderBy;
  92762. pSub->pOrderBy = 0;
  92763. }else if( pParent->pOrderBy ){
  92764. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  92765. }
  92766. if( pSub->pWhere ){
  92767. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  92768. }else{
  92769. pWhere = 0;
  92770. }
  92771. if( subqueryIsAgg ){
  92772. assert( pParent->pHaving==0 );
  92773. pParent->pHaving = pParent->pWhere;
  92774. pParent->pWhere = pWhere;
  92775. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  92776. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  92777. sqlite3ExprDup(db, pSub->pHaving, 0));
  92778. assert( pParent->pGroupBy==0 );
  92779. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  92780. }else{
  92781. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  92782. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  92783. }
  92784. /* The flattened query is distinct if either the inner or the
  92785. ** outer query is distinct.
  92786. */
  92787. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  92788. /*
  92789. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  92790. **
  92791. ** One is tempted to try to add a and b to combine the limits. But this
  92792. ** does not work if either limit is negative.
  92793. */
  92794. if( pSub->pLimit ){
  92795. pParent->pLimit = pSub->pLimit;
  92796. pSub->pLimit = 0;
  92797. }
  92798. }
  92799. /* Finially, delete what is left of the subquery and return
  92800. ** success.
  92801. */
  92802. sqlite3SelectDelete(db, pSub1);
  92803. return 1;
  92804. }
  92805. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  92806. /*
  92807. ** Based on the contents of the AggInfo structure indicated by the first
  92808. ** argument, this function checks if the following are true:
  92809. **
  92810. ** * the query contains just a single aggregate function,
  92811. ** * the aggregate function is either min() or max(), and
  92812. ** * the argument to the aggregate function is a column value.
  92813. **
  92814. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  92815. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  92816. ** list of arguments passed to the aggregate before returning.
  92817. **
  92818. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  92819. ** WHERE_ORDERBY_NORMAL is returned.
  92820. */
  92821. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  92822. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  92823. *ppMinMax = 0;
  92824. if( pAggInfo->nFunc==1 ){
  92825. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  92826. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  92827. assert( pExpr->op==TK_AGG_FUNCTION );
  92828. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  92829. const char *zFunc = pExpr->u.zToken;
  92830. if( sqlite3StrICmp(zFunc, "min")==0 ){
  92831. eRet = WHERE_ORDERBY_MIN;
  92832. *ppMinMax = pEList;
  92833. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  92834. eRet = WHERE_ORDERBY_MAX;
  92835. *ppMinMax = pEList;
  92836. }
  92837. }
  92838. }
  92839. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  92840. return eRet;
  92841. }
  92842. /*
  92843. ** The select statement passed as the first argument is an aggregate query.
  92844. ** The second argment is the associated aggregate-info object. This
  92845. ** function tests if the SELECT is of the form:
  92846. **
  92847. ** SELECT count(*) FROM <tbl>
  92848. **
  92849. ** where table is a database table, not a sub-select or view. If the query
  92850. ** does match this pattern, then a pointer to the Table object representing
  92851. ** <tbl> is returned. Otherwise, 0 is returned.
  92852. */
  92853. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  92854. Table *pTab;
  92855. Expr *pExpr;
  92856. assert( !p->pGroupBy );
  92857. if( p->pWhere || p->pEList->nExpr!=1
  92858. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  92859. ){
  92860. return 0;
  92861. }
  92862. pTab = p->pSrc->a[0].pTab;
  92863. pExpr = p->pEList->a[0].pExpr;
  92864. assert( pTab && !pTab->pSelect && pExpr );
  92865. if( IsVirtual(pTab) ) return 0;
  92866. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  92867. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  92868. if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
  92869. if( pExpr->flags&EP_Distinct ) return 0;
  92870. return pTab;
  92871. }
  92872. /*
  92873. ** If the source-list item passed as an argument was augmented with an
  92874. ** INDEXED BY clause, then try to locate the specified index. If there
  92875. ** was such a clause and the named index cannot be found, return
  92876. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  92877. ** pFrom->pIndex and return SQLITE_OK.
  92878. */
  92879. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  92880. if( pFrom->pTab && pFrom->zIndex ){
  92881. Table *pTab = pFrom->pTab;
  92882. char *zIndex = pFrom->zIndex;
  92883. Index *pIdx;
  92884. for(pIdx=pTab->pIndex;
  92885. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  92886. pIdx=pIdx->pNext
  92887. );
  92888. if( !pIdx ){
  92889. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  92890. pParse->checkSchema = 1;
  92891. return SQLITE_ERROR;
  92892. }
  92893. pFrom->pIndex = pIdx;
  92894. }
  92895. return SQLITE_OK;
  92896. }
  92897. /*
  92898. ** Detect compound SELECT statements that use an ORDER BY clause with
  92899. ** an alternative collating sequence.
  92900. **
  92901. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  92902. **
  92903. ** These are rewritten as a subquery:
  92904. **
  92905. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  92906. ** ORDER BY ... COLLATE ...
  92907. **
  92908. ** This transformation is necessary because the multiSelectOrderBy() routine
  92909. ** above that generates the code for a compound SELECT with an ORDER BY clause
  92910. ** uses a merge algorithm that requires the same collating sequence on the
  92911. ** result columns as on the ORDER BY clause. See ticket
  92912. ** http://www.sqlite.org/src/info/6709574d2a
  92913. **
  92914. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  92915. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  92916. ** there are COLLATE terms in the ORDER BY.
  92917. */
  92918. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  92919. int i;
  92920. Select *pNew;
  92921. Select *pX;
  92922. sqlite3 *db;
  92923. struct ExprList_item *a;
  92924. SrcList *pNewSrc;
  92925. Parse *pParse;
  92926. Token dummy;
  92927. if( p->pPrior==0 ) return WRC_Continue;
  92928. if( p->pOrderBy==0 ) return WRC_Continue;
  92929. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  92930. if( pX==0 ) return WRC_Continue;
  92931. a = p->pOrderBy->a;
  92932. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  92933. if( a[i].pExpr->flags & EP_Collate ) break;
  92934. }
  92935. if( i<0 ) return WRC_Continue;
  92936. /* If we reach this point, that means the transformation is required. */
  92937. pParse = pWalker->pParse;
  92938. db = pParse->db;
  92939. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  92940. if( pNew==0 ) return WRC_Abort;
  92941. memset(&dummy, 0, sizeof(dummy));
  92942. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  92943. if( pNewSrc==0 ) return WRC_Abort;
  92944. *pNew = *p;
  92945. p->pSrc = pNewSrc;
  92946. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  92947. p->op = TK_SELECT;
  92948. p->pWhere = 0;
  92949. pNew->pGroupBy = 0;
  92950. pNew->pHaving = 0;
  92951. pNew->pOrderBy = 0;
  92952. p->pPrior = 0;
  92953. pNew->pLimit = 0;
  92954. pNew->pOffset = 0;
  92955. return WRC_Continue;
  92956. }
  92957. /*
  92958. ** This routine is a Walker callback for "expanding" a SELECT statement.
  92959. ** "Expanding" means to do the following:
  92960. **
  92961. ** (1) Make sure VDBE cursor numbers have been assigned to every
  92962. ** element of the FROM clause.
  92963. **
  92964. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  92965. ** defines FROM clause. When views appear in the FROM clause,
  92966. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  92967. ** that implements the view. A copy is made of the view's SELECT
  92968. ** statement so that we can freely modify or delete that statement
  92969. ** without worrying about messing up the presistent representation
  92970. ** of the view.
  92971. **
  92972. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  92973. ** on joins and the ON and USING clause of joins.
  92974. **
  92975. ** (4) Scan the list of columns in the result set (pEList) looking
  92976. ** for instances of the "*" operator or the TABLE.* operator.
  92977. ** If found, expand each "*" to be every column in every table
  92978. ** and TABLE.* to be every column in TABLE.
  92979. **
  92980. */
  92981. static int selectExpander(Walker *pWalker, Select *p){
  92982. Parse *pParse = pWalker->pParse;
  92983. int i, j, k;
  92984. SrcList *pTabList;
  92985. ExprList *pEList;
  92986. struct SrcList_item *pFrom;
  92987. sqlite3 *db = pParse->db;
  92988. Expr *pE, *pRight, *pExpr;
  92989. u16 selFlags = p->selFlags;
  92990. p->selFlags |= SF_Expanded;
  92991. if( db->mallocFailed ){
  92992. return WRC_Abort;
  92993. }
  92994. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  92995. return WRC_Prune;
  92996. }
  92997. pTabList = p->pSrc;
  92998. pEList = p->pEList;
  92999. /* Make sure cursor numbers have been assigned to all entries in
  93000. ** the FROM clause of the SELECT statement.
  93001. */
  93002. sqlite3SrcListAssignCursors(pParse, pTabList);
  93003. /* Look up every table named in the FROM clause of the select. If
  93004. ** an entry of the FROM clause is a subquery instead of a table or view,
  93005. ** then create a transient table structure to describe the subquery.
  93006. */
  93007. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  93008. Table *pTab;
  93009. if( pFrom->pTab!=0 ){
  93010. /* This statement has already been prepared. There is no need
  93011. ** to go further. */
  93012. assert( i==0 );
  93013. return WRC_Prune;
  93014. }
  93015. if( pFrom->zName==0 ){
  93016. #ifndef SQLITE_OMIT_SUBQUERY
  93017. Select *pSel = pFrom->pSelect;
  93018. /* A sub-query in the FROM clause of a SELECT */
  93019. assert( pSel!=0 );
  93020. assert( pFrom->pTab==0 );
  93021. sqlite3WalkSelect(pWalker, pSel);
  93022. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  93023. if( pTab==0 ) return WRC_Abort;
  93024. pTab->nRef = 1;
  93025. pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  93026. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  93027. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  93028. pTab->iPKey = -1;
  93029. pTab->nRowEst = 1000000;
  93030. pTab->tabFlags |= TF_Ephemeral;
  93031. #endif
  93032. }else{
  93033. /* An ordinary table or view name in the FROM clause */
  93034. assert( pFrom->pTab==0 );
  93035. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  93036. if( pTab==0 ) return WRC_Abort;
  93037. if( pTab->nRef==0xffff ){
  93038. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  93039. pTab->zName);
  93040. pFrom->pTab = 0;
  93041. return WRC_Abort;
  93042. }
  93043. pTab->nRef++;
  93044. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  93045. if( pTab->pSelect || IsVirtual(pTab) ){
  93046. /* We reach here if the named table is a really a view */
  93047. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  93048. assert( pFrom->pSelect==0 );
  93049. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  93050. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  93051. }
  93052. #endif
  93053. }
  93054. /* Locate the index named by the INDEXED BY clause, if any. */
  93055. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  93056. return WRC_Abort;
  93057. }
  93058. }
  93059. /* Process NATURAL keywords, and ON and USING clauses of joins.
  93060. */
  93061. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  93062. return WRC_Abort;
  93063. }
  93064. /* For every "*" that occurs in the column list, insert the names of
  93065. ** all columns in all tables. And for every TABLE.* insert the names
  93066. ** of all columns in TABLE. The parser inserted a special expression
  93067. ** with the TK_ALL operator for each "*" that it found in the column list.
  93068. ** The following code just has to locate the TK_ALL expressions and expand
  93069. ** each one to the list of all columns in all tables.
  93070. **
  93071. ** The first loop just checks to see if there are any "*" operators
  93072. ** that need expanding.
  93073. */
  93074. for(k=0; k<pEList->nExpr; k++){
  93075. pE = pEList->a[k].pExpr;
  93076. if( pE->op==TK_ALL ) break;
  93077. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  93078. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  93079. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  93080. }
  93081. if( k<pEList->nExpr ){
  93082. /*
  93083. ** If we get here it means the result set contains one or more "*"
  93084. ** operators that need to be expanded. Loop through each expression
  93085. ** in the result set and expand them one by one.
  93086. */
  93087. struct ExprList_item *a = pEList->a;
  93088. ExprList *pNew = 0;
  93089. int flags = pParse->db->flags;
  93090. int longNames = (flags & SQLITE_FullColNames)!=0
  93091. && (flags & SQLITE_ShortColNames)==0;
  93092. /* When processing FROM-clause subqueries, it is always the case
  93093. ** that full_column_names=OFF and short_column_names=ON. The
  93094. ** sqlite3ResultSetOfSelect() routine makes it so. */
  93095. assert( (p->selFlags & SF_NestedFrom)==0
  93096. || ((flags & SQLITE_FullColNames)==0 &&
  93097. (flags & SQLITE_ShortColNames)!=0) );
  93098. for(k=0; k<pEList->nExpr; k++){
  93099. pE = a[k].pExpr;
  93100. pRight = pE->pRight;
  93101. assert( pE->op!=TK_DOT || pRight!=0 );
  93102. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  93103. /* This particular expression does not need to be expanded.
  93104. */
  93105. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  93106. if( pNew ){
  93107. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  93108. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  93109. a[k].zName = 0;
  93110. a[k].zSpan = 0;
  93111. }
  93112. a[k].pExpr = 0;
  93113. }else{
  93114. /* This expression is a "*" or a "TABLE.*" and needs to be
  93115. ** expanded. */
  93116. int tableSeen = 0; /* Set to 1 when TABLE matches */
  93117. char *zTName = 0; /* text of name of TABLE */
  93118. if( pE->op==TK_DOT ){
  93119. assert( pE->pLeft!=0 );
  93120. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  93121. zTName = pE->pLeft->u.zToken;
  93122. }
  93123. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  93124. Table *pTab = pFrom->pTab;
  93125. Select *pSub = pFrom->pSelect;
  93126. char *zTabName = pFrom->zAlias;
  93127. const char *zSchemaName = 0;
  93128. int iDb;
  93129. if( zTabName==0 ){
  93130. zTabName = pTab->zName;
  93131. }
  93132. if( db->mallocFailed ) break;
  93133. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  93134. pSub = 0;
  93135. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  93136. continue;
  93137. }
  93138. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93139. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  93140. }
  93141. for(j=0; j<pTab->nCol; j++){
  93142. char *zName = pTab->aCol[j].zName;
  93143. char *zColname; /* The computed column name */
  93144. char *zToFree; /* Malloced string that needs to be freed */
  93145. Token sColname; /* Computed column name as a token */
  93146. assert( zName );
  93147. if( zTName && pSub
  93148. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  93149. ){
  93150. continue;
  93151. }
  93152. /* If a column is marked as 'hidden' (currently only possible
  93153. ** for virtual tables), do not include it in the expanded
  93154. ** result-set list.
  93155. */
  93156. if( IsHiddenColumn(&pTab->aCol[j]) ){
  93157. assert(IsVirtual(pTab));
  93158. continue;
  93159. }
  93160. tableSeen = 1;
  93161. if( i>0 && zTName==0 ){
  93162. if( (pFrom->jointype & JT_NATURAL)!=0
  93163. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  93164. ){
  93165. /* In a NATURAL join, omit the join columns from the
  93166. ** table to the right of the join */
  93167. continue;
  93168. }
  93169. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  93170. /* In a join with a USING clause, omit columns in the
  93171. ** using clause from the table on the right. */
  93172. continue;
  93173. }
  93174. }
  93175. pRight = sqlite3Expr(db, TK_ID, zName);
  93176. zColname = zName;
  93177. zToFree = 0;
  93178. if( longNames || pTabList->nSrc>1 ){
  93179. Expr *pLeft;
  93180. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  93181. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  93182. if( zSchemaName ){
  93183. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  93184. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  93185. }
  93186. if( longNames ){
  93187. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  93188. zToFree = zColname;
  93189. }
  93190. }else{
  93191. pExpr = pRight;
  93192. }
  93193. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  93194. sColname.z = zColname;
  93195. sColname.n = sqlite3Strlen30(zColname);
  93196. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  93197. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  93198. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  93199. if( pSub ){
  93200. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  93201. testcase( pX->zSpan==0 );
  93202. }else{
  93203. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  93204. zSchemaName, zTabName, zColname);
  93205. testcase( pX->zSpan==0 );
  93206. }
  93207. pX->bSpanIsTab = 1;
  93208. }
  93209. sqlite3DbFree(db, zToFree);
  93210. }
  93211. }
  93212. if( !tableSeen ){
  93213. if( zTName ){
  93214. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  93215. }else{
  93216. sqlite3ErrorMsg(pParse, "no tables specified");
  93217. }
  93218. }
  93219. }
  93220. }
  93221. sqlite3ExprListDelete(db, pEList);
  93222. p->pEList = pNew;
  93223. }
  93224. #if SQLITE_MAX_COLUMN
  93225. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  93226. sqlite3ErrorMsg(pParse, "too many columns in result set");
  93227. }
  93228. #endif
  93229. return WRC_Continue;
  93230. }
  93231. /*
  93232. ** No-op routine for the parse-tree walker.
  93233. **
  93234. ** When this routine is the Walker.xExprCallback then expression trees
  93235. ** are walked without any actions being taken at each node. Presumably,
  93236. ** when this routine is used for Walker.xExprCallback then
  93237. ** Walker.xSelectCallback is set to do something useful for every
  93238. ** subquery in the parser tree.
  93239. */
  93240. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  93241. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93242. return WRC_Continue;
  93243. }
  93244. /*
  93245. ** This routine "expands" a SELECT statement and all of its subqueries.
  93246. ** For additional information on what it means to "expand" a SELECT
  93247. ** statement, see the comment on the selectExpand worker callback above.
  93248. **
  93249. ** Expanding a SELECT statement is the first step in processing a
  93250. ** SELECT statement. The SELECT statement must be expanded before
  93251. ** name resolution is performed.
  93252. **
  93253. ** If anything goes wrong, an error message is written into pParse.
  93254. ** The calling function can detect the problem by looking at pParse->nErr
  93255. ** and/or pParse->db->mallocFailed.
  93256. */
  93257. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  93258. Walker w;
  93259. memset(&w, 0, sizeof(w));
  93260. w.xSelectCallback = convertCompoundSelectToSubquery;
  93261. w.xExprCallback = exprWalkNoop;
  93262. w.pParse = pParse;
  93263. sqlite3WalkSelect(&w, pSelect);
  93264. w.xSelectCallback = selectExpander;
  93265. sqlite3WalkSelect(&w, pSelect);
  93266. }
  93267. #ifndef SQLITE_OMIT_SUBQUERY
  93268. /*
  93269. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  93270. ** interface.
  93271. **
  93272. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  93273. ** information to the Table structure that represents the result set
  93274. ** of that subquery.
  93275. **
  93276. ** The Table structure that represents the result set was constructed
  93277. ** by selectExpander() but the type and collation information was omitted
  93278. ** at that point because identifiers had not yet been resolved. This
  93279. ** routine is called after identifier resolution.
  93280. */
  93281. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  93282. Parse *pParse;
  93283. int i;
  93284. SrcList *pTabList;
  93285. struct SrcList_item *pFrom;
  93286. assert( p->selFlags & SF_Resolved );
  93287. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  93288. p->selFlags |= SF_HasTypeInfo;
  93289. pParse = pWalker->pParse;
  93290. pTabList = p->pSrc;
  93291. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  93292. Table *pTab = pFrom->pTab;
  93293. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  93294. /* A sub-query in the FROM clause of a SELECT */
  93295. Select *pSel = pFrom->pSelect;
  93296. assert( pSel );
  93297. while( pSel->pPrior ) pSel = pSel->pPrior;
  93298. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  93299. }
  93300. }
  93301. }
  93302. return WRC_Continue;
  93303. }
  93304. #endif
  93305. /*
  93306. ** This routine adds datatype and collating sequence information to
  93307. ** the Table structures of all FROM-clause subqueries in a
  93308. ** SELECT statement.
  93309. **
  93310. ** Use this routine after name resolution.
  93311. */
  93312. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  93313. #ifndef SQLITE_OMIT_SUBQUERY
  93314. Walker w;
  93315. memset(&w, 0, sizeof(w));
  93316. w.xSelectCallback = selectAddSubqueryTypeInfo;
  93317. w.xExprCallback = exprWalkNoop;
  93318. w.pParse = pParse;
  93319. w.bSelectDepthFirst = 1;
  93320. sqlite3WalkSelect(&w, pSelect);
  93321. #endif
  93322. }
  93323. /*
  93324. ** This routine sets up a SELECT statement for processing. The
  93325. ** following is accomplished:
  93326. **
  93327. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  93328. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  93329. ** * ON and USING clauses are shifted into WHERE statements
  93330. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  93331. ** * Identifiers in expression are matched to tables.
  93332. **
  93333. ** This routine acts recursively on all subqueries within the SELECT.
  93334. */
  93335. SQLITE_PRIVATE void sqlite3SelectPrep(
  93336. Parse *pParse, /* The parser context */
  93337. Select *p, /* The SELECT statement being coded. */
  93338. NameContext *pOuterNC /* Name context for container */
  93339. ){
  93340. sqlite3 *db;
  93341. if( NEVER(p==0) ) return;
  93342. db = pParse->db;
  93343. if( db->mallocFailed ) return;
  93344. if( p->selFlags & SF_HasTypeInfo ) return;
  93345. sqlite3SelectExpand(pParse, p);
  93346. if( pParse->nErr || db->mallocFailed ) return;
  93347. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  93348. if( pParse->nErr || db->mallocFailed ) return;
  93349. sqlite3SelectAddTypeInfo(pParse, p);
  93350. }
  93351. /*
  93352. ** Reset the aggregate accumulator.
  93353. **
  93354. ** The aggregate accumulator is a set of memory cells that hold
  93355. ** intermediate results while calculating an aggregate. This
  93356. ** routine generates code that stores NULLs in all of those memory
  93357. ** cells.
  93358. */
  93359. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  93360. Vdbe *v = pParse->pVdbe;
  93361. int i;
  93362. struct AggInfo_func *pFunc;
  93363. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  93364. return;
  93365. }
  93366. for(i=0; i<pAggInfo->nColumn; i++){
  93367. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  93368. }
  93369. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  93370. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  93371. if( pFunc->iDistinct>=0 ){
  93372. Expr *pE = pFunc->pExpr;
  93373. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  93374. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  93375. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  93376. "argument");
  93377. pFunc->iDistinct = -1;
  93378. }else{
  93379. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  93380. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  93381. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  93382. }
  93383. }
  93384. }
  93385. }
  93386. /*
  93387. ** Invoke the OP_AggFinalize opcode for every aggregate function
  93388. ** in the AggInfo structure.
  93389. */
  93390. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  93391. Vdbe *v = pParse->pVdbe;
  93392. int i;
  93393. struct AggInfo_func *pF;
  93394. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  93395. ExprList *pList = pF->pExpr->x.pList;
  93396. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  93397. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  93398. (void*)pF->pFunc, P4_FUNCDEF);
  93399. }
  93400. }
  93401. /*
  93402. ** Update the accumulator memory cells for an aggregate based on
  93403. ** the current cursor position.
  93404. */
  93405. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  93406. Vdbe *v = pParse->pVdbe;
  93407. int i;
  93408. int regHit = 0;
  93409. int addrHitTest = 0;
  93410. struct AggInfo_func *pF;
  93411. struct AggInfo_col *pC;
  93412. pAggInfo->directMode = 1;
  93413. sqlite3ExprCacheClear(pParse);
  93414. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  93415. int nArg;
  93416. int addrNext = 0;
  93417. int regAgg;
  93418. ExprList *pList = pF->pExpr->x.pList;
  93419. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  93420. if( pList ){
  93421. nArg = pList->nExpr;
  93422. regAgg = sqlite3GetTempRange(pParse, nArg);
  93423. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  93424. }else{
  93425. nArg = 0;
  93426. regAgg = 0;
  93427. }
  93428. if( pF->iDistinct>=0 ){
  93429. addrNext = sqlite3VdbeMakeLabel(v);
  93430. assert( nArg==1 );
  93431. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  93432. }
  93433. if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  93434. CollSeq *pColl = 0;
  93435. struct ExprList_item *pItem;
  93436. int j;
  93437. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  93438. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  93439. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  93440. }
  93441. if( !pColl ){
  93442. pColl = pParse->db->pDfltColl;
  93443. }
  93444. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  93445. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  93446. }
  93447. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  93448. (void*)pF->pFunc, P4_FUNCDEF);
  93449. sqlite3VdbeChangeP5(v, (u8)nArg);
  93450. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  93451. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  93452. if( addrNext ){
  93453. sqlite3VdbeResolveLabel(v, addrNext);
  93454. sqlite3ExprCacheClear(pParse);
  93455. }
  93456. }
  93457. /* Before populating the accumulator registers, clear the column cache.
  93458. ** Otherwise, if any of the required column values are already present
  93459. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  93460. ** to pC->iMem. But by the time the value is used, the original register
  93461. ** may have been used, invalidating the underlying buffer holding the
  93462. ** text or blob value. See ticket [883034dcb5].
  93463. **
  93464. ** Another solution would be to change the OP_SCopy used to copy cached
  93465. ** values to an OP_Copy.
  93466. */
  93467. if( regHit ){
  93468. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  93469. }
  93470. sqlite3ExprCacheClear(pParse);
  93471. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  93472. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  93473. }
  93474. pAggInfo->directMode = 0;
  93475. sqlite3ExprCacheClear(pParse);
  93476. if( addrHitTest ){
  93477. sqlite3VdbeJumpHere(v, addrHitTest);
  93478. }
  93479. }
  93480. /*
  93481. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  93482. ** count(*) query ("SELECT count(*) FROM pTab").
  93483. */
  93484. #ifndef SQLITE_OMIT_EXPLAIN
  93485. static void explainSimpleCount(
  93486. Parse *pParse, /* Parse context */
  93487. Table *pTab, /* Table being queried */
  93488. Index *pIdx /* Index used to optimize scan, or NULL */
  93489. ){
  93490. if( pParse->explain==2 ){
  93491. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
  93492. pTab->zName,
  93493. pIdx ? "USING COVERING INDEX " : "",
  93494. pIdx ? pIdx->zName : "",
  93495. pTab->nRowEst
  93496. );
  93497. sqlite3VdbeAddOp4(
  93498. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  93499. );
  93500. }
  93501. }
  93502. #else
  93503. # define explainSimpleCount(a,b,c)
  93504. #endif
  93505. /*
  93506. ** Generate code for the SELECT statement given in the p argument.
  93507. **
  93508. ** The results are distributed in various ways depending on the
  93509. ** contents of the SelectDest structure pointed to by argument pDest
  93510. ** as follows:
  93511. **
  93512. ** pDest->eDest Result
  93513. ** ------------ -------------------------------------------
  93514. ** SRT_Output Generate a row of output (using the OP_ResultRow
  93515. ** opcode) for each row in the result set.
  93516. **
  93517. ** SRT_Mem Only valid if the result is a single column.
  93518. ** Store the first column of the first result row
  93519. ** in register pDest->iSDParm then abandon the rest
  93520. ** of the query. This destination implies "LIMIT 1".
  93521. **
  93522. ** SRT_Set The result must be a single column. Store each
  93523. ** row of result as the key in table pDest->iSDParm.
  93524. ** Apply the affinity pDest->affSdst before storing
  93525. ** results. Used to implement "IN (SELECT ...)".
  93526. **
  93527. ** SRT_Union Store results as a key in a temporary table
  93528. ** identified by pDest->iSDParm.
  93529. **
  93530. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  93531. **
  93532. ** SRT_Table Store results in temporary table pDest->iSDParm.
  93533. ** This is like SRT_EphemTab except that the table
  93534. ** is assumed to already be open.
  93535. **
  93536. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  93537. ** the result there. The cursor is left open after
  93538. ** returning. This is like SRT_Table except that
  93539. ** this destination uses OP_OpenEphemeral to create
  93540. ** the table first.
  93541. **
  93542. ** SRT_Coroutine Generate a co-routine that returns a new row of
  93543. ** results each time it is invoked. The entry point
  93544. ** of the co-routine is stored in register pDest->iSDParm.
  93545. **
  93546. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  93547. ** set is not empty.
  93548. **
  93549. ** SRT_Discard Throw the results away. This is used by SELECT
  93550. ** statements within triggers whose only purpose is
  93551. ** the side-effects of functions.
  93552. **
  93553. ** This routine returns the number of errors. If any errors are
  93554. ** encountered, then an appropriate error message is left in
  93555. ** pParse->zErrMsg.
  93556. **
  93557. ** This routine does NOT free the Select structure passed in. The
  93558. ** calling function needs to do that.
  93559. */
  93560. SQLITE_PRIVATE int sqlite3Select(
  93561. Parse *pParse, /* The parser context */
  93562. Select *p, /* The SELECT statement being coded. */
  93563. SelectDest *pDest /* What to do with the query results */
  93564. ){
  93565. int i, j; /* Loop counters */
  93566. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  93567. Vdbe *v; /* The virtual machine under construction */
  93568. int isAgg; /* True for select lists like "count(*)" */
  93569. ExprList *pEList; /* List of columns to extract. */
  93570. SrcList *pTabList; /* List of tables to select from */
  93571. Expr *pWhere; /* The WHERE clause. May be NULL */
  93572. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  93573. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  93574. Expr *pHaving; /* The HAVING clause. May be NULL */
  93575. int rc = 1; /* Value to return from this function */
  93576. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  93577. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  93578. AggInfo sAggInfo; /* Information used by aggregate queries */
  93579. int iEnd; /* Address of the end of the query */
  93580. sqlite3 *db; /* The database connection */
  93581. #ifndef SQLITE_OMIT_EXPLAIN
  93582. int iRestoreSelectId = pParse->iSelectId;
  93583. pParse->iSelectId = pParse->iNextSelectId++;
  93584. #endif
  93585. db = pParse->db;
  93586. if( p==0 || db->mallocFailed || pParse->nErr ){
  93587. return 1;
  93588. }
  93589. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  93590. memset(&sAggInfo, 0, sizeof(sAggInfo));
  93591. if( IgnorableOrderby(pDest) ){
  93592. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  93593. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  93594. /* If ORDER BY makes no difference in the output then neither does
  93595. ** DISTINCT so it can be removed too. */
  93596. sqlite3ExprListDelete(db, p->pOrderBy);
  93597. p->pOrderBy = 0;
  93598. p->selFlags &= ~SF_Distinct;
  93599. }
  93600. sqlite3SelectPrep(pParse, p, 0);
  93601. pOrderBy = p->pOrderBy;
  93602. pTabList = p->pSrc;
  93603. pEList = p->pEList;
  93604. if( pParse->nErr || db->mallocFailed ){
  93605. goto select_end;
  93606. }
  93607. isAgg = (p->selFlags & SF_Aggregate)!=0;
  93608. assert( pEList!=0 );
  93609. /* Begin generating code.
  93610. */
  93611. v = sqlite3GetVdbe(pParse);
  93612. if( v==0 ) goto select_end;
  93613. /* If writing to memory or generating a set
  93614. ** only a single column may be output.
  93615. */
  93616. #ifndef SQLITE_OMIT_SUBQUERY
  93617. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  93618. goto select_end;
  93619. }
  93620. #endif
  93621. /* Generate code for all sub-queries in the FROM clause
  93622. */
  93623. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  93624. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  93625. struct SrcList_item *pItem = &pTabList->a[i];
  93626. SelectDest dest;
  93627. Select *pSub = pItem->pSelect;
  93628. int isAggSub;
  93629. if( pSub==0 ) continue;
  93630. /* Sometimes the code for a subquery will be generated more than
  93631. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  93632. ** for example. In that case, do not regenerate the code to manifest
  93633. ** a view or the co-routine to implement a view. The first instance
  93634. ** is sufficient, though the subroutine to manifest the view does need
  93635. ** to be invoked again. */
  93636. if( pItem->addrFillSub ){
  93637. if( pItem->viaCoroutine==0 ){
  93638. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  93639. }
  93640. continue;
  93641. }
  93642. /* Increment Parse.nHeight by the height of the largest expression
  93643. ** tree refered to by this, the parent select. The child select
  93644. ** may contain expression trees of at most
  93645. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  93646. ** more conservative than necessary, but much easier than enforcing
  93647. ** an exact limit.
  93648. */
  93649. pParse->nHeight += sqlite3SelectExprHeight(p);
  93650. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  93651. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  93652. /* This subquery can be absorbed into its parent. */
  93653. if( isAggSub ){
  93654. isAgg = 1;
  93655. p->selFlags |= SF_Aggregate;
  93656. }
  93657. i = -1;
  93658. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  93659. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  93660. ){
  93661. /* Implement a co-routine that will return a single row of the result
  93662. ** set on each invocation.
  93663. */
  93664. int addrTop;
  93665. int addrEof;
  93666. pItem->regReturn = ++pParse->nMem;
  93667. addrEof = ++pParse->nMem;
  93668. /* Before coding the OP_Goto to jump to the start of the main routine,
  93669. ** ensure that the jump to the verify-schema routine has already
  93670. ** been coded. Otherwise, the verify-schema would likely be coded as
  93671. ** part of the co-routine. If the main routine then accessed the
  93672. ** database before invoking the co-routine for the first time (for
  93673. ** example to initialize a LIMIT register from a sub-select), it would
  93674. ** be doing so without having verified the schema version and obtained
  93675. ** the required db locks. See ticket d6b36be38. */
  93676. sqlite3CodeVerifySchema(pParse, -1);
  93677. sqlite3VdbeAddOp0(v, OP_Goto);
  93678. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  93679. sqlite3VdbeChangeP5(v, 1);
  93680. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  93681. pItem->addrFillSub = addrTop;
  93682. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  93683. sqlite3VdbeChangeP5(v, 1);
  93684. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  93685. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  93686. sqlite3Select(pParse, pSub, &dest);
  93687. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  93688. pItem->viaCoroutine = 1;
  93689. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  93690. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  93691. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  93692. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  93693. VdbeComment((v, "end %s", pItem->pTab->zName));
  93694. sqlite3VdbeJumpHere(v, addrTop-1);
  93695. sqlite3ClearTempRegCache(pParse);
  93696. }else{
  93697. /* Generate a subroutine that will fill an ephemeral table with
  93698. ** the content of this subquery. pItem->addrFillSub will point
  93699. ** to the address of the generated subroutine. pItem->regReturn
  93700. ** is a register allocated to hold the subroutine return address
  93701. */
  93702. int topAddr;
  93703. int onceAddr = 0;
  93704. int retAddr;
  93705. assert( pItem->addrFillSub==0 );
  93706. pItem->regReturn = ++pParse->nMem;
  93707. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  93708. pItem->addrFillSub = topAddr+1;
  93709. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  93710. if( pItem->isCorrelated==0 ){
  93711. /* If the subquery is not correlated and if we are not inside of
  93712. ** a trigger, then we only need to compute the value of the subquery
  93713. ** once. */
  93714. onceAddr = sqlite3CodeOnce(pParse);
  93715. }
  93716. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  93717. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  93718. sqlite3Select(pParse, pSub, &dest);
  93719. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  93720. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  93721. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  93722. VdbeComment((v, "end %s", pItem->pTab->zName));
  93723. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  93724. sqlite3ClearTempRegCache(pParse);
  93725. }
  93726. if( /*pParse->nErr ||*/ db->mallocFailed ){
  93727. goto select_end;
  93728. }
  93729. pParse->nHeight -= sqlite3SelectExprHeight(p);
  93730. pTabList = p->pSrc;
  93731. if( !IgnorableOrderby(pDest) ){
  93732. pOrderBy = p->pOrderBy;
  93733. }
  93734. }
  93735. pEList = p->pEList;
  93736. #endif
  93737. pWhere = p->pWhere;
  93738. pGroupBy = p->pGroupBy;
  93739. pHaving = p->pHaving;
  93740. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  93741. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  93742. /* If there is are a sequence of queries, do the earlier ones first.
  93743. */
  93744. if( p->pPrior ){
  93745. if( p->pRightmost==0 ){
  93746. Select *pLoop, *pRight = 0;
  93747. int cnt = 0;
  93748. int mxSelect;
  93749. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  93750. pLoop->pRightmost = p;
  93751. pLoop->pNext = pRight;
  93752. pRight = pLoop;
  93753. }
  93754. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  93755. if( mxSelect && cnt>mxSelect ){
  93756. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  93757. goto select_end;
  93758. }
  93759. }
  93760. rc = multiSelect(pParse, p, pDest);
  93761. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  93762. return rc;
  93763. }
  93764. #endif
  93765. /* If there is both a GROUP BY and an ORDER BY clause and they are
  93766. ** identical, then disable the ORDER BY clause since the GROUP BY
  93767. ** will cause elements to come out in the correct order. This is
  93768. ** an optimization - the correct answer should result regardless.
  93769. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  93770. ** to disable this optimization for testing purposes.
  93771. */
  93772. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
  93773. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  93774. pOrderBy = 0;
  93775. }
  93776. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  93777. ** if the select-list is the same as the ORDER BY list, then this query
  93778. ** can be rewritten as a GROUP BY. In other words, this:
  93779. **
  93780. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  93781. **
  93782. ** is transformed to:
  93783. **
  93784. ** SELECT xyz FROM ... GROUP BY xyz
  93785. **
  93786. ** The second form is preferred as a single index (or temp-table) may be
  93787. ** used for both the ORDER BY and DISTINCT processing. As originally
  93788. ** written the query must use a temp-table for at least one of the ORDER
  93789. ** BY and DISTINCT, and an index or separate temp-table for the other.
  93790. */
  93791. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  93792. && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
  93793. ){
  93794. p->selFlags &= ~SF_Distinct;
  93795. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  93796. pGroupBy = p->pGroupBy;
  93797. pOrderBy = 0;
  93798. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  93799. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  93800. ** original setting of the SF_Distinct flag, not the current setting */
  93801. assert( sDistinct.isTnct );
  93802. }
  93803. /* If there is an ORDER BY clause, then this sorting
  93804. ** index might end up being unused if the data can be
  93805. ** extracted in pre-sorted order. If that is the case, then the
  93806. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  93807. ** we figure out that the sorting index is not needed. The addrSortIndex
  93808. ** variable is used to facilitate that change.
  93809. */
  93810. if( pOrderBy ){
  93811. KeyInfo *pKeyInfo;
  93812. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  93813. pOrderBy->iECursor = pParse->nTab++;
  93814. p->addrOpenEphm[2] = addrSortIndex =
  93815. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  93816. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  93817. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  93818. }else{
  93819. addrSortIndex = -1;
  93820. }
  93821. /* If the output is destined for a temporary table, open that table.
  93822. */
  93823. if( pDest->eDest==SRT_EphemTab ){
  93824. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  93825. }
  93826. /* Set the limiter.
  93827. */
  93828. iEnd = sqlite3VdbeMakeLabel(v);
  93829. p->nSelectRow = (double)LARGEST_INT64;
  93830. computeLimitRegisters(pParse, p, iEnd);
  93831. if( p->iLimit==0 && addrSortIndex>=0 ){
  93832. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  93833. p->selFlags |= SF_UseSorter;
  93834. }
  93835. /* Open a virtual index to use for the distinct set.
  93836. */
  93837. if( p->selFlags & SF_Distinct ){
  93838. sDistinct.tabTnct = pParse->nTab++;
  93839. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  93840. sDistinct.tabTnct, 0, 0,
  93841. (char*)keyInfoFromExprList(pParse, p->pEList),
  93842. P4_KEYINFO_HANDOFF);
  93843. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  93844. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  93845. }else{
  93846. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  93847. }
  93848. if( !isAgg && pGroupBy==0 ){
  93849. /* No aggregate functions and no GROUP BY clause */
  93850. ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
  93851. /* Begin the database scan. */
  93852. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
  93853. if( pWInfo==0 ) goto select_end;
  93854. if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
  93855. if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
  93856. if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
  93857. /* If sorting index that was created by a prior OP_OpenEphemeral
  93858. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  93859. ** into an OP_Noop.
  93860. */
  93861. if( addrSortIndex>=0 && pOrderBy==0 ){
  93862. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  93863. p->addrOpenEphm[2] = -1;
  93864. }
  93865. /* Use the standard inner loop. */
  93866. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  93867. pWInfo->iContinue, pWInfo->iBreak);
  93868. /* End the database scan loop.
  93869. */
  93870. sqlite3WhereEnd(pWInfo);
  93871. }else{
  93872. /* This case when there exist aggregate functions or a GROUP BY clause
  93873. ** or both */
  93874. NameContext sNC; /* Name context for processing aggregate information */
  93875. int iAMem; /* First Mem address for storing current GROUP BY */
  93876. int iBMem; /* First Mem address for previous GROUP BY */
  93877. int iUseFlag; /* Mem address holding flag indicating that at least
  93878. ** one row of the input to the aggregator has been
  93879. ** processed */
  93880. int iAbortFlag; /* Mem address which causes query abort if positive */
  93881. int groupBySort; /* Rows come from source in GROUP BY order */
  93882. int addrEnd; /* End of processing for this SELECT */
  93883. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  93884. int sortOut = 0; /* Output register from the sorter */
  93885. /* Remove any and all aliases between the result set and the
  93886. ** GROUP BY clause.
  93887. */
  93888. if( pGroupBy ){
  93889. int k; /* Loop counter */
  93890. struct ExprList_item *pItem; /* For looping over expression in a list */
  93891. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  93892. pItem->iAlias = 0;
  93893. }
  93894. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  93895. pItem->iAlias = 0;
  93896. }
  93897. if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
  93898. }else{
  93899. p->nSelectRow = (double)1;
  93900. }
  93901. /* Create a label to jump to when we want to abort the query */
  93902. addrEnd = sqlite3VdbeMakeLabel(v);
  93903. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  93904. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  93905. ** SELECT statement.
  93906. */
  93907. memset(&sNC, 0, sizeof(sNC));
  93908. sNC.pParse = pParse;
  93909. sNC.pSrcList = pTabList;
  93910. sNC.pAggInfo = &sAggInfo;
  93911. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  93912. sAggInfo.pGroupBy = pGroupBy;
  93913. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  93914. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  93915. if( pHaving ){
  93916. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  93917. }
  93918. sAggInfo.nAccumulator = sAggInfo.nColumn;
  93919. for(i=0; i<sAggInfo.nFunc; i++){
  93920. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  93921. sNC.ncFlags |= NC_InAggFunc;
  93922. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  93923. sNC.ncFlags &= ~NC_InAggFunc;
  93924. }
  93925. if( db->mallocFailed ) goto select_end;
  93926. /* Processing for aggregates with GROUP BY is very different and
  93927. ** much more complex than aggregates without a GROUP BY.
  93928. */
  93929. if( pGroupBy ){
  93930. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  93931. int j1; /* A-vs-B comparision jump */
  93932. int addrOutputRow; /* Start of subroutine that outputs a result row */
  93933. int regOutputRow; /* Return address register for output subroutine */
  93934. int addrSetAbort; /* Set the abort flag and return */
  93935. int addrTopOfLoop; /* Top of the input loop */
  93936. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  93937. int addrReset; /* Subroutine for resetting the accumulator */
  93938. int regReset; /* Return address register for reset subroutine */
  93939. /* If there is a GROUP BY clause we might need a sorting index to
  93940. ** implement it. Allocate that sorting index now. If it turns out
  93941. ** that we do not need it after all, the OP_SorterOpen instruction
  93942. ** will be converted into a Noop.
  93943. */
  93944. sAggInfo.sortingIdx = pParse->nTab++;
  93945. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  93946. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  93947. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  93948. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  93949. /* Initialize memory locations used by GROUP BY aggregate processing
  93950. */
  93951. iUseFlag = ++pParse->nMem;
  93952. iAbortFlag = ++pParse->nMem;
  93953. regOutputRow = ++pParse->nMem;
  93954. addrOutputRow = sqlite3VdbeMakeLabel(v);
  93955. regReset = ++pParse->nMem;
  93956. addrReset = sqlite3VdbeMakeLabel(v);
  93957. iAMem = pParse->nMem + 1;
  93958. pParse->nMem += pGroupBy->nExpr;
  93959. iBMem = pParse->nMem + 1;
  93960. pParse->nMem += pGroupBy->nExpr;
  93961. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  93962. VdbeComment((v, "clear abort flag"));
  93963. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  93964. VdbeComment((v, "indicate accumulator empty"));
  93965. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  93966. /* Begin a loop that will extract all source rows in GROUP BY order.
  93967. ** This might involve two separate loops with an OP_Sort in between, or
  93968. ** it might be a single loop that uses an index to extract information
  93969. ** in the right order to begin with.
  93970. */
  93971. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  93972. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
  93973. if( pWInfo==0 ) goto select_end;
  93974. if( pWInfo->nOBSat==pGroupBy->nExpr ){
  93975. /* The optimizer is able to deliver rows in group by order so
  93976. ** we do not have to sort. The OP_OpenEphemeral table will be
  93977. ** cancelled later because we still need to use the pKeyInfo
  93978. */
  93979. groupBySort = 0;
  93980. }else{
  93981. /* Rows are coming out in undetermined order. We have to push
  93982. ** each row into a sorting index, terminate the first loop,
  93983. ** then loop over the sorting index in order to get the output
  93984. ** in sorted order
  93985. */
  93986. int regBase;
  93987. int regRecord;
  93988. int nCol;
  93989. int nGroupBy;
  93990. explainTempTable(pParse,
  93991. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  93992. "DISTINCT" : "GROUP BY");
  93993. groupBySort = 1;
  93994. nGroupBy = pGroupBy->nExpr;
  93995. nCol = nGroupBy + 1;
  93996. j = nGroupBy+1;
  93997. for(i=0; i<sAggInfo.nColumn; i++){
  93998. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  93999. nCol++;
  94000. j++;
  94001. }
  94002. }
  94003. regBase = sqlite3GetTempRange(pParse, nCol);
  94004. sqlite3ExprCacheClear(pParse);
  94005. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  94006. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  94007. j = nGroupBy+1;
  94008. for(i=0; i<sAggInfo.nColumn; i++){
  94009. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  94010. if( pCol->iSorterColumn>=j ){
  94011. int r1 = j + regBase;
  94012. int r2;
  94013. r2 = sqlite3ExprCodeGetColumn(pParse,
  94014. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  94015. if( r1!=r2 ){
  94016. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  94017. }
  94018. j++;
  94019. }
  94020. }
  94021. regRecord = sqlite3GetTempReg(pParse);
  94022. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  94023. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  94024. sqlite3ReleaseTempReg(pParse, regRecord);
  94025. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  94026. sqlite3WhereEnd(pWInfo);
  94027. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  94028. sortOut = sqlite3GetTempReg(pParse);
  94029. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  94030. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  94031. VdbeComment((v, "GROUP BY sort"));
  94032. sAggInfo.useSortingIdx = 1;
  94033. sqlite3ExprCacheClear(pParse);
  94034. }
  94035. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  94036. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  94037. ** Then compare the current GROUP BY terms against the GROUP BY terms
  94038. ** from the previous row currently stored in a0, a1, a2...
  94039. */
  94040. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  94041. sqlite3ExprCacheClear(pParse);
  94042. if( groupBySort ){
  94043. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  94044. }
  94045. for(j=0; j<pGroupBy->nExpr; j++){
  94046. if( groupBySort ){
  94047. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  94048. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  94049. }else{
  94050. sAggInfo.directMode = 1;
  94051. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  94052. }
  94053. }
  94054. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  94055. (char*)pKeyInfo, P4_KEYINFO);
  94056. j1 = sqlite3VdbeCurrentAddr(v);
  94057. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  94058. /* Generate code that runs whenever the GROUP BY changes.
  94059. ** Changes in the GROUP BY are detected by the previous code
  94060. ** block. If there were no changes, this block is skipped.
  94061. **
  94062. ** This code copies current group by terms in b0,b1,b2,...
  94063. ** over to a0,a1,a2. It then calls the output subroutine
  94064. ** and resets the aggregate accumulator registers in preparation
  94065. ** for the next GROUP BY batch.
  94066. */
  94067. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  94068. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  94069. VdbeComment((v, "output one row"));
  94070. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  94071. VdbeComment((v, "check abort flag"));
  94072. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  94073. VdbeComment((v, "reset accumulator"));
  94074. /* Update the aggregate accumulators based on the content of
  94075. ** the current row
  94076. */
  94077. sqlite3VdbeJumpHere(v, j1);
  94078. updateAccumulator(pParse, &sAggInfo);
  94079. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  94080. VdbeComment((v, "indicate data in accumulator"));
  94081. /* End of the loop
  94082. */
  94083. if( groupBySort ){
  94084. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  94085. }else{
  94086. sqlite3WhereEnd(pWInfo);
  94087. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  94088. }
  94089. /* Output the final row of result
  94090. */
  94091. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  94092. VdbeComment((v, "output final row"));
  94093. /* Jump over the subroutines
  94094. */
  94095. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  94096. /* Generate a subroutine that outputs a single row of the result
  94097. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  94098. ** is less than or equal to zero, the subroutine is a no-op. If
  94099. ** the processing calls for the query to abort, this subroutine
  94100. ** increments the iAbortFlag memory location before returning in
  94101. ** order to signal the caller to abort.
  94102. */
  94103. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  94104. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  94105. VdbeComment((v, "set abort flag"));
  94106. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  94107. sqlite3VdbeResolveLabel(v, addrOutputRow);
  94108. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  94109. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  94110. VdbeComment((v, "Groupby result generator entry point"));
  94111. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  94112. finalizeAggFunctions(pParse, &sAggInfo);
  94113. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  94114. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  94115. &sDistinct, pDest,
  94116. addrOutputRow+1, addrSetAbort);
  94117. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  94118. VdbeComment((v, "end groupby result generator"));
  94119. /* Generate a subroutine that will reset the group-by accumulator
  94120. */
  94121. sqlite3VdbeResolveLabel(v, addrReset);
  94122. resetAccumulator(pParse, &sAggInfo);
  94123. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  94124. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  94125. else {
  94126. ExprList *pDel = 0;
  94127. #ifndef SQLITE_OMIT_BTREECOUNT
  94128. Table *pTab;
  94129. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  94130. /* If isSimpleCount() returns a pointer to a Table structure, then
  94131. ** the SQL statement is of the form:
  94132. **
  94133. ** SELECT count(*) FROM <tbl>
  94134. **
  94135. ** where the Table structure returned represents table <tbl>.
  94136. **
  94137. ** This statement is so common that it is optimized specially. The
  94138. ** OP_Count instruction is executed either on the intkey table that
  94139. ** contains the data for table <tbl> or on one of its indexes. It
  94140. ** is better to execute the op on an index, as indexes are almost
  94141. ** always spread across less pages than their corresponding tables.
  94142. */
  94143. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  94144. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  94145. Index *pIdx; /* Iterator variable */
  94146. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  94147. Index *pBest = 0; /* Best index found so far */
  94148. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  94149. sqlite3CodeVerifySchema(pParse, iDb);
  94150. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  94151. /* Search for the index that has the least amount of columns. If
  94152. ** there is such an index, and it has less columns than the table
  94153. ** does, then we can assume that it consumes less space on disk and
  94154. ** will therefore be cheaper to scan to determine the query result.
  94155. ** In this case set iRoot to the root page number of the index b-tree
  94156. ** and pKeyInfo to the KeyInfo structure required to navigate the
  94157. ** index.
  94158. **
  94159. ** (2011-04-15) Do not do a full scan of an unordered index.
  94160. **
  94161. ** In practice the KeyInfo structure will not be used. It is only
  94162. ** passed to keep OP_OpenRead happy.
  94163. */
  94164. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  94165. if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
  94166. pBest = pIdx;
  94167. }
  94168. }
  94169. if( pBest && pBest->nColumn<pTab->nCol ){
  94170. iRoot = pBest->tnum;
  94171. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  94172. }
  94173. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  94174. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  94175. if( pKeyInfo ){
  94176. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  94177. }
  94178. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  94179. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  94180. explainSimpleCount(pParse, pTab, pBest);
  94181. }else
  94182. #endif /* SQLITE_OMIT_BTREECOUNT */
  94183. {
  94184. /* Check if the query is of one of the following forms:
  94185. **
  94186. ** SELECT min(x) FROM ...
  94187. ** SELECT max(x) FROM ...
  94188. **
  94189. ** If it is, then ask the code in where.c to attempt to sort results
  94190. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  94191. ** If where.c is able to produce results sorted in this order, then
  94192. ** add vdbe code to break out of the processing loop after the
  94193. ** first iteration (since the first iteration of the loop is
  94194. ** guaranteed to operate on the row with the minimum or maximum
  94195. ** value of x, the only row required).
  94196. **
  94197. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  94198. ** modify behavior as follows:
  94199. **
  94200. ** + If the query is a "SELECT min(x)", then the loop coded by
  94201. ** where.c should not iterate over any values with a NULL value
  94202. ** for x.
  94203. **
  94204. ** + The optimizer code in where.c (the thing that decides which
  94205. ** index or indices to use) should place a different priority on
  94206. ** satisfying the 'ORDER BY' clause than it does in other cases.
  94207. ** Refer to code and comments in where.c for details.
  94208. */
  94209. ExprList *pMinMax = 0;
  94210. u8 flag = WHERE_ORDERBY_NORMAL;
  94211. assert( p->pGroupBy==0 );
  94212. assert( flag==0 );
  94213. if( p->pHaving==0 ){
  94214. flag = minMaxQuery(&sAggInfo, &pMinMax);
  94215. }
  94216. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  94217. if( flag ){
  94218. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  94219. pDel = pMinMax;
  94220. if( pMinMax && !db->mallocFailed ){
  94221. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  94222. pMinMax->a[0].pExpr->op = TK_COLUMN;
  94223. }
  94224. }
  94225. /* This case runs if the aggregate has no GROUP BY clause. The
  94226. ** processing is much simpler since there is only a single row
  94227. ** of output.
  94228. */
  94229. resetAccumulator(pParse, &sAggInfo);
  94230. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  94231. if( pWInfo==0 ){
  94232. sqlite3ExprListDelete(db, pDel);
  94233. goto select_end;
  94234. }
  94235. updateAccumulator(pParse, &sAggInfo);
  94236. assert( pMinMax==0 || pMinMax->nExpr==1 );
  94237. if( pWInfo->nOBSat>0 ){
  94238. sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  94239. VdbeComment((v, "%s() by index",
  94240. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  94241. }
  94242. sqlite3WhereEnd(pWInfo);
  94243. finalizeAggFunctions(pParse, &sAggInfo);
  94244. }
  94245. pOrderBy = 0;
  94246. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  94247. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  94248. pDest, addrEnd, addrEnd);
  94249. sqlite3ExprListDelete(db, pDel);
  94250. }
  94251. sqlite3VdbeResolveLabel(v, addrEnd);
  94252. } /* endif aggregate query */
  94253. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  94254. explainTempTable(pParse, "DISTINCT");
  94255. }
  94256. /* If there is an ORDER BY clause, then we need to sort the results
  94257. ** and send them to the callback one by one.
  94258. */
  94259. if( pOrderBy ){
  94260. explainTempTable(pParse, "ORDER BY");
  94261. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  94262. }
  94263. /* Jump here to skip this query
  94264. */
  94265. sqlite3VdbeResolveLabel(v, iEnd);
  94266. /* The SELECT was successfully coded. Set the return code to 0
  94267. ** to indicate no errors.
  94268. */
  94269. rc = 0;
  94270. /* Control jumps to here if an error is encountered above, or upon
  94271. ** successful coding of the SELECT.
  94272. */
  94273. select_end:
  94274. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  94275. /* Identify column names if results of the SELECT are to be output.
  94276. */
  94277. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  94278. generateColumnNames(pParse, pTabList, pEList);
  94279. }
  94280. sqlite3DbFree(db, sAggInfo.aCol);
  94281. sqlite3DbFree(db, sAggInfo.aFunc);
  94282. return rc;
  94283. }
  94284. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  94285. /*
  94286. ** Generate a human-readable description of a the Select object.
  94287. */
  94288. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  94289. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  94290. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  94291. if( p->selFlags & SF_Distinct ){
  94292. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  94293. }
  94294. if( p->selFlags & SF_Aggregate ){
  94295. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  94296. }
  94297. sqlite3ExplainNL(pVdbe);
  94298. sqlite3ExplainPrintf(pVdbe, " ");
  94299. }
  94300. sqlite3ExplainExprList(pVdbe, p->pEList);
  94301. sqlite3ExplainNL(pVdbe);
  94302. if( p->pSrc && p->pSrc->nSrc ){
  94303. int i;
  94304. sqlite3ExplainPrintf(pVdbe, "FROM ");
  94305. sqlite3ExplainPush(pVdbe);
  94306. for(i=0; i<p->pSrc->nSrc; i++){
  94307. struct SrcList_item *pItem = &p->pSrc->a[i];
  94308. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  94309. if( pItem->pSelect ){
  94310. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  94311. if( pItem->pTab ){
  94312. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  94313. }
  94314. }else if( pItem->zName ){
  94315. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  94316. }
  94317. if( pItem->zAlias ){
  94318. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  94319. }
  94320. if( pItem->jointype & JT_LEFT ){
  94321. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  94322. }
  94323. sqlite3ExplainNL(pVdbe);
  94324. }
  94325. sqlite3ExplainPop(pVdbe);
  94326. }
  94327. if( p->pWhere ){
  94328. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  94329. sqlite3ExplainExpr(pVdbe, p->pWhere);
  94330. sqlite3ExplainNL(pVdbe);
  94331. }
  94332. if( p->pGroupBy ){
  94333. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  94334. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  94335. sqlite3ExplainNL(pVdbe);
  94336. }
  94337. if( p->pHaving ){
  94338. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  94339. sqlite3ExplainExpr(pVdbe, p->pHaving);
  94340. sqlite3ExplainNL(pVdbe);
  94341. }
  94342. if( p->pOrderBy ){
  94343. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  94344. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  94345. sqlite3ExplainNL(pVdbe);
  94346. }
  94347. if( p->pLimit ){
  94348. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  94349. sqlite3ExplainExpr(pVdbe, p->pLimit);
  94350. sqlite3ExplainNL(pVdbe);
  94351. }
  94352. if( p->pOffset ){
  94353. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  94354. sqlite3ExplainExpr(pVdbe, p->pOffset);
  94355. sqlite3ExplainNL(pVdbe);
  94356. }
  94357. }
  94358. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  94359. if( p==0 ){
  94360. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  94361. return;
  94362. }
  94363. while( p->pPrior ){
  94364. p->pPrior->pNext = p;
  94365. p = p->pPrior;
  94366. }
  94367. sqlite3ExplainPush(pVdbe);
  94368. while( p ){
  94369. explainOneSelect(pVdbe, p);
  94370. p = p->pNext;
  94371. if( p==0 ) break;
  94372. sqlite3ExplainNL(pVdbe);
  94373. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  94374. }
  94375. sqlite3ExplainPrintf(pVdbe, "END");
  94376. sqlite3ExplainPop(pVdbe);
  94377. }
  94378. /* End of the structure debug printing code
  94379. *****************************************************************************/
  94380. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  94381. /************** End of select.c **********************************************/
  94382. /************** Begin file table.c *******************************************/
  94383. /*
  94384. ** 2001 September 15
  94385. **
  94386. ** The author disclaims copyright to this source code. In place of
  94387. ** a legal notice, here is a blessing:
  94388. **
  94389. ** May you do good and not evil.
  94390. ** May you find forgiveness for yourself and forgive others.
  94391. ** May you share freely, never taking more than you give.
  94392. **
  94393. *************************************************************************
  94394. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  94395. ** interface routines. These are just wrappers around the main
  94396. ** interface routine of sqlite3_exec().
  94397. **
  94398. ** These routines are in a separate files so that they will not be linked
  94399. ** if they are not used.
  94400. */
  94401. /* #include <stdlib.h> */
  94402. /* #include <string.h> */
  94403. #ifndef SQLITE_OMIT_GET_TABLE
  94404. /*
  94405. ** This structure is used to pass data from sqlite3_get_table() through
  94406. ** to the callback function is uses to build the result.
  94407. */
  94408. typedef struct TabResult {
  94409. char **azResult; /* Accumulated output */
  94410. char *zErrMsg; /* Error message text, if an error occurs */
  94411. int nAlloc; /* Slots allocated for azResult[] */
  94412. int nRow; /* Number of rows in the result */
  94413. int nColumn; /* Number of columns in the result */
  94414. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  94415. int rc; /* Return code from sqlite3_exec() */
  94416. } TabResult;
  94417. /*
  94418. ** This routine is called once for each row in the result table. Its job
  94419. ** is to fill in the TabResult structure appropriately, allocating new
  94420. ** memory as necessary.
  94421. */
  94422. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  94423. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  94424. int need; /* Slots needed in p->azResult[] */
  94425. int i; /* Loop counter */
  94426. char *z; /* A single column of result */
  94427. /* Make sure there is enough space in p->azResult to hold everything
  94428. ** we need to remember from this invocation of the callback.
  94429. */
  94430. if( p->nRow==0 && argv!=0 ){
  94431. need = nCol*2;
  94432. }else{
  94433. need = nCol;
  94434. }
  94435. if( p->nData + need > p->nAlloc ){
  94436. char **azNew;
  94437. p->nAlloc = p->nAlloc*2 + need;
  94438. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  94439. if( azNew==0 ) goto malloc_failed;
  94440. p->azResult = azNew;
  94441. }
  94442. /* If this is the first row, then generate an extra row containing
  94443. ** the names of all columns.
  94444. */
  94445. if( p->nRow==0 ){
  94446. p->nColumn = nCol;
  94447. for(i=0; i<nCol; i++){
  94448. z = sqlite3_mprintf("%s", colv[i]);
  94449. if( z==0 ) goto malloc_failed;
  94450. p->azResult[p->nData++] = z;
  94451. }
  94452. }else if( p->nColumn!=nCol ){
  94453. sqlite3_free(p->zErrMsg);
  94454. p->zErrMsg = sqlite3_mprintf(
  94455. "sqlite3_get_table() called with two or more incompatible queries"
  94456. );
  94457. p->rc = SQLITE_ERROR;
  94458. return 1;
  94459. }
  94460. /* Copy over the row data
  94461. */
  94462. if( argv!=0 ){
  94463. for(i=0; i<nCol; i++){
  94464. if( argv[i]==0 ){
  94465. z = 0;
  94466. }else{
  94467. int n = sqlite3Strlen30(argv[i])+1;
  94468. z = sqlite3_malloc( n );
  94469. if( z==0 ) goto malloc_failed;
  94470. memcpy(z, argv[i], n);
  94471. }
  94472. p->azResult[p->nData++] = z;
  94473. }
  94474. p->nRow++;
  94475. }
  94476. return 0;
  94477. malloc_failed:
  94478. p->rc = SQLITE_NOMEM;
  94479. return 1;
  94480. }
  94481. /*
  94482. ** Query the database. But instead of invoking a callback for each row,
  94483. ** malloc() for space to hold the result and return the entire results
  94484. ** at the conclusion of the call.
  94485. **
  94486. ** The result that is written to ***pazResult is held in memory obtained
  94487. ** from malloc(). But the caller cannot free this memory directly.
  94488. ** Instead, the entire table should be passed to sqlite3_free_table() when
  94489. ** the calling procedure is finished using it.
  94490. */
  94491. SQLITE_API int sqlite3_get_table(
  94492. sqlite3 *db, /* The database on which the SQL executes */
  94493. const char *zSql, /* The SQL to be executed */
  94494. char ***pazResult, /* Write the result table here */
  94495. int *pnRow, /* Write the number of rows in the result here */
  94496. int *pnColumn, /* Write the number of columns of result here */
  94497. char **pzErrMsg /* Write error messages here */
  94498. ){
  94499. int rc;
  94500. TabResult res;
  94501. *pazResult = 0;
  94502. if( pnColumn ) *pnColumn = 0;
  94503. if( pnRow ) *pnRow = 0;
  94504. if( pzErrMsg ) *pzErrMsg = 0;
  94505. res.zErrMsg = 0;
  94506. res.nRow = 0;
  94507. res.nColumn = 0;
  94508. res.nData = 1;
  94509. res.nAlloc = 20;
  94510. res.rc = SQLITE_OK;
  94511. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  94512. if( res.azResult==0 ){
  94513. db->errCode = SQLITE_NOMEM;
  94514. return SQLITE_NOMEM;
  94515. }
  94516. res.azResult[0] = 0;
  94517. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  94518. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  94519. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  94520. if( (rc&0xff)==SQLITE_ABORT ){
  94521. sqlite3_free_table(&res.azResult[1]);
  94522. if( res.zErrMsg ){
  94523. if( pzErrMsg ){
  94524. sqlite3_free(*pzErrMsg);
  94525. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  94526. }
  94527. sqlite3_free(res.zErrMsg);
  94528. }
  94529. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  94530. return res.rc;
  94531. }
  94532. sqlite3_free(res.zErrMsg);
  94533. if( rc!=SQLITE_OK ){
  94534. sqlite3_free_table(&res.azResult[1]);
  94535. return rc;
  94536. }
  94537. if( res.nAlloc>res.nData ){
  94538. char **azNew;
  94539. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  94540. if( azNew==0 ){
  94541. sqlite3_free_table(&res.azResult[1]);
  94542. db->errCode = SQLITE_NOMEM;
  94543. return SQLITE_NOMEM;
  94544. }
  94545. res.azResult = azNew;
  94546. }
  94547. *pazResult = &res.azResult[1];
  94548. if( pnColumn ) *pnColumn = res.nColumn;
  94549. if( pnRow ) *pnRow = res.nRow;
  94550. return rc;
  94551. }
  94552. /*
  94553. ** This routine frees the space the sqlite3_get_table() malloced.
  94554. */
  94555. SQLITE_API void sqlite3_free_table(
  94556. char **azResult /* Result returned from from sqlite3_get_table() */
  94557. ){
  94558. if( azResult ){
  94559. int i, n;
  94560. azResult--;
  94561. assert( azResult!=0 );
  94562. n = SQLITE_PTR_TO_INT(azResult[0]);
  94563. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  94564. sqlite3_free(azResult);
  94565. }
  94566. }
  94567. #endif /* SQLITE_OMIT_GET_TABLE */
  94568. /************** End of table.c ***********************************************/
  94569. /************** Begin file trigger.c *****************************************/
  94570. /*
  94571. **
  94572. ** The author disclaims copyright to this source code. In place of
  94573. ** a legal notice, here is a blessing:
  94574. **
  94575. ** May you do good and not evil.
  94576. ** May you find forgiveness for yourself and forgive others.
  94577. ** May you share freely, never taking more than you give.
  94578. **
  94579. *************************************************************************
  94580. ** This file contains the implementation for TRIGGERs
  94581. */
  94582. #ifndef SQLITE_OMIT_TRIGGER
  94583. /*
  94584. ** Delete a linked list of TriggerStep structures.
  94585. */
  94586. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  94587. while( pTriggerStep ){
  94588. TriggerStep * pTmp = pTriggerStep;
  94589. pTriggerStep = pTriggerStep->pNext;
  94590. sqlite3ExprDelete(db, pTmp->pWhere);
  94591. sqlite3ExprListDelete(db, pTmp->pExprList);
  94592. sqlite3SelectDelete(db, pTmp->pSelect);
  94593. sqlite3IdListDelete(db, pTmp->pIdList);
  94594. sqlite3DbFree(db, pTmp);
  94595. }
  94596. }
  94597. /*
  94598. ** Given table pTab, return a list of all the triggers attached to
  94599. ** the table. The list is connected by Trigger.pNext pointers.
  94600. **
  94601. ** All of the triggers on pTab that are in the same database as pTab
  94602. ** are already attached to pTab->pTrigger. But there might be additional
  94603. ** triggers on pTab in the TEMP schema. This routine prepends all
  94604. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  94605. ** and returns the combined list.
  94606. **
  94607. ** To state it another way: This routine returns a list of all triggers
  94608. ** that fire off of pTab. The list will include any TEMP triggers on
  94609. ** pTab as well as the triggers lised in pTab->pTrigger.
  94610. */
  94611. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  94612. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  94613. Trigger *pList = 0; /* List of triggers to return */
  94614. if( pParse->disableTriggers ){
  94615. return 0;
  94616. }
  94617. if( pTmpSchema!=pTab->pSchema ){
  94618. HashElem *p;
  94619. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  94620. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  94621. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  94622. if( pTrig->pTabSchema==pTab->pSchema
  94623. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  94624. ){
  94625. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  94626. pList = pTrig;
  94627. }
  94628. }
  94629. }
  94630. return (pList ? pList : pTab->pTrigger);
  94631. }
  94632. /*
  94633. ** This is called by the parser when it sees a CREATE TRIGGER statement
  94634. ** up to the point of the BEGIN before the trigger actions. A Trigger
  94635. ** structure is generated based on the information available and stored
  94636. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  94637. ** sqlite3FinishTrigger() function is called to complete the trigger
  94638. ** construction process.
  94639. */
  94640. SQLITE_PRIVATE void sqlite3BeginTrigger(
  94641. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  94642. Token *pName1, /* The name of the trigger */
  94643. Token *pName2, /* The name of the trigger */
  94644. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  94645. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  94646. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  94647. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  94648. Expr *pWhen, /* WHEN clause */
  94649. int isTemp, /* True if the TEMPORARY keyword is present */
  94650. int noErr /* Suppress errors if the trigger already exists */
  94651. ){
  94652. Trigger *pTrigger = 0; /* The new trigger */
  94653. Table *pTab; /* Table that the trigger fires off of */
  94654. char *zName = 0; /* Name of the trigger */
  94655. sqlite3 *db = pParse->db; /* The database connection */
  94656. int iDb; /* The database to store the trigger in */
  94657. Token *pName; /* The unqualified db name */
  94658. DbFixer sFix; /* State vector for the DB fixer */
  94659. int iTabDb; /* Index of the database holding pTab */
  94660. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  94661. assert( pName2!=0 );
  94662. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  94663. assert( op>0 && op<0xff );
  94664. if( isTemp ){
  94665. /* If TEMP was specified, then the trigger name may not be qualified. */
  94666. if( pName2->n>0 ){
  94667. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  94668. goto trigger_cleanup;
  94669. }
  94670. iDb = 1;
  94671. pName = pName1;
  94672. }else{
  94673. /* Figure out the db that the trigger will be created in */
  94674. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  94675. if( iDb<0 ){
  94676. goto trigger_cleanup;
  94677. }
  94678. }
  94679. if( !pTableName || db->mallocFailed ){
  94680. goto trigger_cleanup;
  94681. }
  94682. /* A long-standing parser bug is that this syntax was allowed:
  94683. **
  94684. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  94685. ** ^^^^^^^^
  94686. **
  94687. ** To maintain backwards compatibility, ignore the database
  94688. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  94689. */
  94690. if( db->init.busy && iDb!=1 ){
  94691. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  94692. pTableName->a[0].zDatabase = 0;
  94693. }
  94694. /* If the trigger name was unqualified, and the table is a temp table,
  94695. ** then set iDb to 1 to create the trigger in the temporary database.
  94696. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  94697. ** exist, the error is caught by the block below.
  94698. */
  94699. pTab = sqlite3SrcListLookup(pParse, pTableName);
  94700. if( db->init.busy==0 && pName2->n==0 && pTab
  94701. && pTab->pSchema==db->aDb[1].pSchema ){
  94702. iDb = 1;
  94703. }
  94704. /* Ensure the table name matches database name and that the table exists */
  94705. if( db->mallocFailed ) goto trigger_cleanup;
  94706. assert( pTableName->nSrc==1 );
  94707. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
  94708. sqlite3FixSrcList(&sFix, pTableName) ){
  94709. goto trigger_cleanup;
  94710. }
  94711. pTab = sqlite3SrcListLookup(pParse, pTableName);
  94712. if( !pTab ){
  94713. /* The table does not exist. */
  94714. if( db->init.iDb==1 ){
  94715. /* Ticket #3810.
  94716. ** Normally, whenever a table is dropped, all associated triggers are
  94717. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  94718. ** and the table is dropped by a different database connection, the
  94719. ** trigger is not visible to the database connection that does the
  94720. ** drop so the trigger cannot be dropped. This results in an
  94721. ** "orphaned trigger" - a trigger whose associated table is missing.
  94722. */
  94723. db->init.orphanTrigger = 1;
  94724. }
  94725. goto trigger_cleanup;
  94726. }
  94727. if( IsVirtual(pTab) ){
  94728. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  94729. goto trigger_cleanup;
  94730. }
  94731. /* Check that the trigger name is not reserved and that no trigger of the
  94732. ** specified name exists */
  94733. zName = sqlite3NameFromToken(db, pName);
  94734. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  94735. goto trigger_cleanup;
  94736. }
  94737. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94738. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  94739. zName, sqlite3Strlen30(zName)) ){
  94740. if( !noErr ){
  94741. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  94742. }else{
  94743. assert( !db->init.busy );
  94744. sqlite3CodeVerifySchema(pParse, iDb);
  94745. }
  94746. goto trigger_cleanup;
  94747. }
  94748. /* Do not create a trigger on a system table */
  94749. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  94750. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  94751. pParse->nErr++;
  94752. goto trigger_cleanup;
  94753. }
  94754. /* INSTEAD of triggers are only for views and views only support INSTEAD
  94755. ** of triggers.
  94756. */
  94757. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  94758. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  94759. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  94760. goto trigger_cleanup;
  94761. }
  94762. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  94763. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  94764. " trigger on table: %S", pTableName, 0);
  94765. goto trigger_cleanup;
  94766. }
  94767. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  94768. #ifndef SQLITE_OMIT_AUTHORIZATION
  94769. {
  94770. int code = SQLITE_CREATE_TRIGGER;
  94771. const char *zDb = db->aDb[iTabDb].zName;
  94772. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  94773. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  94774. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  94775. goto trigger_cleanup;
  94776. }
  94777. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  94778. goto trigger_cleanup;
  94779. }
  94780. }
  94781. #endif
  94782. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  94783. ** cannot appear on views. So we might as well translate every
  94784. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  94785. ** elsewhere.
  94786. */
  94787. if (tr_tm == TK_INSTEAD){
  94788. tr_tm = TK_BEFORE;
  94789. }
  94790. /* Build the Trigger object */
  94791. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  94792. if( pTrigger==0 ) goto trigger_cleanup;
  94793. pTrigger->zName = zName;
  94794. zName = 0;
  94795. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  94796. pTrigger->pSchema = db->aDb[iDb].pSchema;
  94797. pTrigger->pTabSchema = pTab->pSchema;
  94798. pTrigger->op = (u8)op;
  94799. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  94800. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  94801. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  94802. assert( pParse->pNewTrigger==0 );
  94803. pParse->pNewTrigger = pTrigger;
  94804. trigger_cleanup:
  94805. sqlite3DbFree(db, zName);
  94806. sqlite3SrcListDelete(db, pTableName);
  94807. sqlite3IdListDelete(db, pColumns);
  94808. sqlite3ExprDelete(db, pWhen);
  94809. if( !pParse->pNewTrigger ){
  94810. sqlite3DeleteTrigger(db, pTrigger);
  94811. }else{
  94812. assert( pParse->pNewTrigger==pTrigger );
  94813. }
  94814. }
  94815. /*
  94816. ** This routine is called after all of the trigger actions have been parsed
  94817. ** in order to complete the process of building the trigger.
  94818. */
  94819. SQLITE_PRIVATE void sqlite3FinishTrigger(
  94820. Parse *pParse, /* Parser context */
  94821. TriggerStep *pStepList, /* The triggered program */
  94822. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  94823. ){
  94824. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  94825. char *zName; /* Name of trigger */
  94826. sqlite3 *db = pParse->db; /* The database */
  94827. DbFixer sFix; /* Fixer object */
  94828. int iDb; /* Database containing the trigger */
  94829. Token nameToken; /* Trigger name for error reporting */
  94830. pParse->pNewTrigger = 0;
  94831. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  94832. zName = pTrig->zName;
  94833. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  94834. pTrig->step_list = pStepList;
  94835. while( pStepList ){
  94836. pStepList->pTrig = pTrig;
  94837. pStepList = pStepList->pNext;
  94838. }
  94839. nameToken.z = pTrig->zName;
  94840. nameToken.n = sqlite3Strlen30(nameToken.z);
  94841. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
  94842. && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
  94843. goto triggerfinish_cleanup;
  94844. }
  94845. /* if we are not initializing,
  94846. ** build the sqlite_master entry
  94847. */
  94848. if( !db->init.busy ){
  94849. Vdbe *v;
  94850. char *z;
  94851. /* Make an entry in the sqlite_master table */
  94852. v = sqlite3GetVdbe(pParse);
  94853. if( v==0 ) goto triggerfinish_cleanup;
  94854. sqlite3BeginWriteOperation(pParse, 0, iDb);
  94855. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  94856. sqlite3NestedParse(pParse,
  94857. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  94858. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  94859. pTrig->table, z);
  94860. sqlite3DbFree(db, z);
  94861. sqlite3ChangeCookie(pParse, iDb);
  94862. sqlite3VdbeAddParseSchemaOp(v, iDb,
  94863. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  94864. }
  94865. if( db->init.busy ){
  94866. Trigger *pLink = pTrig;
  94867. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  94868. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94869. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  94870. if( pTrig ){
  94871. db->mallocFailed = 1;
  94872. }else if( pLink->pSchema==pLink->pTabSchema ){
  94873. Table *pTab;
  94874. int n = sqlite3Strlen30(pLink->table);
  94875. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  94876. assert( pTab!=0 );
  94877. pLink->pNext = pTab->pTrigger;
  94878. pTab->pTrigger = pLink;
  94879. }
  94880. }
  94881. triggerfinish_cleanup:
  94882. sqlite3DeleteTrigger(db, pTrig);
  94883. assert( !pParse->pNewTrigger );
  94884. sqlite3DeleteTriggerStep(db, pStepList);
  94885. }
  94886. /*
  94887. ** Turn a SELECT statement (that the pSelect parameter points to) into
  94888. ** a trigger step. Return a pointer to a TriggerStep structure.
  94889. **
  94890. ** The parser calls this routine when it finds a SELECT statement in
  94891. ** body of a TRIGGER.
  94892. */
  94893. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  94894. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  94895. if( pTriggerStep==0 ) {
  94896. sqlite3SelectDelete(db, pSelect);
  94897. return 0;
  94898. }
  94899. pTriggerStep->op = TK_SELECT;
  94900. pTriggerStep->pSelect = pSelect;
  94901. pTriggerStep->orconf = OE_Default;
  94902. return pTriggerStep;
  94903. }
  94904. /*
  94905. ** Allocate space to hold a new trigger step. The allocated space
  94906. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  94907. **
  94908. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  94909. */
  94910. static TriggerStep *triggerStepAllocate(
  94911. sqlite3 *db, /* Database connection */
  94912. u8 op, /* Trigger opcode */
  94913. Token *pName /* The target name */
  94914. ){
  94915. TriggerStep *pTriggerStep;
  94916. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  94917. if( pTriggerStep ){
  94918. char *z = (char*)&pTriggerStep[1];
  94919. memcpy(z, pName->z, pName->n);
  94920. pTriggerStep->target.z = z;
  94921. pTriggerStep->target.n = pName->n;
  94922. pTriggerStep->op = op;
  94923. }
  94924. return pTriggerStep;
  94925. }
  94926. /*
  94927. ** Build a trigger step out of an INSERT statement. Return a pointer
  94928. ** to the new trigger step.
  94929. **
  94930. ** The parser calls this routine when it sees an INSERT inside the
  94931. ** body of a trigger.
  94932. */
  94933. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  94934. sqlite3 *db, /* The database connection */
  94935. Token *pTableName, /* Name of the table into which we insert */
  94936. IdList *pColumn, /* List of columns in pTableName to insert into */
  94937. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  94938. Select *pSelect, /* A SELECT statement that supplies values */
  94939. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  94940. ){
  94941. TriggerStep *pTriggerStep;
  94942. assert(pEList == 0 || pSelect == 0);
  94943. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  94944. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  94945. if( pTriggerStep ){
  94946. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  94947. pTriggerStep->pIdList = pColumn;
  94948. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  94949. pTriggerStep->orconf = orconf;
  94950. }else{
  94951. sqlite3IdListDelete(db, pColumn);
  94952. }
  94953. sqlite3ExprListDelete(db, pEList);
  94954. sqlite3SelectDelete(db, pSelect);
  94955. return pTriggerStep;
  94956. }
  94957. /*
  94958. ** Construct a trigger step that implements an UPDATE statement and return
  94959. ** a pointer to that trigger step. The parser calls this routine when it
  94960. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  94961. */
  94962. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  94963. sqlite3 *db, /* The database connection */
  94964. Token *pTableName, /* Name of the table to be updated */
  94965. ExprList *pEList, /* The SET clause: list of column and new values */
  94966. Expr *pWhere, /* The WHERE clause */
  94967. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  94968. ){
  94969. TriggerStep *pTriggerStep;
  94970. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  94971. if( pTriggerStep ){
  94972. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  94973. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  94974. pTriggerStep->orconf = orconf;
  94975. }
  94976. sqlite3ExprListDelete(db, pEList);
  94977. sqlite3ExprDelete(db, pWhere);
  94978. return pTriggerStep;
  94979. }
  94980. /*
  94981. ** Construct a trigger step that implements a DELETE statement and return
  94982. ** a pointer to that trigger step. The parser calls this routine when it
  94983. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  94984. */
  94985. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  94986. sqlite3 *db, /* Database connection */
  94987. Token *pTableName, /* The table from which rows are deleted */
  94988. Expr *pWhere /* The WHERE clause */
  94989. ){
  94990. TriggerStep *pTriggerStep;
  94991. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  94992. if( pTriggerStep ){
  94993. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  94994. pTriggerStep->orconf = OE_Default;
  94995. }
  94996. sqlite3ExprDelete(db, pWhere);
  94997. return pTriggerStep;
  94998. }
  94999. /*
  95000. ** Recursively delete a Trigger structure
  95001. */
  95002. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  95003. if( pTrigger==0 ) return;
  95004. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  95005. sqlite3DbFree(db, pTrigger->zName);
  95006. sqlite3DbFree(db, pTrigger->table);
  95007. sqlite3ExprDelete(db, pTrigger->pWhen);
  95008. sqlite3IdListDelete(db, pTrigger->pColumns);
  95009. sqlite3DbFree(db, pTrigger);
  95010. }
  95011. /*
  95012. ** This function is called to drop a trigger from the database schema.
  95013. **
  95014. ** This may be called directly from the parser and therefore identifies
  95015. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  95016. ** same job as this routine except it takes a pointer to the trigger
  95017. ** instead of the trigger name.
  95018. **/
  95019. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  95020. Trigger *pTrigger = 0;
  95021. int i;
  95022. const char *zDb;
  95023. const char *zName;
  95024. int nName;
  95025. sqlite3 *db = pParse->db;
  95026. if( db->mallocFailed ) goto drop_trigger_cleanup;
  95027. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  95028. goto drop_trigger_cleanup;
  95029. }
  95030. assert( pName->nSrc==1 );
  95031. zDb = pName->a[0].zDatabase;
  95032. zName = pName->a[0].zName;
  95033. nName = sqlite3Strlen30(zName);
  95034. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  95035. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  95036. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  95037. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  95038. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  95039. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  95040. if( pTrigger ) break;
  95041. }
  95042. if( !pTrigger ){
  95043. if( !noErr ){
  95044. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  95045. }else{
  95046. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  95047. }
  95048. pParse->checkSchema = 1;
  95049. goto drop_trigger_cleanup;
  95050. }
  95051. sqlite3DropTriggerPtr(pParse, pTrigger);
  95052. drop_trigger_cleanup:
  95053. sqlite3SrcListDelete(db, pName);
  95054. }
  95055. /*
  95056. ** Return a pointer to the Table structure for the table that a trigger
  95057. ** is set on.
  95058. */
  95059. static Table *tableOfTrigger(Trigger *pTrigger){
  95060. int n = sqlite3Strlen30(pTrigger->table);
  95061. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  95062. }
  95063. /*
  95064. ** Drop a trigger given a pointer to that trigger.
  95065. */
  95066. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  95067. Table *pTable;
  95068. Vdbe *v;
  95069. sqlite3 *db = pParse->db;
  95070. int iDb;
  95071. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  95072. assert( iDb>=0 && iDb<db->nDb );
  95073. pTable = tableOfTrigger(pTrigger);
  95074. assert( pTable );
  95075. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  95076. #ifndef SQLITE_OMIT_AUTHORIZATION
  95077. {
  95078. int code = SQLITE_DROP_TRIGGER;
  95079. const char *zDb = db->aDb[iDb].zName;
  95080. const char *zTab = SCHEMA_TABLE(iDb);
  95081. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  95082. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  95083. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  95084. return;
  95085. }
  95086. }
  95087. #endif
  95088. /* Generate code to destroy the database record of the trigger.
  95089. */
  95090. assert( pTable!=0 );
  95091. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  95092. int base;
  95093. static const VdbeOpList dropTrigger[] = {
  95094. { OP_Rewind, 0, ADDR(9), 0},
  95095. { OP_String8, 0, 1, 0}, /* 1 */
  95096. { OP_Column, 0, 1, 2},
  95097. { OP_Ne, 2, ADDR(8), 1},
  95098. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  95099. { OP_Column, 0, 0, 2},
  95100. { OP_Ne, 2, ADDR(8), 1},
  95101. { OP_Delete, 0, 0, 0},
  95102. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  95103. };
  95104. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95105. sqlite3OpenMasterTable(pParse, iDb);
  95106. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  95107. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  95108. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  95109. sqlite3ChangeCookie(pParse, iDb);
  95110. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  95111. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  95112. if( pParse->nMem<3 ){
  95113. pParse->nMem = 3;
  95114. }
  95115. }
  95116. }
  95117. /*
  95118. ** Remove a trigger from the hash tables of the sqlite* pointer.
  95119. */
  95120. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  95121. Trigger *pTrigger;
  95122. Hash *pHash;
  95123. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95124. pHash = &(db->aDb[iDb].pSchema->trigHash);
  95125. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  95126. if( ALWAYS(pTrigger) ){
  95127. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  95128. Table *pTab = tableOfTrigger(pTrigger);
  95129. Trigger **pp;
  95130. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  95131. *pp = (*pp)->pNext;
  95132. }
  95133. sqlite3DeleteTrigger(db, pTrigger);
  95134. db->flags |= SQLITE_InternChanges;
  95135. }
  95136. }
  95137. /*
  95138. ** pEList is the SET clause of an UPDATE statement. Each entry
  95139. ** in pEList is of the format <id>=<expr>. If any of the entries
  95140. ** in pEList have an <id> which matches an identifier in pIdList,
  95141. ** then return TRUE. If pIdList==NULL, then it is considered a
  95142. ** wildcard that matches anything. Likewise if pEList==NULL then
  95143. ** it matches anything so always return true. Return false only
  95144. ** if there is no match.
  95145. */
  95146. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  95147. int e;
  95148. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  95149. for(e=0; e<pEList->nExpr; e++){
  95150. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  95151. }
  95152. return 0;
  95153. }
  95154. /*
  95155. ** Return a list of all triggers on table pTab if there exists at least
  95156. ** one trigger that must be fired when an operation of type 'op' is
  95157. ** performed on the table, and, if that operation is an UPDATE, if at
  95158. ** least one of the columns in pChanges is being modified.
  95159. */
  95160. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  95161. Parse *pParse, /* Parse context */
  95162. Table *pTab, /* The table the contains the triggers */
  95163. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  95164. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  95165. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  95166. ){
  95167. int mask = 0;
  95168. Trigger *pList = 0;
  95169. Trigger *p;
  95170. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  95171. pList = sqlite3TriggerList(pParse, pTab);
  95172. }
  95173. assert( pList==0 || IsVirtual(pTab)==0 );
  95174. for(p=pList; p; p=p->pNext){
  95175. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  95176. mask |= p->tr_tm;
  95177. }
  95178. }
  95179. if( pMask ){
  95180. *pMask = mask;
  95181. }
  95182. return (mask ? pList : 0);
  95183. }
  95184. /*
  95185. ** Convert the pStep->target token into a SrcList and return a pointer
  95186. ** to that SrcList.
  95187. **
  95188. ** This routine adds a specific database name, if needed, to the target when
  95189. ** forming the SrcList. This prevents a trigger in one database from
  95190. ** referring to a target in another database. An exception is when the
  95191. ** trigger is in TEMP in which case it can refer to any other database it
  95192. ** wants.
  95193. */
  95194. static SrcList *targetSrcList(
  95195. Parse *pParse, /* The parsing context */
  95196. TriggerStep *pStep /* The trigger containing the target token */
  95197. ){
  95198. int iDb; /* Index of the database to use */
  95199. SrcList *pSrc; /* SrcList to be returned */
  95200. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  95201. if( pSrc ){
  95202. assert( pSrc->nSrc>0 );
  95203. assert( pSrc->a!=0 );
  95204. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  95205. if( iDb==0 || iDb>=2 ){
  95206. sqlite3 *db = pParse->db;
  95207. assert( iDb<pParse->db->nDb );
  95208. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  95209. }
  95210. }
  95211. return pSrc;
  95212. }
  95213. /*
  95214. ** Generate VDBE code for the statements inside the body of a single
  95215. ** trigger.
  95216. */
  95217. static int codeTriggerProgram(
  95218. Parse *pParse, /* The parser context */
  95219. TriggerStep *pStepList, /* List of statements inside the trigger body */
  95220. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  95221. ){
  95222. TriggerStep *pStep;
  95223. Vdbe *v = pParse->pVdbe;
  95224. sqlite3 *db = pParse->db;
  95225. assert( pParse->pTriggerTab && pParse->pToplevel );
  95226. assert( pStepList );
  95227. assert( v!=0 );
  95228. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  95229. /* Figure out the ON CONFLICT policy that will be used for this step
  95230. ** of the trigger program. If the statement that caused this trigger
  95231. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  95232. ** the ON CONFLICT policy that was specified as part of the trigger
  95233. ** step statement. Example:
  95234. **
  95235. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  95236. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  95237. ** END;
  95238. **
  95239. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  95240. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  95241. */
  95242. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  95243. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  95244. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  95245. ** that it is not safe to refactor constants (this happens after the
  95246. ** start of the first loop in the SQL statement is coded - at that
  95247. ** point code may be conditionally executed, so it is no longer safe to
  95248. ** initialize constant register values). */
  95249. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  95250. pParse->cookieGoto = 0;
  95251. switch( pStep->op ){
  95252. case TK_UPDATE: {
  95253. sqlite3Update(pParse,
  95254. targetSrcList(pParse, pStep),
  95255. sqlite3ExprListDup(db, pStep->pExprList, 0),
  95256. sqlite3ExprDup(db, pStep->pWhere, 0),
  95257. pParse->eOrconf
  95258. );
  95259. break;
  95260. }
  95261. case TK_INSERT: {
  95262. sqlite3Insert(pParse,
  95263. targetSrcList(pParse, pStep),
  95264. sqlite3ExprListDup(db, pStep->pExprList, 0),
  95265. sqlite3SelectDup(db, pStep->pSelect, 0),
  95266. sqlite3IdListDup(db, pStep->pIdList),
  95267. pParse->eOrconf
  95268. );
  95269. break;
  95270. }
  95271. case TK_DELETE: {
  95272. sqlite3DeleteFrom(pParse,
  95273. targetSrcList(pParse, pStep),
  95274. sqlite3ExprDup(db, pStep->pWhere, 0)
  95275. );
  95276. break;
  95277. }
  95278. default: assert( pStep->op==TK_SELECT ); {
  95279. SelectDest sDest;
  95280. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  95281. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  95282. sqlite3Select(pParse, pSelect, &sDest);
  95283. sqlite3SelectDelete(db, pSelect);
  95284. break;
  95285. }
  95286. }
  95287. if( pStep->op!=TK_SELECT ){
  95288. sqlite3VdbeAddOp0(v, OP_ResetCount);
  95289. }
  95290. }
  95291. return 0;
  95292. }
  95293. #ifdef SQLITE_DEBUG
  95294. /*
  95295. ** This function is used to add VdbeComment() annotations to a VDBE
  95296. ** program. It is not used in production code, only for debugging.
  95297. */
  95298. static const char *onErrorText(int onError){
  95299. switch( onError ){
  95300. case OE_Abort: return "abort";
  95301. case OE_Rollback: return "rollback";
  95302. case OE_Fail: return "fail";
  95303. case OE_Replace: return "replace";
  95304. case OE_Ignore: return "ignore";
  95305. case OE_Default: return "default";
  95306. }
  95307. return "n/a";
  95308. }
  95309. #endif
  95310. /*
  95311. ** Parse context structure pFrom has just been used to create a sub-vdbe
  95312. ** (trigger program). If an error has occurred, transfer error information
  95313. ** from pFrom to pTo.
  95314. */
  95315. static void transferParseError(Parse *pTo, Parse *pFrom){
  95316. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  95317. assert( pTo->zErrMsg==0 || pTo->nErr );
  95318. if( pTo->nErr==0 ){
  95319. pTo->zErrMsg = pFrom->zErrMsg;
  95320. pTo->nErr = pFrom->nErr;
  95321. }else{
  95322. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  95323. }
  95324. }
  95325. /*
  95326. ** Create and populate a new TriggerPrg object with a sub-program
  95327. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  95328. */
  95329. static TriggerPrg *codeRowTrigger(
  95330. Parse *pParse, /* Current parse context */
  95331. Trigger *pTrigger, /* Trigger to code */
  95332. Table *pTab, /* The table pTrigger is attached to */
  95333. int orconf /* ON CONFLICT policy to code trigger program with */
  95334. ){
  95335. Parse *pTop = sqlite3ParseToplevel(pParse);
  95336. sqlite3 *db = pParse->db; /* Database handle */
  95337. TriggerPrg *pPrg; /* Value to return */
  95338. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  95339. Vdbe *v; /* Temporary VM */
  95340. NameContext sNC; /* Name context for sub-vdbe */
  95341. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  95342. Parse *pSubParse; /* Parse context for sub-vdbe */
  95343. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  95344. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  95345. assert( pTop->pVdbe );
  95346. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  95347. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  95348. ** list of the top-level Parse object sooner rather than later. */
  95349. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  95350. if( !pPrg ) return 0;
  95351. pPrg->pNext = pTop->pTriggerPrg;
  95352. pTop->pTriggerPrg = pPrg;
  95353. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  95354. if( !pProgram ) return 0;
  95355. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  95356. pPrg->pTrigger = pTrigger;
  95357. pPrg->orconf = orconf;
  95358. pPrg->aColmask[0] = 0xffffffff;
  95359. pPrg->aColmask[1] = 0xffffffff;
  95360. /* Allocate and populate a new Parse context to use for coding the
  95361. ** trigger sub-program. */
  95362. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  95363. if( !pSubParse ) return 0;
  95364. memset(&sNC, 0, sizeof(sNC));
  95365. sNC.pParse = pSubParse;
  95366. pSubParse->db = db;
  95367. pSubParse->pTriggerTab = pTab;
  95368. pSubParse->pToplevel = pTop;
  95369. pSubParse->zAuthContext = pTrigger->zName;
  95370. pSubParse->eTriggerOp = pTrigger->op;
  95371. pSubParse->nQueryLoop = pParse->nQueryLoop;
  95372. v = sqlite3GetVdbe(pSubParse);
  95373. if( v ){
  95374. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  95375. pTrigger->zName, onErrorText(orconf),
  95376. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  95377. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  95378. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  95379. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  95380. pTab->zName
  95381. ));
  95382. #ifndef SQLITE_OMIT_TRACE
  95383. sqlite3VdbeChangeP4(v, -1,
  95384. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  95385. );
  95386. #endif
  95387. /* If one was specified, code the WHEN clause. If it evaluates to false
  95388. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  95389. ** OP_Halt inserted at the end of the program. */
  95390. if( pTrigger->pWhen ){
  95391. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  95392. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  95393. && db->mallocFailed==0
  95394. ){
  95395. iEndTrigger = sqlite3VdbeMakeLabel(v);
  95396. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  95397. }
  95398. sqlite3ExprDelete(db, pWhen);
  95399. }
  95400. /* Code the trigger program into the sub-vdbe. */
  95401. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  95402. /* Insert an OP_Halt at the end of the sub-program. */
  95403. if( iEndTrigger ){
  95404. sqlite3VdbeResolveLabel(v, iEndTrigger);
  95405. }
  95406. sqlite3VdbeAddOp0(v, OP_Halt);
  95407. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  95408. transferParseError(pParse, pSubParse);
  95409. if( db->mallocFailed==0 ){
  95410. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  95411. }
  95412. pProgram->nMem = pSubParse->nMem;
  95413. pProgram->nCsr = pSubParse->nTab;
  95414. pProgram->nOnce = pSubParse->nOnce;
  95415. pProgram->token = (void *)pTrigger;
  95416. pPrg->aColmask[0] = pSubParse->oldmask;
  95417. pPrg->aColmask[1] = pSubParse->newmask;
  95418. sqlite3VdbeDelete(v);
  95419. }
  95420. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  95421. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  95422. sqlite3StackFree(db, pSubParse);
  95423. return pPrg;
  95424. }
  95425. /*
  95426. ** Return a pointer to a TriggerPrg object containing the sub-program for
  95427. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  95428. ** TriggerPrg object exists, a new object is allocated and populated before
  95429. ** being returned.
  95430. */
  95431. static TriggerPrg *getRowTrigger(
  95432. Parse *pParse, /* Current parse context */
  95433. Trigger *pTrigger, /* Trigger to code */
  95434. Table *pTab, /* The table trigger pTrigger is attached to */
  95435. int orconf /* ON CONFLICT algorithm. */
  95436. ){
  95437. Parse *pRoot = sqlite3ParseToplevel(pParse);
  95438. TriggerPrg *pPrg;
  95439. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  95440. /* It may be that this trigger has already been coded (or is in the
  95441. ** process of being coded). If this is the case, then an entry with
  95442. ** a matching TriggerPrg.pTrigger field will be present somewhere
  95443. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  95444. for(pPrg=pRoot->pTriggerPrg;
  95445. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  95446. pPrg=pPrg->pNext
  95447. );
  95448. /* If an existing TriggerPrg could not be located, create a new one. */
  95449. if( !pPrg ){
  95450. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  95451. }
  95452. return pPrg;
  95453. }
  95454. /*
  95455. ** Generate code for the trigger program associated with trigger p on
  95456. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  95457. ** function are the same as those described in the header function for
  95458. ** sqlite3CodeRowTrigger()
  95459. */
  95460. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  95461. Parse *pParse, /* Parse context */
  95462. Trigger *p, /* Trigger to code */
  95463. Table *pTab, /* The table to code triggers from */
  95464. int reg, /* Reg array containing OLD.* and NEW.* values */
  95465. int orconf, /* ON CONFLICT policy */
  95466. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  95467. ){
  95468. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  95469. TriggerPrg *pPrg;
  95470. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  95471. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  95472. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  95473. ** is a pointer to the sub-vdbe containing the trigger program. */
  95474. if( pPrg ){
  95475. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  95476. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  95477. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  95478. VdbeComment(
  95479. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  95480. /* Set the P5 operand of the OP_Program instruction to non-zero if
  95481. ** recursive invocation of this trigger program is disallowed. Recursive
  95482. ** invocation is disallowed if (a) the sub-program is really a trigger,
  95483. ** not a foreign key action, and (b) the flag to enable recursive triggers
  95484. ** is clear. */
  95485. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  95486. }
  95487. }
  95488. /*
  95489. ** This is called to code the required FOR EACH ROW triggers for an operation
  95490. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  95491. ** is given by the op paramater. The tr_tm parameter determines whether the
  95492. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  95493. ** parameter pChanges is passed the list of columns being modified.
  95494. **
  95495. ** If there are no triggers that fire at the specified time for the specified
  95496. ** operation on pTab, this function is a no-op.
  95497. **
  95498. ** The reg argument is the address of the first in an array of registers
  95499. ** that contain the values substituted for the new.* and old.* references
  95500. ** in the trigger program. If N is the number of columns in table pTab
  95501. ** (a copy of pTab->nCol), then registers are populated as follows:
  95502. **
  95503. ** Register Contains
  95504. ** ------------------------------------------------------
  95505. ** reg+0 OLD.rowid
  95506. ** reg+1 OLD.* value of left-most column of pTab
  95507. ** ... ...
  95508. ** reg+N OLD.* value of right-most column of pTab
  95509. ** reg+N+1 NEW.rowid
  95510. ** reg+N+2 OLD.* value of left-most column of pTab
  95511. ** ... ...
  95512. ** reg+N+N+1 NEW.* value of right-most column of pTab
  95513. **
  95514. ** For ON DELETE triggers, the registers containing the NEW.* values will
  95515. ** never be accessed by the trigger program, so they are not allocated or
  95516. ** populated by the caller (there is no data to populate them with anyway).
  95517. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  95518. ** are never accessed, and so are not allocated by the caller. So, for an
  95519. ** ON INSERT trigger, the value passed to this function as parameter reg
  95520. ** is not a readable register, although registers (reg+N) through
  95521. ** (reg+N+N+1) are.
  95522. **
  95523. ** Parameter orconf is the default conflict resolution algorithm for the
  95524. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  95525. ** is the instruction that control should jump to if a trigger program
  95526. ** raises an IGNORE exception.
  95527. */
  95528. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  95529. Parse *pParse, /* Parse context */
  95530. Trigger *pTrigger, /* List of triggers on table pTab */
  95531. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  95532. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  95533. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  95534. Table *pTab, /* The table to code triggers from */
  95535. int reg, /* The first in an array of registers (see above) */
  95536. int orconf, /* ON CONFLICT policy */
  95537. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  95538. ){
  95539. Trigger *p; /* Used to iterate through pTrigger list */
  95540. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  95541. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  95542. assert( (op==TK_UPDATE)==(pChanges!=0) );
  95543. for(p=pTrigger; p; p=p->pNext){
  95544. /* Sanity checking: The schema for the trigger and for the table are
  95545. ** always defined. The trigger must be in the same schema as the table
  95546. ** or else it must be a TEMP trigger. */
  95547. assert( p->pSchema!=0 );
  95548. assert( p->pTabSchema!=0 );
  95549. assert( p->pSchema==p->pTabSchema
  95550. || p->pSchema==pParse->db->aDb[1].pSchema );
  95551. /* Determine whether we should code this trigger */
  95552. if( p->op==op
  95553. && p->tr_tm==tr_tm
  95554. && checkColumnOverlap(p->pColumns, pChanges)
  95555. ){
  95556. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  95557. }
  95558. }
  95559. }
  95560. /*
  95561. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  95562. ** This function returns a 32-bit bitmask indicating which columns of the
  95563. ** old.* or new.* tables actually are used by triggers. This information
  95564. ** may be used by the caller, for example, to avoid having to load the entire
  95565. ** old.* record into memory when executing an UPDATE or DELETE command.
  95566. **
  95567. ** Bit 0 of the returned mask is set if the left-most column of the
  95568. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  95569. ** the second leftmost column value is required, and so on. If there
  95570. ** are more than 32 columns in the table, and at least one of the columns
  95571. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  95572. **
  95573. ** It is not possible to determine if the old.rowid or new.rowid column is
  95574. ** accessed by triggers. The caller must always assume that it is.
  95575. **
  95576. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  95577. ** applies to the old.* table. If 1, the new.* table.
  95578. **
  95579. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  95580. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  95581. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  95582. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  95583. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  95584. */
  95585. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  95586. Parse *pParse, /* Parse context */
  95587. Trigger *pTrigger, /* List of triggers on table pTab */
  95588. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  95589. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  95590. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  95591. Table *pTab, /* The table to code triggers from */
  95592. int orconf /* Default ON CONFLICT policy for trigger steps */
  95593. ){
  95594. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  95595. u32 mask = 0;
  95596. Trigger *p;
  95597. assert( isNew==1 || isNew==0 );
  95598. for(p=pTrigger; p; p=p->pNext){
  95599. if( p->op==op && (tr_tm&p->tr_tm)
  95600. && checkColumnOverlap(p->pColumns,pChanges)
  95601. ){
  95602. TriggerPrg *pPrg;
  95603. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  95604. if( pPrg ){
  95605. mask |= pPrg->aColmask[isNew];
  95606. }
  95607. }
  95608. }
  95609. return mask;
  95610. }
  95611. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  95612. /************** End of trigger.c *********************************************/
  95613. /************** Begin file update.c ******************************************/
  95614. /*
  95615. ** 2001 September 15
  95616. **
  95617. ** The author disclaims copyright to this source code. In place of
  95618. ** a legal notice, here is a blessing:
  95619. **
  95620. ** May you do good and not evil.
  95621. ** May you find forgiveness for yourself and forgive others.
  95622. ** May you share freely, never taking more than you give.
  95623. **
  95624. *************************************************************************
  95625. ** This file contains C code routines that are called by the parser
  95626. ** to handle UPDATE statements.
  95627. */
  95628. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95629. /* Forward declaration */
  95630. static void updateVirtualTable(
  95631. Parse *pParse, /* The parsing context */
  95632. SrcList *pSrc, /* The virtual table to be modified */
  95633. Table *pTab, /* The virtual table */
  95634. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  95635. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  95636. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  95637. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  95638. int onError /* ON CONFLICT strategy */
  95639. );
  95640. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  95641. /*
  95642. ** The most recently coded instruction was an OP_Column to retrieve the
  95643. ** i-th column of table pTab. This routine sets the P4 parameter of the
  95644. ** OP_Column to the default value, if any.
  95645. **
  95646. ** The default value of a column is specified by a DEFAULT clause in the
  95647. ** column definition. This was either supplied by the user when the table
  95648. ** was created, or added later to the table definition by an ALTER TABLE
  95649. ** command. If the latter, then the row-records in the table btree on disk
  95650. ** may not contain a value for the column and the default value, taken
  95651. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  95652. ** If the former, then all row-records are guaranteed to include a value
  95653. ** for the column and the P4 value is not required.
  95654. **
  95655. ** Column definitions created by an ALTER TABLE command may only have
  95656. ** literal default values specified: a number, null or a string. (If a more
  95657. ** complicated default expression value was provided, it is evaluated
  95658. ** when the ALTER TABLE is executed and one of the literal values written
  95659. ** into the sqlite_master table.)
  95660. **
  95661. ** Therefore, the P4 parameter is only required if the default value for
  95662. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  95663. ** function is capable of transforming these types of expressions into
  95664. ** sqlite3_value objects.
  95665. **
  95666. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  95667. ** on register iReg. This is used when an equivalent integer value is
  95668. ** stored in place of an 8-byte floating point value in order to save
  95669. ** space.
  95670. */
  95671. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  95672. assert( pTab!=0 );
  95673. if( !pTab->pSelect ){
  95674. sqlite3_value *pValue;
  95675. u8 enc = ENC(sqlite3VdbeDb(v));
  95676. Column *pCol = &pTab->aCol[i];
  95677. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  95678. assert( i<pTab->nCol );
  95679. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  95680. pCol->affinity, &pValue);
  95681. if( pValue ){
  95682. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  95683. }
  95684. #ifndef SQLITE_OMIT_FLOATING_POINT
  95685. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  95686. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  95687. }
  95688. #endif
  95689. }
  95690. }
  95691. /*
  95692. ** Process an UPDATE statement.
  95693. **
  95694. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  95695. ** \_______/ \________/ \______/ \________________/
  95696. * onError pTabList pChanges pWhere
  95697. */
  95698. SQLITE_PRIVATE void sqlite3Update(
  95699. Parse *pParse, /* The parser context */
  95700. SrcList *pTabList, /* The table in which we should change things */
  95701. ExprList *pChanges, /* Things to be changed */
  95702. Expr *pWhere, /* The WHERE clause. May be null */
  95703. int onError /* How to handle constraint errors */
  95704. ){
  95705. int i, j; /* Loop counters */
  95706. Table *pTab; /* The table to be updated */
  95707. int addr = 0; /* VDBE instruction address of the start of the loop */
  95708. WhereInfo *pWInfo; /* Information about the WHERE clause */
  95709. Vdbe *v; /* The virtual database engine */
  95710. Index *pIdx; /* For looping over indices */
  95711. int nIdx; /* Number of indices that need updating */
  95712. int iCur; /* VDBE Cursor number of pTab */
  95713. sqlite3 *db; /* The database structure */
  95714. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  95715. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  95716. ** an expression for the i-th column of the table.
  95717. ** aXRef[i]==-1 if the i-th column is not changed. */
  95718. int chngRowid; /* True if the record number is being changed */
  95719. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  95720. int openAll = 0; /* True if all indices need to be opened */
  95721. AuthContext sContext; /* The authorization context */
  95722. NameContext sNC; /* The name-context to resolve expressions in */
  95723. int iDb; /* Database containing the table being updated */
  95724. int okOnePass; /* True for one-pass algorithm without the FIFO */
  95725. int hasFK; /* True if foreign key processing is required */
  95726. #ifndef SQLITE_OMIT_TRIGGER
  95727. int isView; /* True when updating a view (INSTEAD OF trigger) */
  95728. Trigger *pTrigger; /* List of triggers on pTab, if required */
  95729. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  95730. #endif
  95731. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  95732. /* Register Allocations */
  95733. int regRowCount = 0; /* A count of rows changed */
  95734. int regOldRowid; /* The old rowid */
  95735. int regNewRowid; /* The new rowid */
  95736. int regNew; /* Content of the NEW.* table in triggers */
  95737. int regOld = 0; /* Content of OLD.* table in triggers */
  95738. int regRowSet = 0; /* Rowset of rows to be updated */
  95739. memset(&sContext, 0, sizeof(sContext));
  95740. db = pParse->db;
  95741. if( pParse->nErr || db->mallocFailed ){
  95742. goto update_cleanup;
  95743. }
  95744. assert( pTabList->nSrc==1 );
  95745. /* Locate the table which we want to update.
  95746. */
  95747. pTab = sqlite3SrcListLookup(pParse, pTabList);
  95748. if( pTab==0 ) goto update_cleanup;
  95749. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95750. /* Figure out if we have any triggers and if the table being
  95751. ** updated is a view.
  95752. */
  95753. #ifndef SQLITE_OMIT_TRIGGER
  95754. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  95755. isView = pTab->pSelect!=0;
  95756. assert( pTrigger || tmask==0 );
  95757. #else
  95758. # define pTrigger 0
  95759. # define isView 0
  95760. # define tmask 0
  95761. #endif
  95762. #ifdef SQLITE_OMIT_VIEW
  95763. # undef isView
  95764. # define isView 0
  95765. #endif
  95766. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  95767. goto update_cleanup;
  95768. }
  95769. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  95770. goto update_cleanup;
  95771. }
  95772. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  95773. if( aXRef==0 ) goto update_cleanup;
  95774. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  95775. /* Allocate a cursors for the main database table and for all indices.
  95776. ** The index cursors might not be used, but if they are used they
  95777. ** need to occur right after the database cursor. So go ahead and
  95778. ** allocate enough space, just in case.
  95779. */
  95780. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  95781. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95782. pParse->nTab++;
  95783. }
  95784. /* Initialize the name-context */
  95785. memset(&sNC, 0, sizeof(sNC));
  95786. sNC.pParse = pParse;
  95787. sNC.pSrcList = pTabList;
  95788. /* Resolve the column names in all the expressions of the
  95789. ** of the UPDATE statement. Also find the column index
  95790. ** for each column to be updated in the pChanges array. For each
  95791. ** column to be updated, make sure we have authorization to change
  95792. ** that column.
  95793. */
  95794. chngRowid = 0;
  95795. for(i=0; i<pChanges->nExpr; i++){
  95796. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  95797. goto update_cleanup;
  95798. }
  95799. for(j=0; j<pTab->nCol; j++){
  95800. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  95801. if( j==pTab->iPKey ){
  95802. chngRowid = 1;
  95803. pRowidExpr = pChanges->a[i].pExpr;
  95804. }
  95805. aXRef[j] = i;
  95806. break;
  95807. }
  95808. }
  95809. if( j>=pTab->nCol ){
  95810. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  95811. j = -1;
  95812. chngRowid = 1;
  95813. pRowidExpr = pChanges->a[i].pExpr;
  95814. }else{
  95815. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  95816. pParse->checkSchema = 1;
  95817. goto update_cleanup;
  95818. }
  95819. }
  95820. #ifndef SQLITE_OMIT_AUTHORIZATION
  95821. {
  95822. int rc;
  95823. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  95824. j<0 ? "ROWID" : pTab->aCol[j].zName,
  95825. db->aDb[iDb].zName);
  95826. if( rc==SQLITE_DENY ){
  95827. goto update_cleanup;
  95828. }else if( rc==SQLITE_IGNORE ){
  95829. aXRef[j] = -1;
  95830. }
  95831. }
  95832. #endif
  95833. }
  95834. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  95835. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  95836. ** array for each index associated with table being updated. Fill in
  95837. ** the value with a register number for indices that are to be used
  95838. ** and with zero for unused indices.
  95839. */
  95840. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  95841. if( nIdx>0 ){
  95842. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  95843. if( aRegIdx==0 ) goto update_cleanup;
  95844. }
  95845. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  95846. int reg;
  95847. if( hasFK || chngRowid ){
  95848. reg = ++pParse->nMem;
  95849. }else{
  95850. reg = 0;
  95851. for(i=0; i<pIdx->nColumn; i++){
  95852. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  95853. reg = ++pParse->nMem;
  95854. break;
  95855. }
  95856. }
  95857. }
  95858. aRegIdx[j] = reg;
  95859. }
  95860. /* Begin generating code. */
  95861. v = sqlite3GetVdbe(pParse);
  95862. if( v==0 ) goto update_cleanup;
  95863. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  95864. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95865. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95866. /* Virtual tables must be handled separately */
  95867. if( IsVirtual(pTab) ){
  95868. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  95869. pWhere, onError);
  95870. pWhere = 0;
  95871. pTabList = 0;
  95872. goto update_cleanup;
  95873. }
  95874. #endif
  95875. /* Allocate required registers. */
  95876. regRowSet = ++pParse->nMem;
  95877. regOldRowid = regNewRowid = ++pParse->nMem;
  95878. if( pTrigger || hasFK ){
  95879. regOld = pParse->nMem + 1;
  95880. pParse->nMem += pTab->nCol;
  95881. }
  95882. if( chngRowid || pTrigger || hasFK ){
  95883. regNewRowid = ++pParse->nMem;
  95884. }
  95885. regNew = pParse->nMem + 1;
  95886. pParse->nMem += pTab->nCol;
  95887. /* Start the view context. */
  95888. if( isView ){
  95889. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  95890. }
  95891. /* If we are trying to update a view, realize that view into
  95892. ** a ephemeral table.
  95893. */
  95894. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  95895. if( isView ){
  95896. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  95897. }
  95898. #endif
  95899. /* Resolve the column names in all the expressions in the
  95900. ** WHERE clause.
  95901. */
  95902. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  95903. goto update_cleanup;
  95904. }
  95905. /* Begin the database scan
  95906. */
  95907. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  95908. pWInfo = sqlite3WhereBegin(
  95909. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  95910. );
  95911. if( pWInfo==0 ) goto update_cleanup;
  95912. okOnePass = pWInfo->okOnePass;
  95913. /* Remember the rowid of every item to be updated.
  95914. */
  95915. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  95916. if( !okOnePass ){
  95917. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  95918. }
  95919. /* End the database scan loop.
  95920. */
  95921. sqlite3WhereEnd(pWInfo);
  95922. /* Initialize the count of updated rows
  95923. */
  95924. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  95925. regRowCount = ++pParse->nMem;
  95926. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  95927. }
  95928. if( !isView ){
  95929. /*
  95930. ** Open every index that needs updating. Note that if any
  95931. ** index could potentially invoke a REPLACE conflict resolution
  95932. ** action, then we need to open all indices because we might need
  95933. ** to be deleting some records.
  95934. */
  95935. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  95936. if( onError==OE_Replace ){
  95937. openAll = 1;
  95938. }else{
  95939. openAll = 0;
  95940. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95941. if( pIdx->onError==OE_Replace ){
  95942. openAll = 1;
  95943. break;
  95944. }
  95945. }
  95946. }
  95947. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  95948. assert( aRegIdx );
  95949. if( openAll || aRegIdx[i]>0 ){
  95950. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  95951. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  95952. (char*)pKey, P4_KEYINFO_HANDOFF);
  95953. assert( pParse->nTab>iCur+i+1 );
  95954. }
  95955. }
  95956. }
  95957. /* Top of the update loop */
  95958. if( okOnePass ){
  95959. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  95960. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  95961. sqlite3VdbeJumpHere(v, a1);
  95962. }else{
  95963. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  95964. }
  95965. /* Make cursor iCur point to the record that is being updated. If
  95966. ** this record does not exist for some reason (deleted by a trigger,
  95967. ** for example, then jump to the next iteration of the RowSet loop. */
  95968. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  95969. /* If the record number will change, set register regNewRowid to
  95970. ** contain the new value. If the record number is not being modified,
  95971. ** then regNewRowid is the same register as regOldRowid, which is
  95972. ** already populated. */
  95973. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  95974. if( chngRowid ){
  95975. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  95976. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  95977. }
  95978. /* If there are triggers on this table, populate an array of registers
  95979. ** with the required old.* column data. */
  95980. if( hasFK || pTrigger ){
  95981. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  95982. oldmask |= sqlite3TriggerColmask(pParse,
  95983. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  95984. );
  95985. for(i=0; i<pTab->nCol; i++){
  95986. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  95987. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  95988. }else{
  95989. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  95990. }
  95991. }
  95992. if( chngRowid==0 ){
  95993. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  95994. }
  95995. }
  95996. /* Populate the array of registers beginning at regNew with the new
  95997. ** row data. This array is used to check constaints, create the new
  95998. ** table and index records, and as the values for any new.* references
  95999. ** made by triggers.
  96000. **
  96001. ** If there are one or more BEFORE triggers, then do not populate the
  96002. ** registers associated with columns that are (a) not modified by
  96003. ** this UPDATE statement and (b) not accessed by new.* references. The
  96004. ** values for registers not modified by the UPDATE must be reloaded from
  96005. ** the database after the BEFORE triggers are fired anyway (as the trigger
  96006. ** may have modified them). So not loading those that are not going to
  96007. ** be used eliminates some redundant opcodes.
  96008. */
  96009. newmask = sqlite3TriggerColmask(
  96010. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  96011. );
  96012. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  96013. for(i=0; i<pTab->nCol; i++){
  96014. if( i==pTab->iPKey ){
  96015. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  96016. }else{
  96017. j = aXRef[i];
  96018. if( j>=0 ){
  96019. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  96020. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  96021. /* This branch loads the value of a column that will not be changed
  96022. ** into a register. This is done if there are no BEFORE triggers, or
  96023. ** if there are one or more BEFORE triggers that use this value via
  96024. ** a new.* reference in a trigger program.
  96025. */
  96026. testcase( i==31 );
  96027. testcase( i==32 );
  96028. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  96029. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  96030. }
  96031. }
  96032. }
  96033. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  96034. ** verified. One could argue that this is wrong.
  96035. */
  96036. if( tmask&TRIGGER_BEFORE ){
  96037. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  96038. sqlite3TableAffinityStr(v, pTab);
  96039. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  96040. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  96041. /* The row-trigger may have deleted the row being updated. In this
  96042. ** case, jump to the next row. No updates or AFTER triggers are
  96043. ** required. This behavior - what happens when the row being updated
  96044. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  96045. ** documentation.
  96046. */
  96047. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  96048. /* If it did not delete it, the row-trigger may still have modified
  96049. ** some of the columns of the row being updated. Load the values for
  96050. ** all columns not modified by the update statement into their
  96051. ** registers in case this has happened.
  96052. */
  96053. for(i=0; i<pTab->nCol; i++){
  96054. if( aXRef[i]<0 && i!=pTab->iPKey ){
  96055. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  96056. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  96057. }
  96058. }
  96059. }
  96060. if( !isView ){
  96061. int j1; /* Address of jump instruction */
  96062. /* Do constraint checks. */
  96063. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  96064. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  96065. /* Do FK constraint checks. */
  96066. if( hasFK ){
  96067. sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
  96068. }
  96069. /* Delete the index entries associated with the current record. */
  96070. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  96071. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  96072. /* If changing the record number, delete the old record. */
  96073. if( hasFK || chngRowid ){
  96074. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  96075. }
  96076. sqlite3VdbeJumpHere(v, j1);
  96077. if( hasFK ){
  96078. sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
  96079. }
  96080. /* Insert the new index entries and the new record. */
  96081. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  96082. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  96083. ** handle rows (possibly in other tables) that refer via a foreign key
  96084. ** to the row just updated. */
  96085. if( hasFK ){
  96086. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
  96087. }
  96088. }
  96089. /* Increment the row counter
  96090. */
  96091. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  96092. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  96093. }
  96094. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  96095. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  96096. /* Repeat the above with the next record to be updated, until
  96097. ** all record selected by the WHERE clause have been updated.
  96098. */
  96099. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  96100. sqlite3VdbeJumpHere(v, addr);
  96101. /* Close all tables */
  96102. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  96103. assert( aRegIdx );
  96104. if( openAll || aRegIdx[i]>0 ){
  96105. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  96106. }
  96107. }
  96108. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  96109. /* Update the sqlite_sequence table by storing the content of the
  96110. ** maximum rowid counter values recorded while inserting into
  96111. ** autoincrement tables.
  96112. */
  96113. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  96114. sqlite3AutoincrementEnd(pParse);
  96115. }
  96116. /*
  96117. ** Return the number of rows that were changed. If this routine is
  96118. ** generating code because of a call to sqlite3NestedParse(), do not
  96119. ** invoke the callback function.
  96120. */
  96121. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  96122. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  96123. sqlite3VdbeSetNumCols(v, 1);
  96124. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  96125. }
  96126. update_cleanup:
  96127. sqlite3AuthContextPop(&sContext);
  96128. sqlite3DbFree(db, aRegIdx);
  96129. sqlite3DbFree(db, aXRef);
  96130. sqlite3SrcListDelete(db, pTabList);
  96131. sqlite3ExprListDelete(db, pChanges);
  96132. sqlite3ExprDelete(db, pWhere);
  96133. return;
  96134. }
  96135. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  96136. ** thely may interfere with compilation of other functions in this file
  96137. ** (or in another file, if this file becomes part of the amalgamation). */
  96138. #ifdef isView
  96139. #undef isView
  96140. #endif
  96141. #ifdef pTrigger
  96142. #undef pTrigger
  96143. #endif
  96144. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96145. /*
  96146. ** Generate code for an UPDATE of a virtual table.
  96147. **
  96148. ** The strategy is that we create an ephemerial table that contains
  96149. ** for each row to be changed:
  96150. **
  96151. ** (A) The original rowid of that row.
  96152. ** (B) The revised rowid for the row. (note1)
  96153. ** (C) The content of every column in the row.
  96154. **
  96155. ** Then we loop over this ephemeral table and for each row in
  96156. ** the ephermeral table call VUpdate.
  96157. **
  96158. ** When finished, drop the ephemeral table.
  96159. **
  96160. ** (note1) Actually, if we know in advance that (A) is always the same
  96161. ** as (B) we only store (A), then duplicate (A) when pulling
  96162. ** it out of the ephemeral table before calling VUpdate.
  96163. */
  96164. static void updateVirtualTable(
  96165. Parse *pParse, /* The parsing context */
  96166. SrcList *pSrc, /* The virtual table to be modified */
  96167. Table *pTab, /* The virtual table */
  96168. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  96169. Expr *pRowid, /* Expression used to recompute the rowid */
  96170. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  96171. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  96172. int onError /* ON CONFLICT strategy */
  96173. ){
  96174. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  96175. ExprList *pEList = 0; /* The result set of the SELECT statement */
  96176. Select *pSelect = 0; /* The SELECT statement */
  96177. Expr *pExpr; /* Temporary expression */
  96178. int ephemTab; /* Table holding the result of the SELECT */
  96179. int i; /* Loop counter */
  96180. int addr; /* Address of top of loop */
  96181. int iReg; /* First register in set passed to OP_VUpdate */
  96182. sqlite3 *db = pParse->db; /* Database connection */
  96183. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  96184. SelectDest dest;
  96185. /* Construct the SELECT statement that will find the new values for
  96186. ** all updated rows.
  96187. */
  96188. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  96189. if( pRowid ){
  96190. pEList = sqlite3ExprListAppend(pParse, pEList,
  96191. sqlite3ExprDup(db, pRowid, 0));
  96192. }
  96193. assert( pTab->iPKey<0 );
  96194. for(i=0; i<pTab->nCol; i++){
  96195. if( aXRef[i]>=0 ){
  96196. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  96197. }else{
  96198. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  96199. }
  96200. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  96201. }
  96202. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  96203. /* Create the ephemeral table into which the update results will
  96204. ** be stored.
  96205. */
  96206. assert( v );
  96207. ephemTab = pParse->nTab++;
  96208. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  96209. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  96210. /* fill the ephemeral table
  96211. */
  96212. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  96213. sqlite3Select(pParse, pSelect, &dest);
  96214. /* Generate code to scan the ephemeral table and call VUpdate. */
  96215. iReg = ++pParse->nMem;
  96216. pParse->nMem += pTab->nCol+1;
  96217. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  96218. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  96219. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  96220. for(i=0; i<pTab->nCol; i++){
  96221. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  96222. }
  96223. sqlite3VtabMakeWritable(pParse, pTab);
  96224. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  96225. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  96226. sqlite3MayAbort(pParse);
  96227. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  96228. sqlite3VdbeJumpHere(v, addr);
  96229. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  96230. /* Cleanup */
  96231. sqlite3SelectDelete(db, pSelect);
  96232. }
  96233. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  96234. /************** End of update.c **********************************************/
  96235. /************** Begin file vacuum.c ******************************************/
  96236. /*
  96237. ** 2003 April 6
  96238. **
  96239. ** The author disclaims copyright to this source code. In place of
  96240. ** a legal notice, here is a blessing:
  96241. **
  96242. ** May you do good and not evil.
  96243. ** May you find forgiveness for yourself and forgive others.
  96244. ** May you share freely, never taking more than you give.
  96245. **
  96246. *************************************************************************
  96247. ** This file contains code used to implement the VACUUM command.
  96248. **
  96249. ** Most of the code in this file may be omitted by defining the
  96250. ** SQLITE_OMIT_VACUUM macro.
  96251. */
  96252. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  96253. /*
  96254. ** Finalize a prepared statement. If there was an error, store the
  96255. ** text of the error message in *pzErrMsg. Return the result code.
  96256. */
  96257. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  96258. int rc;
  96259. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  96260. if( rc ){
  96261. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  96262. }
  96263. return rc;
  96264. }
  96265. /*
  96266. ** Execute zSql on database db. Return an error code.
  96267. */
  96268. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  96269. sqlite3_stmt *pStmt;
  96270. VVA_ONLY( int rc; )
  96271. if( !zSql ){
  96272. return SQLITE_NOMEM;
  96273. }
  96274. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  96275. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  96276. return sqlite3_errcode(db);
  96277. }
  96278. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  96279. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  96280. return vacuumFinalize(db, pStmt, pzErrMsg);
  96281. }
  96282. /*
  96283. ** Execute zSql on database db. The statement returns exactly
  96284. ** one column. Execute this as SQL on the same database.
  96285. */
  96286. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  96287. sqlite3_stmt *pStmt;
  96288. int rc;
  96289. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  96290. if( rc!=SQLITE_OK ) return rc;
  96291. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  96292. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  96293. if( rc!=SQLITE_OK ){
  96294. vacuumFinalize(db, pStmt, pzErrMsg);
  96295. return rc;
  96296. }
  96297. }
  96298. return vacuumFinalize(db, pStmt, pzErrMsg);
  96299. }
  96300. /*
  96301. ** The non-standard VACUUM command is used to clean up the database,
  96302. ** collapse free space, etc. It is modelled after the VACUUM command
  96303. ** in PostgreSQL.
  96304. **
  96305. ** In version 1.0.x of SQLite, the VACUUM command would call
  96306. ** gdbm_reorganize() on all the database tables. But beginning
  96307. ** with 2.0.0, SQLite no longer uses GDBM so this command has
  96308. ** become a no-op.
  96309. */
  96310. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  96311. Vdbe *v = sqlite3GetVdbe(pParse);
  96312. if( v ){
  96313. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  96314. sqlite3VdbeUsesBtree(v, 0);
  96315. }
  96316. return;
  96317. }
  96318. /*
  96319. ** This routine implements the OP_Vacuum opcode of the VDBE.
  96320. */
  96321. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  96322. int rc = SQLITE_OK; /* Return code from service routines */
  96323. Btree *pMain; /* The database being vacuumed */
  96324. Btree *pTemp; /* The temporary database we vacuum into */
  96325. char *zSql = 0; /* SQL statements */
  96326. int saved_flags; /* Saved value of the db->flags */
  96327. int saved_nChange; /* Saved value of db->nChange */
  96328. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  96329. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  96330. Db *pDb = 0; /* Database to detach at end of vacuum */
  96331. int isMemDb; /* True if vacuuming a :memory: database */
  96332. int nRes; /* Bytes of reserved space at the end of each page */
  96333. int nDb; /* Number of attached databases */
  96334. if( !db->autoCommit ){
  96335. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  96336. return SQLITE_ERROR;
  96337. }
  96338. if( db->activeVdbeCnt>1 ){
  96339. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  96340. return SQLITE_ERROR;
  96341. }
  96342. /* Save the current value of the database flags so that it can be
  96343. ** restored before returning. Then set the writable-schema flag, and
  96344. ** disable CHECK and foreign key constraints. */
  96345. saved_flags = db->flags;
  96346. saved_nChange = db->nChange;
  96347. saved_nTotalChange = db->nTotalChange;
  96348. saved_xTrace = db->xTrace;
  96349. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  96350. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  96351. db->xTrace = 0;
  96352. pMain = db->aDb[0].pBt;
  96353. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  96354. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  96355. ** can be set to 'off' for this file, as it is not recovered if a crash
  96356. ** occurs anyway. The integrity of the database is maintained by a
  96357. ** (possibly synchronous) transaction opened on the main database before
  96358. ** sqlite3BtreeCopyFile() is called.
  96359. **
  96360. ** An optimisation would be to use a non-journaled pager.
  96361. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  96362. ** that actually made the VACUUM run slower. Very little journalling
  96363. ** actually occurs when doing a vacuum since the vacuum_db is initially
  96364. ** empty. Only the journal header is written. Apparently it takes more
  96365. ** time to parse and run the PRAGMA to turn journalling off than it does
  96366. ** to write the journal header file.
  96367. */
  96368. nDb = db->nDb;
  96369. if( sqlite3TempInMemory(db) ){
  96370. zSql = "ATTACH ':memory:' AS vacuum_db;";
  96371. }else{
  96372. zSql = "ATTACH '' AS vacuum_db;";
  96373. }
  96374. rc = execSql(db, pzErrMsg, zSql);
  96375. if( db->nDb>nDb ){
  96376. pDb = &db->aDb[db->nDb-1];
  96377. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  96378. }
  96379. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96380. pTemp = db->aDb[db->nDb-1].pBt;
  96381. /* The call to execSql() to attach the temp database has left the file
  96382. ** locked (as there was more than one active statement when the transaction
  96383. ** to read the schema was concluded. Unlock it here so that this doesn't
  96384. ** cause problems for the call to BtreeSetPageSize() below. */
  96385. sqlite3BtreeCommit(pTemp);
  96386. nRes = sqlite3BtreeGetReserve(pMain);
  96387. /* A VACUUM cannot change the pagesize of an encrypted database. */
  96388. #ifdef SQLITE_HAS_CODEC
  96389. if( db->nextPagesize ){
  96390. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  96391. int nKey;
  96392. char *zKey;
  96393. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  96394. if( nKey ) db->nextPagesize = 0;
  96395. }
  96396. #endif
  96397. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  96398. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96399. /* Begin a transaction and take an exclusive lock on the main database
  96400. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  96401. ** to ensure that we do not try to change the page-size on a WAL database.
  96402. */
  96403. rc = execSql(db, pzErrMsg, "BEGIN;");
  96404. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96405. rc = sqlite3BtreeBeginTrans(pMain, 2);
  96406. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96407. /* Do not attempt to change the page size for a WAL database */
  96408. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  96409. ==PAGER_JOURNALMODE_WAL ){
  96410. db->nextPagesize = 0;
  96411. }
  96412. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  96413. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  96414. || NEVER(db->mallocFailed)
  96415. ){
  96416. rc = SQLITE_NOMEM;
  96417. goto end_of_vacuum;
  96418. }
  96419. #ifndef SQLITE_OMIT_AUTOVACUUM
  96420. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  96421. sqlite3BtreeGetAutoVacuum(pMain));
  96422. #endif
  96423. /* Query the schema of the main database. Create a mirror schema
  96424. ** in the temporary database.
  96425. */
  96426. rc = execExecSql(db, pzErrMsg,
  96427. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  96428. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  96429. " AND rootpage>0"
  96430. );
  96431. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96432. rc = execExecSql(db, pzErrMsg,
  96433. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  96434. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  96435. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96436. rc = execExecSql(db, pzErrMsg,
  96437. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  96438. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  96439. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96440. /* Loop through the tables in the main database. For each, do
  96441. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  96442. ** the contents to the temporary database.
  96443. */
  96444. rc = execExecSql(db, pzErrMsg,
  96445. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  96446. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  96447. "FROM main.sqlite_master "
  96448. "WHERE type = 'table' AND name!='sqlite_sequence' "
  96449. " AND rootpage>0"
  96450. );
  96451. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96452. /* Copy over the sequence table
  96453. */
  96454. rc = execExecSql(db, pzErrMsg,
  96455. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  96456. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  96457. );
  96458. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96459. rc = execExecSql(db, pzErrMsg,
  96460. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  96461. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  96462. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  96463. );
  96464. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96465. /* Copy the triggers, views, and virtual tables from the main database
  96466. ** over to the temporary database. None of these objects has any
  96467. ** associated storage, so all we have to do is copy their entries
  96468. ** from the SQLITE_MASTER table.
  96469. */
  96470. rc = execSql(db, pzErrMsg,
  96471. "INSERT INTO vacuum_db.sqlite_master "
  96472. " SELECT type, name, tbl_name, rootpage, sql"
  96473. " FROM main.sqlite_master"
  96474. " WHERE type='view' OR type='trigger'"
  96475. " OR (type='table' AND rootpage=0)"
  96476. );
  96477. if( rc ) goto end_of_vacuum;
  96478. /* At this point, there is a write transaction open on both the
  96479. ** vacuum database and the main database. Assuming no error occurs,
  96480. ** both transactions are closed by this block - the main database
  96481. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  96482. ** call to sqlite3BtreeCommit().
  96483. */
  96484. {
  96485. u32 meta;
  96486. int i;
  96487. /* This array determines which meta meta values are preserved in the
  96488. ** vacuum. Even entries are the meta value number and odd entries
  96489. ** are an increment to apply to the meta value after the vacuum.
  96490. ** The increment is used to increase the schema cookie so that other
  96491. ** connections to the same database will know to reread the schema.
  96492. */
  96493. static const unsigned char aCopy[] = {
  96494. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  96495. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  96496. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  96497. BTREE_USER_VERSION, 0, /* Preserve the user version */
  96498. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  96499. };
  96500. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  96501. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  96502. /* Copy Btree meta values */
  96503. for(i=0; i<ArraySize(aCopy); i+=2){
  96504. /* GetMeta() and UpdateMeta() cannot fail in this context because
  96505. ** we already have page 1 loaded into cache and marked dirty. */
  96506. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  96507. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  96508. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  96509. }
  96510. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  96511. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96512. rc = sqlite3BtreeCommit(pTemp);
  96513. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  96514. #ifndef SQLITE_OMIT_AUTOVACUUM
  96515. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  96516. #endif
  96517. }
  96518. assert( rc==SQLITE_OK );
  96519. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  96520. end_of_vacuum:
  96521. /* Restore the original value of db->flags */
  96522. db->flags = saved_flags;
  96523. db->nChange = saved_nChange;
  96524. db->nTotalChange = saved_nTotalChange;
  96525. db->xTrace = saved_xTrace;
  96526. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  96527. /* Currently there is an SQL level transaction open on the vacuum
  96528. ** database. No locks are held on any other files (since the main file
  96529. ** was committed at the btree level). So it safe to end the transaction
  96530. ** by manually setting the autoCommit flag to true and detaching the
  96531. ** vacuum database. The vacuum_db journal file is deleted when the pager
  96532. ** is closed by the DETACH.
  96533. */
  96534. db->autoCommit = 1;
  96535. if( pDb ){
  96536. sqlite3BtreeClose(pDb->pBt);
  96537. pDb->pBt = 0;
  96538. pDb->pSchema = 0;
  96539. }
  96540. /* This both clears the schemas and reduces the size of the db->aDb[]
  96541. ** array. */
  96542. sqlite3ResetAllSchemasOfConnection(db);
  96543. return rc;
  96544. }
  96545. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  96546. /************** End of vacuum.c **********************************************/
  96547. /************** Begin file vtab.c ********************************************/
  96548. /*
  96549. ** 2006 June 10
  96550. **
  96551. ** The author disclaims copyright to this source code. In place of
  96552. ** a legal notice, here is a blessing:
  96553. **
  96554. ** May you do good and not evil.
  96555. ** May you find forgiveness for yourself and forgive others.
  96556. ** May you share freely, never taking more than you give.
  96557. **
  96558. *************************************************************************
  96559. ** This file contains code used to help implement virtual tables.
  96560. */
  96561. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96562. /*
  96563. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  96564. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  96565. ** this struct allocated on the stack. It is used by the implementation of
  96566. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  96567. ** are invoked only from within xCreate and xConnect methods.
  96568. */
  96569. struct VtabCtx {
  96570. VTable *pVTable; /* The virtual table being constructed */
  96571. Table *pTab; /* The Table object to which the virtual table belongs */
  96572. };
  96573. /*
  96574. ** The actual function that does the work of creating a new module.
  96575. ** This function implements the sqlite3_create_module() and
  96576. ** sqlite3_create_module_v2() interfaces.
  96577. */
  96578. static int createModule(
  96579. sqlite3 *db, /* Database in which module is registered */
  96580. const char *zName, /* Name assigned to this module */
  96581. const sqlite3_module *pModule, /* The definition of the module */
  96582. void *pAux, /* Context pointer for xCreate/xConnect */
  96583. void (*xDestroy)(void *) /* Module destructor function */
  96584. ){
  96585. int rc = SQLITE_OK;
  96586. int nName;
  96587. sqlite3_mutex_enter(db->mutex);
  96588. nName = sqlite3Strlen30(zName);
  96589. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  96590. rc = SQLITE_MISUSE_BKPT;
  96591. }else{
  96592. Module *pMod;
  96593. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  96594. if( pMod ){
  96595. Module *pDel;
  96596. char *zCopy = (char *)(&pMod[1]);
  96597. memcpy(zCopy, zName, nName+1);
  96598. pMod->zName = zCopy;
  96599. pMod->pModule = pModule;
  96600. pMod->pAux = pAux;
  96601. pMod->xDestroy = xDestroy;
  96602. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  96603. assert( pDel==0 || pDel==pMod );
  96604. if( pDel ){
  96605. db->mallocFailed = 1;
  96606. sqlite3DbFree(db, pDel);
  96607. }
  96608. }
  96609. }
  96610. rc = sqlite3ApiExit(db, rc);
  96611. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  96612. sqlite3_mutex_leave(db->mutex);
  96613. return rc;
  96614. }
  96615. /*
  96616. ** External API function used to create a new virtual-table module.
  96617. */
  96618. SQLITE_API int sqlite3_create_module(
  96619. sqlite3 *db, /* Database in which module is registered */
  96620. const char *zName, /* Name assigned to this module */
  96621. const sqlite3_module *pModule, /* The definition of the module */
  96622. void *pAux /* Context pointer for xCreate/xConnect */
  96623. ){
  96624. return createModule(db, zName, pModule, pAux, 0);
  96625. }
  96626. /*
  96627. ** External API function used to create a new virtual-table module.
  96628. */
  96629. SQLITE_API int sqlite3_create_module_v2(
  96630. sqlite3 *db, /* Database in which module is registered */
  96631. const char *zName, /* Name assigned to this module */
  96632. const sqlite3_module *pModule, /* The definition of the module */
  96633. void *pAux, /* Context pointer for xCreate/xConnect */
  96634. void (*xDestroy)(void *) /* Module destructor function */
  96635. ){
  96636. return createModule(db, zName, pModule, pAux, xDestroy);
  96637. }
  96638. /*
  96639. ** Lock the virtual table so that it cannot be disconnected.
  96640. ** Locks nest. Every lock should have a corresponding unlock.
  96641. ** If an unlock is omitted, resources leaks will occur.
  96642. **
  96643. ** If a disconnect is attempted while a virtual table is locked,
  96644. ** the disconnect is deferred until all locks have been removed.
  96645. */
  96646. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  96647. pVTab->nRef++;
  96648. }
  96649. /*
  96650. ** pTab is a pointer to a Table structure representing a virtual-table.
  96651. ** Return a pointer to the VTable object used by connection db to access
  96652. ** this virtual-table, if one has been created, or NULL otherwise.
  96653. */
  96654. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  96655. VTable *pVtab;
  96656. assert( IsVirtual(pTab) );
  96657. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  96658. return pVtab;
  96659. }
  96660. /*
  96661. ** Decrement the ref-count on a virtual table object. When the ref-count
  96662. ** reaches zero, call the xDisconnect() method to delete the object.
  96663. */
  96664. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  96665. sqlite3 *db = pVTab->db;
  96666. assert( db );
  96667. assert( pVTab->nRef>0 );
  96668. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  96669. pVTab->nRef--;
  96670. if( pVTab->nRef==0 ){
  96671. sqlite3_vtab *p = pVTab->pVtab;
  96672. if( p ){
  96673. p->pModule->xDisconnect(p);
  96674. }
  96675. sqlite3DbFree(db, pVTab);
  96676. }
  96677. }
  96678. /*
  96679. ** Table p is a virtual table. This function moves all elements in the
  96680. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  96681. ** database connections to be disconnected at the next opportunity.
  96682. ** Except, if argument db is not NULL, then the entry associated with
  96683. ** connection db is left in the p->pVTable list.
  96684. */
  96685. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  96686. VTable *pRet = 0;
  96687. VTable *pVTable = p->pVTable;
  96688. p->pVTable = 0;
  96689. /* Assert that the mutex (if any) associated with the BtShared database
  96690. ** that contains table p is held by the caller. See header comments
  96691. ** above function sqlite3VtabUnlockList() for an explanation of why
  96692. ** this makes it safe to access the sqlite3.pDisconnect list of any
  96693. ** database connection that may have an entry in the p->pVTable list.
  96694. */
  96695. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  96696. while( pVTable ){
  96697. sqlite3 *db2 = pVTable->db;
  96698. VTable *pNext = pVTable->pNext;
  96699. assert( db2 );
  96700. if( db2==db ){
  96701. pRet = pVTable;
  96702. p->pVTable = pRet;
  96703. pRet->pNext = 0;
  96704. }else{
  96705. pVTable->pNext = db2->pDisconnect;
  96706. db2->pDisconnect = pVTable;
  96707. }
  96708. pVTable = pNext;
  96709. }
  96710. assert( !db || pRet );
  96711. return pRet;
  96712. }
  96713. /*
  96714. ** Table *p is a virtual table. This function removes the VTable object
  96715. ** for table *p associated with database connection db from the linked
  96716. ** list in p->pVTab. It also decrements the VTable ref count. This is
  96717. ** used when closing database connection db to free all of its VTable
  96718. ** objects without disturbing the rest of the Schema object (which may
  96719. ** be being used by other shared-cache connections).
  96720. */
  96721. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  96722. VTable **ppVTab;
  96723. assert( IsVirtual(p) );
  96724. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96725. assert( sqlite3_mutex_held(db->mutex) );
  96726. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  96727. if( (*ppVTab)->db==db ){
  96728. VTable *pVTab = *ppVTab;
  96729. *ppVTab = pVTab->pNext;
  96730. sqlite3VtabUnlock(pVTab);
  96731. break;
  96732. }
  96733. }
  96734. }
  96735. /*
  96736. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  96737. **
  96738. ** This function may only be called when the mutexes associated with all
  96739. ** shared b-tree databases opened using connection db are held by the
  96740. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  96741. ** sqlite3.pDisconnect list is accessed only as follows:
  96742. **
  96743. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  96744. ** associated with the database handle itself must be held.
  96745. **
  96746. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  96747. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  96748. ** associated with the database the virtual table is stored in is held
  96749. ** or, if the virtual table is stored in a non-sharable database, then
  96750. ** the database handle mutex is held.
  96751. **
  96752. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  96753. ** by multiple threads. It is thread-safe.
  96754. */
  96755. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  96756. VTable *p = db->pDisconnect;
  96757. db->pDisconnect = 0;
  96758. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96759. assert( sqlite3_mutex_held(db->mutex) );
  96760. if( p ){
  96761. sqlite3ExpirePreparedStatements(db);
  96762. do {
  96763. VTable *pNext = p->pNext;
  96764. sqlite3VtabUnlock(p);
  96765. p = pNext;
  96766. }while( p );
  96767. }
  96768. }
  96769. /*
  96770. ** Clear any and all virtual-table information from the Table record.
  96771. ** This routine is called, for example, just before deleting the Table
  96772. ** record.
  96773. **
  96774. ** Since it is a virtual-table, the Table structure contains a pointer
  96775. ** to the head of a linked list of VTable structures. Each VTable
  96776. ** structure is associated with a single sqlite3* user of the schema.
  96777. ** The reference count of the VTable structure associated with database
  96778. ** connection db is decremented immediately (which may lead to the
  96779. ** structure being xDisconnected and free). Any other VTable structures
  96780. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  96781. ** database connection.
  96782. */
  96783. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  96784. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  96785. if( p->azModuleArg ){
  96786. int i;
  96787. for(i=0; i<p->nModuleArg; i++){
  96788. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  96789. }
  96790. sqlite3DbFree(db, p->azModuleArg);
  96791. }
  96792. }
  96793. /*
  96794. ** Add a new module argument to pTable->azModuleArg[].
  96795. ** The string is not copied - the pointer is stored. The
  96796. ** string will be freed automatically when the table is
  96797. ** deleted.
  96798. */
  96799. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  96800. int i = pTable->nModuleArg++;
  96801. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  96802. char **azModuleArg;
  96803. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  96804. if( azModuleArg==0 ){
  96805. int j;
  96806. for(j=0; j<i; j++){
  96807. sqlite3DbFree(db, pTable->azModuleArg[j]);
  96808. }
  96809. sqlite3DbFree(db, zArg);
  96810. sqlite3DbFree(db, pTable->azModuleArg);
  96811. pTable->nModuleArg = 0;
  96812. }else{
  96813. azModuleArg[i] = zArg;
  96814. azModuleArg[i+1] = 0;
  96815. }
  96816. pTable->azModuleArg = azModuleArg;
  96817. }
  96818. /*
  96819. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  96820. ** statement. The module name has been parsed, but the optional list
  96821. ** of parameters that follow the module name are still pending.
  96822. */
  96823. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  96824. Parse *pParse, /* Parsing context */
  96825. Token *pName1, /* Name of new table, or database name */
  96826. Token *pName2, /* Name of new table or NULL */
  96827. Token *pModuleName, /* Name of the module for the virtual table */
  96828. int ifNotExists /* No error if the table already exists */
  96829. ){
  96830. int iDb; /* The database the table is being created in */
  96831. Table *pTable; /* The new virtual table */
  96832. sqlite3 *db; /* Database connection */
  96833. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  96834. pTable = pParse->pNewTable;
  96835. if( pTable==0 ) return;
  96836. assert( 0==pTable->pIndex );
  96837. db = pParse->db;
  96838. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  96839. assert( iDb>=0 );
  96840. pTable->tabFlags |= TF_Virtual;
  96841. pTable->nModuleArg = 0;
  96842. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  96843. addModuleArgument(db, pTable, 0);
  96844. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  96845. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  96846. #ifndef SQLITE_OMIT_AUTHORIZATION
  96847. /* Creating a virtual table invokes the authorization callback twice.
  96848. ** The first invocation, to obtain permission to INSERT a row into the
  96849. ** sqlite_master table, has already been made by sqlite3StartTable().
  96850. ** The second call, to obtain permission to create the table, is made now.
  96851. */
  96852. if( pTable->azModuleArg ){
  96853. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  96854. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  96855. }
  96856. #endif
  96857. }
  96858. /*
  96859. ** This routine takes the module argument that has been accumulating
  96860. ** in pParse->zArg[] and appends it to the list of arguments on the
  96861. ** virtual table currently under construction in pParse->pTable.
  96862. */
  96863. static void addArgumentToVtab(Parse *pParse){
  96864. if( pParse->sArg.z && pParse->pNewTable ){
  96865. const char *z = (const char*)pParse->sArg.z;
  96866. int n = pParse->sArg.n;
  96867. sqlite3 *db = pParse->db;
  96868. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  96869. }
  96870. }
  96871. /*
  96872. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  96873. ** has been completely parsed.
  96874. */
  96875. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  96876. Table *pTab = pParse->pNewTable; /* The table being constructed */
  96877. sqlite3 *db = pParse->db; /* The database connection */
  96878. if( pTab==0 ) return;
  96879. addArgumentToVtab(pParse);
  96880. pParse->sArg.z = 0;
  96881. if( pTab->nModuleArg<1 ) return;
  96882. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  96883. ** first time (in other words if the virtual table is actually being
  96884. ** created now instead of just being read out of sqlite_master) then
  96885. ** do additional initialization work and store the statement text
  96886. ** in the sqlite_master table.
  96887. */
  96888. if( !db->init.busy ){
  96889. char *zStmt;
  96890. char *zWhere;
  96891. int iDb;
  96892. Vdbe *v;
  96893. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  96894. if( pEnd ){
  96895. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  96896. }
  96897. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  96898. /* A slot for the record has already been allocated in the
  96899. ** SQLITE_MASTER table. We just need to update that slot with all
  96900. ** the information we've collected.
  96901. **
  96902. ** The VM register number pParse->regRowid holds the rowid of an
  96903. ** entry in the sqlite_master table tht was created for this vtab
  96904. ** by sqlite3StartTable().
  96905. */
  96906. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96907. sqlite3NestedParse(pParse,
  96908. "UPDATE %Q.%s "
  96909. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  96910. "WHERE rowid=#%d",
  96911. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  96912. pTab->zName,
  96913. pTab->zName,
  96914. zStmt,
  96915. pParse->regRowid
  96916. );
  96917. sqlite3DbFree(db, zStmt);
  96918. v = sqlite3GetVdbe(pParse);
  96919. sqlite3ChangeCookie(pParse, iDb);
  96920. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  96921. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  96922. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  96923. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  96924. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  96925. }
  96926. /* If we are rereading the sqlite_master table create the in-memory
  96927. ** record of the table. The xConnect() method is not called until
  96928. ** the first time the virtual table is used in an SQL statement. This
  96929. ** allows a schema that contains virtual tables to be loaded before
  96930. ** the required virtual table implementations are registered. */
  96931. else {
  96932. Table *pOld;
  96933. Schema *pSchema = pTab->pSchema;
  96934. const char *zName = pTab->zName;
  96935. int nName = sqlite3Strlen30(zName);
  96936. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  96937. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  96938. if( pOld ){
  96939. db->mallocFailed = 1;
  96940. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  96941. return;
  96942. }
  96943. pParse->pNewTable = 0;
  96944. }
  96945. }
  96946. /*
  96947. ** The parser calls this routine when it sees the first token
  96948. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  96949. */
  96950. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  96951. addArgumentToVtab(pParse);
  96952. pParse->sArg.z = 0;
  96953. pParse->sArg.n = 0;
  96954. }
  96955. /*
  96956. ** The parser calls this routine for each token after the first token
  96957. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  96958. */
  96959. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  96960. Token *pArg = &pParse->sArg;
  96961. if( pArg->z==0 ){
  96962. pArg->z = p->z;
  96963. pArg->n = p->n;
  96964. }else{
  96965. assert(pArg->z < p->z);
  96966. pArg->n = (int)(&p->z[p->n] - pArg->z);
  96967. }
  96968. }
  96969. /*
  96970. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  96971. ** pointer to the function to invoke is passed as the fourth parameter
  96972. ** to this procedure.
  96973. */
  96974. static int vtabCallConstructor(
  96975. sqlite3 *db,
  96976. Table *pTab,
  96977. Module *pMod,
  96978. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  96979. char **pzErr
  96980. ){
  96981. VtabCtx sCtx, *pPriorCtx;
  96982. VTable *pVTable;
  96983. int rc;
  96984. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  96985. int nArg = pTab->nModuleArg;
  96986. char *zErr = 0;
  96987. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  96988. int iDb;
  96989. if( !zModuleName ){
  96990. return SQLITE_NOMEM;
  96991. }
  96992. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  96993. if( !pVTable ){
  96994. sqlite3DbFree(db, zModuleName);
  96995. return SQLITE_NOMEM;
  96996. }
  96997. pVTable->db = db;
  96998. pVTable->pMod = pMod;
  96999. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  97000. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  97001. /* Invoke the virtual table constructor */
  97002. assert( &db->pVtabCtx );
  97003. assert( xConstruct );
  97004. sCtx.pTab = pTab;
  97005. sCtx.pVTable = pVTable;
  97006. pPriorCtx = db->pVtabCtx;
  97007. db->pVtabCtx = &sCtx;
  97008. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  97009. db->pVtabCtx = pPriorCtx;
  97010. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  97011. if( SQLITE_OK!=rc ){
  97012. if( zErr==0 ){
  97013. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  97014. }else {
  97015. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  97016. sqlite3_free(zErr);
  97017. }
  97018. sqlite3DbFree(db, pVTable);
  97019. }else if( ALWAYS(pVTable->pVtab) ){
  97020. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  97021. ** the sqlite3_vtab object if successful. */
  97022. pVTable->pVtab->pModule = pMod->pModule;
  97023. pVTable->nRef = 1;
  97024. if( sCtx.pTab ){
  97025. const char *zFormat = "vtable constructor did not declare schema: %s";
  97026. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  97027. sqlite3VtabUnlock(pVTable);
  97028. rc = SQLITE_ERROR;
  97029. }else{
  97030. int iCol;
  97031. /* If everything went according to plan, link the new VTable structure
  97032. ** into the linked list headed by pTab->pVTable. Then loop through the
  97033. ** columns of the table to see if any of them contain the token "hidden".
  97034. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  97035. ** the type string. */
  97036. pVTable->pNext = pTab->pVTable;
  97037. pTab->pVTable = pVTable;
  97038. for(iCol=0; iCol<pTab->nCol; iCol++){
  97039. char *zType = pTab->aCol[iCol].zType;
  97040. int nType;
  97041. int i = 0;
  97042. if( !zType ) continue;
  97043. nType = sqlite3Strlen30(zType);
  97044. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  97045. for(i=0; i<nType; i++){
  97046. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  97047. && (zType[i+7]=='\0' || zType[i+7]==' ')
  97048. ){
  97049. i++;
  97050. break;
  97051. }
  97052. }
  97053. }
  97054. if( i<nType ){
  97055. int j;
  97056. int nDel = 6 + (zType[i+6] ? 1 : 0);
  97057. for(j=i; (j+nDel)<=nType; j++){
  97058. zType[j] = zType[j+nDel];
  97059. }
  97060. if( zType[i]=='\0' && i>0 ){
  97061. assert(zType[i-1]==' ');
  97062. zType[i-1] = '\0';
  97063. }
  97064. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  97065. }
  97066. }
  97067. }
  97068. }
  97069. sqlite3DbFree(db, zModuleName);
  97070. return rc;
  97071. }
  97072. /*
  97073. ** This function is invoked by the parser to call the xConnect() method
  97074. ** of the virtual table pTab. If an error occurs, an error code is returned
  97075. ** and an error left in pParse.
  97076. **
  97077. ** This call is a no-op if table pTab is not a virtual table.
  97078. */
  97079. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  97080. sqlite3 *db = pParse->db;
  97081. const char *zMod;
  97082. Module *pMod;
  97083. int rc;
  97084. assert( pTab );
  97085. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  97086. return SQLITE_OK;
  97087. }
  97088. /* Locate the required virtual table module */
  97089. zMod = pTab->azModuleArg[0];
  97090. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  97091. if( !pMod ){
  97092. const char *zModule = pTab->azModuleArg[0];
  97093. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  97094. rc = SQLITE_ERROR;
  97095. }else{
  97096. char *zErr = 0;
  97097. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  97098. if( rc!=SQLITE_OK ){
  97099. sqlite3ErrorMsg(pParse, "%s", zErr);
  97100. }
  97101. sqlite3DbFree(db, zErr);
  97102. }
  97103. return rc;
  97104. }
  97105. /*
  97106. ** Grow the db->aVTrans[] array so that there is room for at least one
  97107. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  97108. */
  97109. static int growVTrans(sqlite3 *db){
  97110. const int ARRAY_INCR = 5;
  97111. /* Grow the sqlite3.aVTrans array if required */
  97112. if( (db->nVTrans%ARRAY_INCR)==0 ){
  97113. VTable **aVTrans;
  97114. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  97115. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  97116. if( !aVTrans ){
  97117. return SQLITE_NOMEM;
  97118. }
  97119. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  97120. db->aVTrans = aVTrans;
  97121. }
  97122. return SQLITE_OK;
  97123. }
  97124. /*
  97125. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  97126. ** have already been reserved using growVTrans().
  97127. */
  97128. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  97129. /* Add pVtab to the end of sqlite3.aVTrans */
  97130. db->aVTrans[db->nVTrans++] = pVTab;
  97131. sqlite3VtabLock(pVTab);
  97132. }
  97133. /*
  97134. ** This function is invoked by the vdbe to call the xCreate method
  97135. ** of the virtual table named zTab in database iDb.
  97136. **
  97137. ** If an error occurs, *pzErr is set to point an an English language
  97138. ** description of the error and an SQLITE_XXX error code is returned.
  97139. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  97140. */
  97141. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  97142. int rc = SQLITE_OK;
  97143. Table *pTab;
  97144. Module *pMod;
  97145. const char *zMod;
  97146. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  97147. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  97148. /* Locate the required virtual table module */
  97149. zMod = pTab->azModuleArg[0];
  97150. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  97151. /* If the module has been registered and includes a Create method,
  97152. ** invoke it now. If the module has not been registered, return an
  97153. ** error. Otherwise, do nothing.
  97154. */
  97155. if( !pMod ){
  97156. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  97157. rc = SQLITE_ERROR;
  97158. }else{
  97159. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  97160. }
  97161. /* Justification of ALWAYS(): The xConstructor method is required to
  97162. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  97163. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  97164. rc = growVTrans(db);
  97165. if( rc==SQLITE_OK ){
  97166. addToVTrans(db, sqlite3GetVTable(db, pTab));
  97167. }
  97168. }
  97169. return rc;
  97170. }
  97171. /*
  97172. ** This function is used to set the schema of a virtual table. It is only
  97173. ** valid to call this function from within the xCreate() or xConnect() of a
  97174. ** virtual table module.
  97175. */
  97176. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  97177. Parse *pParse;
  97178. int rc = SQLITE_OK;
  97179. Table *pTab;
  97180. char *zErr = 0;
  97181. sqlite3_mutex_enter(db->mutex);
  97182. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  97183. sqlite3Error(db, SQLITE_MISUSE, 0);
  97184. sqlite3_mutex_leave(db->mutex);
  97185. return SQLITE_MISUSE_BKPT;
  97186. }
  97187. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  97188. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  97189. if( pParse==0 ){
  97190. rc = SQLITE_NOMEM;
  97191. }else{
  97192. pParse->declareVtab = 1;
  97193. pParse->db = db;
  97194. pParse->nQueryLoop = 1;
  97195. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  97196. && pParse->pNewTable
  97197. && !db->mallocFailed
  97198. && !pParse->pNewTable->pSelect
  97199. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  97200. ){
  97201. if( !pTab->aCol ){
  97202. pTab->aCol = pParse->pNewTable->aCol;
  97203. pTab->nCol = pParse->pNewTable->nCol;
  97204. pParse->pNewTable->nCol = 0;
  97205. pParse->pNewTable->aCol = 0;
  97206. }
  97207. db->pVtabCtx->pTab = 0;
  97208. }else{
  97209. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  97210. sqlite3DbFree(db, zErr);
  97211. rc = SQLITE_ERROR;
  97212. }
  97213. pParse->declareVtab = 0;
  97214. if( pParse->pVdbe ){
  97215. sqlite3VdbeFinalize(pParse->pVdbe);
  97216. }
  97217. sqlite3DeleteTable(db, pParse->pNewTable);
  97218. sqlite3StackFree(db, pParse);
  97219. }
  97220. assert( (rc&0xff)==rc );
  97221. rc = sqlite3ApiExit(db, rc);
  97222. sqlite3_mutex_leave(db->mutex);
  97223. return rc;
  97224. }
  97225. /*
  97226. ** This function is invoked by the vdbe to call the xDestroy method
  97227. ** of the virtual table named zTab in database iDb. This occurs
  97228. ** when a DROP TABLE is mentioned.
  97229. **
  97230. ** This call is a no-op if zTab is not a virtual table.
  97231. */
  97232. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  97233. int rc = SQLITE_OK;
  97234. Table *pTab;
  97235. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  97236. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  97237. VTable *p = vtabDisconnectAll(db, pTab);
  97238. assert( rc==SQLITE_OK );
  97239. rc = p->pMod->pModule->xDestroy(p->pVtab);
  97240. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  97241. if( rc==SQLITE_OK ){
  97242. assert( pTab->pVTable==p && p->pNext==0 );
  97243. p->pVtab = 0;
  97244. pTab->pVTable = 0;
  97245. sqlite3VtabUnlock(p);
  97246. }
  97247. }
  97248. return rc;
  97249. }
  97250. /*
  97251. ** This function invokes either the xRollback or xCommit method
  97252. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  97253. ** called is identified by the second argument, "offset", which is
  97254. ** the offset of the method to call in the sqlite3_module structure.
  97255. **
  97256. ** The array is cleared after invoking the callbacks.
  97257. */
  97258. static void callFinaliser(sqlite3 *db, int offset){
  97259. int i;
  97260. if( db->aVTrans ){
  97261. for(i=0; i<db->nVTrans; i++){
  97262. VTable *pVTab = db->aVTrans[i];
  97263. sqlite3_vtab *p = pVTab->pVtab;
  97264. if( p ){
  97265. int (*x)(sqlite3_vtab *);
  97266. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  97267. if( x ) x(p);
  97268. }
  97269. pVTab->iSavepoint = 0;
  97270. sqlite3VtabUnlock(pVTab);
  97271. }
  97272. sqlite3DbFree(db, db->aVTrans);
  97273. db->nVTrans = 0;
  97274. db->aVTrans = 0;
  97275. }
  97276. }
  97277. /*
  97278. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  97279. ** array. Return the error code for the first error that occurs, or
  97280. ** SQLITE_OK if all xSync operations are successful.
  97281. **
  97282. ** Set *pzErrmsg to point to a buffer that should be released using
  97283. ** sqlite3DbFree() containing an error message, if one is available.
  97284. */
  97285. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  97286. int i;
  97287. int rc = SQLITE_OK;
  97288. VTable **aVTrans = db->aVTrans;
  97289. db->aVTrans = 0;
  97290. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  97291. int (*x)(sqlite3_vtab *);
  97292. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  97293. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  97294. rc = x(pVtab);
  97295. sqlite3DbFree(db, *pzErrmsg);
  97296. *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  97297. sqlite3_free(pVtab->zErrMsg);
  97298. }
  97299. }
  97300. db->aVTrans = aVTrans;
  97301. return rc;
  97302. }
  97303. /*
  97304. ** Invoke the xRollback method of all virtual tables in the
  97305. ** sqlite3.aVTrans array. Then clear the array itself.
  97306. */
  97307. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  97308. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  97309. return SQLITE_OK;
  97310. }
  97311. /*
  97312. ** Invoke the xCommit method of all virtual tables in the
  97313. ** sqlite3.aVTrans array. Then clear the array itself.
  97314. */
  97315. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  97316. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  97317. return SQLITE_OK;
  97318. }
  97319. /*
  97320. ** If the virtual table pVtab supports the transaction interface
  97321. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  97322. ** not currently open, invoke the xBegin method now.
  97323. **
  97324. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  97325. ** in the sqlite3.aVTrans array.
  97326. */
  97327. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  97328. int rc = SQLITE_OK;
  97329. const sqlite3_module *pModule;
  97330. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  97331. ** than zero, then this function is being called from within a
  97332. ** virtual module xSync() callback. It is illegal to write to
  97333. ** virtual module tables in this case, so return SQLITE_LOCKED.
  97334. */
  97335. if( sqlite3VtabInSync(db) ){
  97336. return SQLITE_LOCKED;
  97337. }
  97338. if( !pVTab ){
  97339. return SQLITE_OK;
  97340. }
  97341. pModule = pVTab->pVtab->pModule;
  97342. if( pModule->xBegin ){
  97343. int i;
  97344. /* If pVtab is already in the aVTrans array, return early */
  97345. for(i=0; i<db->nVTrans; i++){
  97346. if( db->aVTrans[i]==pVTab ){
  97347. return SQLITE_OK;
  97348. }
  97349. }
  97350. /* Invoke the xBegin method. If successful, add the vtab to the
  97351. ** sqlite3.aVTrans[] array. */
  97352. rc = growVTrans(db);
  97353. if( rc==SQLITE_OK ){
  97354. rc = pModule->xBegin(pVTab->pVtab);
  97355. if( rc==SQLITE_OK ){
  97356. addToVTrans(db, pVTab);
  97357. }
  97358. }
  97359. }
  97360. return rc;
  97361. }
  97362. /*
  97363. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  97364. ** virtual tables that currently have an open transaction. Pass iSavepoint
  97365. ** as the second argument to the virtual table method invoked.
  97366. **
  97367. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  97368. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  97369. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  97370. ** an open transaction is invoked.
  97371. **
  97372. ** If any virtual table method returns an error code other than SQLITE_OK,
  97373. ** processing is abandoned and the error returned to the caller of this
  97374. ** function immediately. If all calls to virtual table methods are successful,
  97375. ** SQLITE_OK is returned.
  97376. */
  97377. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  97378. int rc = SQLITE_OK;
  97379. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  97380. assert( iSavepoint>=0 );
  97381. if( db->aVTrans ){
  97382. int i;
  97383. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  97384. VTable *pVTab = db->aVTrans[i];
  97385. const sqlite3_module *pMod = pVTab->pMod->pModule;
  97386. if( pVTab->pVtab && pMod->iVersion>=2 ){
  97387. int (*xMethod)(sqlite3_vtab *, int);
  97388. switch( op ){
  97389. case SAVEPOINT_BEGIN:
  97390. xMethod = pMod->xSavepoint;
  97391. pVTab->iSavepoint = iSavepoint+1;
  97392. break;
  97393. case SAVEPOINT_ROLLBACK:
  97394. xMethod = pMod->xRollbackTo;
  97395. break;
  97396. default:
  97397. xMethod = pMod->xRelease;
  97398. break;
  97399. }
  97400. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  97401. rc = xMethod(pVTab->pVtab, iSavepoint);
  97402. }
  97403. }
  97404. }
  97405. }
  97406. return rc;
  97407. }
  97408. /*
  97409. ** The first parameter (pDef) is a function implementation. The
  97410. ** second parameter (pExpr) is the first argument to this function.
  97411. ** If pExpr is a column in a virtual table, then let the virtual
  97412. ** table implementation have an opportunity to overload the function.
  97413. **
  97414. ** This routine is used to allow virtual table implementations to
  97415. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  97416. **
  97417. ** Return either the pDef argument (indicating no change) or a
  97418. ** new FuncDef structure that is marked as ephemeral using the
  97419. ** SQLITE_FUNC_EPHEM flag.
  97420. */
  97421. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  97422. sqlite3 *db, /* Database connection for reporting malloc problems */
  97423. FuncDef *pDef, /* Function to possibly overload */
  97424. int nArg, /* Number of arguments to the function */
  97425. Expr *pExpr /* First argument to the function */
  97426. ){
  97427. Table *pTab;
  97428. sqlite3_vtab *pVtab;
  97429. sqlite3_module *pMod;
  97430. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  97431. void *pArg = 0;
  97432. FuncDef *pNew;
  97433. int rc = 0;
  97434. char *zLowerName;
  97435. unsigned char *z;
  97436. /* Check to see the left operand is a column in a virtual table */
  97437. if( NEVER(pExpr==0) ) return pDef;
  97438. if( pExpr->op!=TK_COLUMN ) return pDef;
  97439. pTab = pExpr->pTab;
  97440. if( NEVER(pTab==0) ) return pDef;
  97441. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  97442. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  97443. assert( pVtab!=0 );
  97444. assert( pVtab->pModule!=0 );
  97445. pMod = (sqlite3_module *)pVtab->pModule;
  97446. if( pMod->xFindFunction==0 ) return pDef;
  97447. /* Call the xFindFunction method on the virtual table implementation
  97448. ** to see if the implementation wants to overload this function
  97449. */
  97450. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  97451. if( zLowerName ){
  97452. for(z=(unsigned char*)zLowerName; *z; z++){
  97453. *z = sqlite3UpperToLower[*z];
  97454. }
  97455. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  97456. sqlite3DbFree(db, zLowerName);
  97457. }
  97458. if( rc==0 ){
  97459. return pDef;
  97460. }
  97461. /* Create a new ephemeral function definition for the overloaded
  97462. ** function */
  97463. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  97464. + sqlite3Strlen30(pDef->zName) + 1);
  97465. if( pNew==0 ){
  97466. return pDef;
  97467. }
  97468. *pNew = *pDef;
  97469. pNew->zName = (char *)&pNew[1];
  97470. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  97471. pNew->xFunc = xFunc;
  97472. pNew->pUserData = pArg;
  97473. pNew->flags |= SQLITE_FUNC_EPHEM;
  97474. return pNew;
  97475. }
  97476. /*
  97477. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  97478. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  97479. ** array if it is missing. If pTab is already in the array, this routine
  97480. ** is a no-op.
  97481. */
  97482. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  97483. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97484. int i, n;
  97485. Table **apVtabLock;
  97486. assert( IsVirtual(pTab) );
  97487. for(i=0; i<pToplevel->nVtabLock; i++){
  97488. if( pTab==pToplevel->apVtabLock[i] ) return;
  97489. }
  97490. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  97491. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  97492. if( apVtabLock ){
  97493. pToplevel->apVtabLock = apVtabLock;
  97494. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  97495. }else{
  97496. pToplevel->db->mallocFailed = 1;
  97497. }
  97498. }
  97499. /*
  97500. ** Return the ON CONFLICT resolution mode in effect for the virtual
  97501. ** table update operation currently in progress.
  97502. **
  97503. ** The results of this routine are undefined unless it is called from
  97504. ** within an xUpdate method.
  97505. */
  97506. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  97507. static const unsigned char aMap[] = {
  97508. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  97509. };
  97510. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  97511. assert( OE_Ignore==4 && OE_Replace==5 );
  97512. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  97513. return (int)aMap[db->vtabOnConflict-1];
  97514. }
  97515. /*
  97516. ** Call from within the xCreate() or xConnect() methods to provide
  97517. ** the SQLite core with additional information about the behavior
  97518. ** of the virtual table being implemented.
  97519. */
  97520. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  97521. va_list ap;
  97522. int rc = SQLITE_OK;
  97523. sqlite3_mutex_enter(db->mutex);
  97524. va_start(ap, op);
  97525. switch( op ){
  97526. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  97527. VtabCtx *p = db->pVtabCtx;
  97528. if( !p ){
  97529. rc = SQLITE_MISUSE_BKPT;
  97530. }else{
  97531. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  97532. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  97533. }
  97534. break;
  97535. }
  97536. default:
  97537. rc = SQLITE_MISUSE_BKPT;
  97538. break;
  97539. }
  97540. va_end(ap);
  97541. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  97542. sqlite3_mutex_leave(db->mutex);
  97543. return rc;
  97544. }
  97545. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  97546. /************** End of vtab.c ************************************************/
  97547. /************** Begin file where.c *******************************************/
  97548. /*
  97549. ** 2001 September 15
  97550. **
  97551. ** The author disclaims copyright to this source code. In place of
  97552. ** a legal notice, here is a blessing:
  97553. **
  97554. ** May you do good and not evil.
  97555. ** May you find forgiveness for yourself and forgive others.
  97556. ** May you share freely, never taking more than you give.
  97557. **
  97558. *************************************************************************
  97559. ** This module contains C code that generates VDBE code used to process
  97560. ** the WHERE clause of SQL statements. This module is responsible for
  97561. ** generating the code that loops through a table looking for applicable
  97562. ** rows. Indices are selected and used to speed the search when doing
  97563. ** so is applicable. Because this module is responsible for selecting
  97564. ** indices, you might also think of this module as the "query optimizer".
  97565. */
  97566. /*
  97567. ** Trace output macros
  97568. */
  97569. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  97570. /***/ int sqlite3WhereTrace = 0;
  97571. #endif
  97572. #if defined(SQLITE_DEBUG) \
  97573. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  97574. # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  97575. #else
  97576. # define WHERETRACE(X)
  97577. #endif
  97578. /* Forward reference
  97579. */
  97580. typedef struct WhereClause WhereClause;
  97581. typedef struct WhereMaskSet WhereMaskSet;
  97582. typedef struct WhereOrInfo WhereOrInfo;
  97583. typedef struct WhereAndInfo WhereAndInfo;
  97584. typedef struct WhereCost WhereCost;
  97585. /*
  97586. ** The query generator uses an array of instances of this structure to
  97587. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  97588. ** clause subexpression is separated from the others by AND operators,
  97589. ** usually, or sometimes subexpressions separated by OR.
  97590. **
  97591. ** All WhereTerms are collected into a single WhereClause structure.
  97592. ** The following identity holds:
  97593. **
  97594. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  97595. **
  97596. ** When a term is of the form:
  97597. **
  97598. ** X <op> <expr>
  97599. **
  97600. ** where X is a column name and <op> is one of certain operators,
  97601. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  97602. ** cursor number and column number for X. WhereTerm.eOperator records
  97603. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  97604. ** use of a bitmask encoding for the operator allows us to search
  97605. ** quickly for terms that match any of several different operators.
  97606. **
  97607. ** A WhereTerm might also be two or more subterms connected by OR:
  97608. **
  97609. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  97610. **
  97611. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  97612. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  97613. ** is collected about the
  97614. **
  97615. ** If a term in the WHERE clause does not match either of the two previous
  97616. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  97617. ** to the original subexpression content and wtFlags is set up appropriately
  97618. ** but no other fields in the WhereTerm object are meaningful.
  97619. **
  97620. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  97621. ** but they do so indirectly. A single WhereMaskSet structure translates
  97622. ** cursor number into bits and the translated bit is stored in the prereq
  97623. ** fields. The translation is used in order to maximize the number of
  97624. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  97625. ** spread out over the non-negative integers. For example, the cursor
  97626. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  97627. ** translates these sparse cursor numbers into consecutive integers
  97628. ** beginning with 0 in order to make the best possible use of the available
  97629. ** bits in the Bitmask. So, in the example above, the cursor numbers
  97630. ** would be mapped into integers 0 through 7.
  97631. **
  97632. ** The number of terms in a join is limited by the number of bits
  97633. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  97634. ** is only able to process joins with 64 or fewer tables.
  97635. */
  97636. typedef struct WhereTerm WhereTerm;
  97637. struct WhereTerm {
  97638. Expr *pExpr; /* Pointer to the subexpression that is this term */
  97639. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  97640. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  97641. union {
  97642. int leftColumn; /* Column number of X in "X <op> <expr>" */
  97643. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  97644. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  97645. } u;
  97646. u16 eOperator; /* A WO_xx value describing <op> */
  97647. u8 wtFlags; /* TERM_xxx bit flags. See below */
  97648. u8 nChild; /* Number of children that must disable us */
  97649. WhereClause *pWC; /* The clause this term is part of */
  97650. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  97651. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  97652. };
  97653. /*
  97654. ** Allowed values of WhereTerm.wtFlags
  97655. */
  97656. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  97657. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  97658. #define TERM_CODED 0x04 /* This term is already coded */
  97659. #define TERM_COPIED 0x08 /* Has a child */
  97660. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  97661. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  97662. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  97663. #ifdef SQLITE_ENABLE_STAT3
  97664. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  97665. #else
  97666. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  97667. #endif
  97668. /*
  97669. ** An instance of the following structure holds all information about a
  97670. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  97671. **
  97672. ** Explanation of pOuter: For a WHERE clause of the form
  97673. **
  97674. ** a AND ((b AND c) OR (d AND e)) AND f
  97675. **
  97676. ** There are separate WhereClause objects for the whole clause and for
  97677. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  97678. ** subclauses points to the WhereClause object for the whole clause.
  97679. */
  97680. struct WhereClause {
  97681. Parse *pParse; /* The parser context */
  97682. WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  97683. WhereClause *pOuter; /* Outer conjunction */
  97684. u8 op; /* Split operator. TK_AND or TK_OR */
  97685. u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
  97686. int nTerm; /* Number of terms */
  97687. int nSlot; /* Number of entries in a[] */
  97688. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  97689. #if defined(SQLITE_SMALL_STACK)
  97690. WhereTerm aStatic[1]; /* Initial static space for a[] */
  97691. #else
  97692. WhereTerm aStatic[8]; /* Initial static space for a[] */
  97693. #endif
  97694. };
  97695. /*
  97696. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  97697. ** a dynamically allocated instance of the following structure.
  97698. */
  97699. struct WhereOrInfo {
  97700. WhereClause wc; /* Decomposition into subterms */
  97701. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  97702. };
  97703. /*
  97704. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  97705. ** a dynamically allocated instance of the following structure.
  97706. */
  97707. struct WhereAndInfo {
  97708. WhereClause wc; /* The subexpression broken out */
  97709. };
  97710. /*
  97711. ** An instance of the following structure keeps track of a mapping
  97712. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  97713. **
  97714. ** The VDBE cursor numbers are small integers contained in
  97715. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  97716. ** clause, the cursor numbers might not begin with 0 and they might
  97717. ** contain gaps in the numbering sequence. But we want to make maximum
  97718. ** use of the bits in our bitmasks. This structure provides a mapping
  97719. ** from the sparse cursor numbers into consecutive integers beginning
  97720. ** with 0.
  97721. **
  97722. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  97723. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  97724. **
  97725. ** For example, if the WHERE clause expression used these VDBE
  97726. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  97727. ** would map those cursor numbers into bits 0 through 5.
  97728. **
  97729. ** Note that the mapping is not necessarily ordered. In the example
  97730. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  97731. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  97732. ** does not really matter. What is important is that sparse cursor
  97733. ** numbers all get mapped into bit numbers that begin with 0 and contain
  97734. ** no gaps.
  97735. */
  97736. struct WhereMaskSet {
  97737. int n; /* Number of assigned cursor values */
  97738. int ix[BMS]; /* Cursor assigned to each bit */
  97739. };
  97740. /*
  97741. ** A WhereCost object records a lookup strategy and the estimated
  97742. ** cost of pursuing that strategy.
  97743. */
  97744. struct WhereCost {
  97745. WherePlan plan; /* The lookup strategy */
  97746. double rCost; /* Overall cost of pursuing this search strategy */
  97747. Bitmask used; /* Bitmask of cursors used by this plan */
  97748. };
  97749. /*
  97750. ** Bitmasks for the operators that indices are able to exploit. An
  97751. ** OR-ed combination of these values can be used when searching for
  97752. ** terms in the where clause.
  97753. */
  97754. #define WO_IN 0x001
  97755. #define WO_EQ 0x002
  97756. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  97757. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  97758. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  97759. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  97760. #define WO_MATCH 0x040
  97761. #define WO_ISNULL 0x080
  97762. #define WO_OR 0x100 /* Two or more OR-connected terms */
  97763. #define WO_AND 0x200 /* Two or more AND-connected terms */
  97764. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  97765. #define WO_NOOP 0x800 /* This term does not restrict search space */
  97766. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  97767. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  97768. /*
  97769. ** Value for wsFlags returned by bestIndex() and stored in
  97770. ** WhereLevel.wsFlags. These flags determine which search
  97771. ** strategies are appropriate.
  97772. **
  97773. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  97774. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  97775. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  97776. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  97777. ** the "op" parameter to findTerm when we are resolving equality constraints.
  97778. ** ISNULL constraints will then not be used on the right table of a left
  97779. ** join. Tickets #2177 and #2189.
  97780. */
  97781. #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  97782. #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  97783. #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
  97784. #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  97785. #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  97786. #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
  97787. #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
  97788. #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
  97789. #define WHERE_IN_ABLE 0x080f1000 /* Able to support an IN operator */
  97790. #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  97791. #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  97792. #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
  97793. #define WHERE_IDX_ONLY 0x00400000 /* Use index only - omit table */
  97794. #define WHERE_ORDERED 0x00800000 /* Output will appear in correct order */
  97795. #define WHERE_REVERSE 0x01000000 /* Scan in reverse order */
  97796. #define WHERE_UNIQUE 0x02000000 /* Selects no more than one row */
  97797. #define WHERE_ALL_UNIQUE 0x04000000 /* This and all prior have one row */
  97798. #define WHERE_OB_UNIQUE 0x00004000 /* Values in ORDER BY columns are
  97799. ** different for every output row */
  97800. #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  97801. #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  97802. #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
  97803. #define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
  97804. #define WHERE_COVER_SCAN 0x80000000 /* Full scan of a covering index */
  97805. /*
  97806. ** This module contains many separate subroutines that work together to
  97807. ** find the best indices to use for accessing a particular table in a query.
  97808. ** An instance of the following structure holds context information about the
  97809. ** index search so that it can be more easily passed between the various
  97810. ** routines.
  97811. */
  97812. typedef struct WhereBestIdx WhereBestIdx;
  97813. struct WhereBestIdx {
  97814. Parse *pParse; /* Parser context */
  97815. WhereClause *pWC; /* The WHERE clause */
  97816. struct SrcList_item *pSrc; /* The FROM clause term to search */
  97817. Bitmask notReady; /* Mask of cursors not available */
  97818. Bitmask notValid; /* Cursors not available for any purpose */
  97819. ExprList *pOrderBy; /* The ORDER BY clause */
  97820. ExprList *pDistinct; /* The select-list if query is DISTINCT */
  97821. sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
  97822. int i, n; /* Which loop is being coded; # of loops */
  97823. WhereLevel *aLevel; /* Info about outer loops */
  97824. WhereCost cost; /* Lowest cost query plan */
  97825. };
  97826. /*
  97827. ** Return TRUE if the probe cost is less than the baseline cost
  97828. */
  97829. static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
  97830. if( pProbe->rCost<pBaseline->rCost ) return 1;
  97831. if( pProbe->rCost>pBaseline->rCost ) return 0;
  97832. if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
  97833. if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
  97834. return 0;
  97835. }
  97836. /*
  97837. ** Initialize a preallocated WhereClause structure.
  97838. */
  97839. static void whereClauseInit(
  97840. WhereClause *pWC, /* The WhereClause to be initialized */
  97841. Parse *pParse, /* The parsing context */
  97842. WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
  97843. u16 wctrlFlags /* Might include WHERE_AND_ONLY */
  97844. ){
  97845. pWC->pParse = pParse;
  97846. pWC->pMaskSet = pMaskSet;
  97847. pWC->pOuter = 0;
  97848. pWC->nTerm = 0;
  97849. pWC->nSlot = ArraySize(pWC->aStatic);
  97850. pWC->a = pWC->aStatic;
  97851. pWC->wctrlFlags = wctrlFlags;
  97852. }
  97853. /* Forward reference */
  97854. static void whereClauseClear(WhereClause*);
  97855. /*
  97856. ** Deallocate all memory associated with a WhereOrInfo object.
  97857. */
  97858. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  97859. whereClauseClear(&p->wc);
  97860. sqlite3DbFree(db, p);
  97861. }
  97862. /*
  97863. ** Deallocate all memory associated with a WhereAndInfo object.
  97864. */
  97865. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  97866. whereClauseClear(&p->wc);
  97867. sqlite3DbFree(db, p);
  97868. }
  97869. /*
  97870. ** Deallocate a WhereClause structure. The WhereClause structure
  97871. ** itself is not freed. This routine is the inverse of whereClauseInit().
  97872. */
  97873. static void whereClauseClear(WhereClause *pWC){
  97874. int i;
  97875. WhereTerm *a;
  97876. sqlite3 *db = pWC->pParse->db;
  97877. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  97878. if( a->wtFlags & TERM_DYNAMIC ){
  97879. sqlite3ExprDelete(db, a->pExpr);
  97880. }
  97881. if( a->wtFlags & TERM_ORINFO ){
  97882. whereOrInfoDelete(db, a->u.pOrInfo);
  97883. }else if( a->wtFlags & TERM_ANDINFO ){
  97884. whereAndInfoDelete(db, a->u.pAndInfo);
  97885. }
  97886. }
  97887. if( pWC->a!=pWC->aStatic ){
  97888. sqlite3DbFree(db, pWC->a);
  97889. }
  97890. }
  97891. /*
  97892. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  97893. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  97894. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  97895. ** 0 is returned if the new WhereTerm could not be added due to a memory
  97896. ** allocation error. The memory allocation failure will be recorded in
  97897. ** the db->mallocFailed flag so that higher-level functions can detect it.
  97898. **
  97899. ** This routine will increase the size of the pWC->a[] array as necessary.
  97900. **
  97901. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  97902. ** for freeing the expression p is assumed by the WhereClause object pWC.
  97903. ** This is true even if this routine fails to allocate a new WhereTerm.
  97904. **
  97905. ** WARNING: This routine might reallocate the space used to store
  97906. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  97907. ** calling this routine. Such pointers may be reinitialized by referencing
  97908. ** the pWC->a[] array.
  97909. */
  97910. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  97911. WhereTerm *pTerm;
  97912. int idx;
  97913. testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
  97914. if( pWC->nTerm>=pWC->nSlot ){
  97915. WhereTerm *pOld = pWC->a;
  97916. sqlite3 *db = pWC->pParse->db;
  97917. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  97918. if( pWC->a==0 ){
  97919. if( wtFlags & TERM_DYNAMIC ){
  97920. sqlite3ExprDelete(db, p);
  97921. }
  97922. pWC->a = pOld;
  97923. return 0;
  97924. }
  97925. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  97926. if( pOld!=pWC->aStatic ){
  97927. sqlite3DbFree(db, pOld);
  97928. }
  97929. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  97930. }
  97931. pTerm = &pWC->a[idx = pWC->nTerm++];
  97932. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  97933. pTerm->wtFlags = wtFlags;
  97934. pTerm->pWC = pWC;
  97935. pTerm->iParent = -1;
  97936. return idx;
  97937. }
  97938. /*
  97939. ** This routine identifies subexpressions in the WHERE clause where
  97940. ** each subexpression is separated by the AND operator or some other
  97941. ** operator specified in the op parameter. The WhereClause structure
  97942. ** is filled with pointers to subexpressions. For example:
  97943. **
  97944. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  97945. ** \________/ \_______________/ \________________/
  97946. ** slot[0] slot[1] slot[2]
  97947. **
  97948. ** The original WHERE clause in pExpr is unaltered. All this routine
  97949. ** does is make slot[] entries point to substructure within pExpr.
  97950. **
  97951. ** In the previous sentence and in the diagram, "slot[]" refers to
  97952. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  97953. ** all terms of the WHERE clause.
  97954. */
  97955. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  97956. pWC->op = (u8)op;
  97957. if( pExpr==0 ) return;
  97958. if( pExpr->op!=op ){
  97959. whereClauseInsert(pWC, pExpr, 0);
  97960. }else{
  97961. whereSplit(pWC, pExpr->pLeft, op);
  97962. whereSplit(pWC, pExpr->pRight, op);
  97963. }
  97964. }
  97965. /*
  97966. ** Initialize an expression mask set (a WhereMaskSet object)
  97967. */
  97968. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  97969. /*
  97970. ** Return the bitmask for the given cursor number. Return 0 if
  97971. ** iCursor is not in the set.
  97972. */
  97973. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  97974. int i;
  97975. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  97976. for(i=0; i<pMaskSet->n; i++){
  97977. if( pMaskSet->ix[i]==iCursor ){
  97978. return ((Bitmask)1)<<i;
  97979. }
  97980. }
  97981. return 0;
  97982. }
  97983. /*
  97984. ** Create a new mask for cursor iCursor.
  97985. **
  97986. ** There is one cursor per table in the FROM clause. The number of
  97987. ** tables in the FROM clause is limited by a test early in the
  97988. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  97989. ** array will never overflow.
  97990. */
  97991. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  97992. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  97993. pMaskSet->ix[pMaskSet->n++] = iCursor;
  97994. }
  97995. /*
  97996. ** This routine walks (recursively) an expression tree and generates
  97997. ** a bitmask indicating which tables are used in that expression
  97998. ** tree.
  97999. **
  98000. ** In order for this routine to work, the calling function must have
  98001. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  98002. ** the header comment on that routine for additional information.
  98003. ** The sqlite3ResolveExprNames() routines looks for column names and
  98004. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  98005. ** the VDBE cursor number of the table. This routine just has to
  98006. ** translate the cursor numbers into bitmask values and OR all
  98007. ** the bitmasks together.
  98008. */
  98009. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  98010. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  98011. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  98012. Bitmask mask = 0;
  98013. if( p==0 ) return 0;
  98014. if( p->op==TK_COLUMN ){
  98015. mask = getMask(pMaskSet, p->iTable);
  98016. return mask;
  98017. }
  98018. mask = exprTableUsage(pMaskSet, p->pRight);
  98019. mask |= exprTableUsage(pMaskSet, p->pLeft);
  98020. if( ExprHasProperty(p, EP_xIsSelect) ){
  98021. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  98022. }else{
  98023. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  98024. }
  98025. return mask;
  98026. }
  98027. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  98028. int i;
  98029. Bitmask mask = 0;
  98030. if( pList ){
  98031. for(i=0; i<pList->nExpr; i++){
  98032. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  98033. }
  98034. }
  98035. return mask;
  98036. }
  98037. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  98038. Bitmask mask = 0;
  98039. while( pS ){
  98040. SrcList *pSrc = pS->pSrc;
  98041. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  98042. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  98043. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  98044. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  98045. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  98046. if( ALWAYS(pSrc!=0) ){
  98047. int i;
  98048. for(i=0; i<pSrc->nSrc; i++){
  98049. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  98050. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  98051. }
  98052. }
  98053. pS = pS->pPrior;
  98054. }
  98055. return mask;
  98056. }
  98057. /*
  98058. ** Return TRUE if the given operator is one of the operators that is
  98059. ** allowed for an indexable WHERE clause term. The allowed operators are
  98060. ** "=", "<", ">", "<=", ">=", and "IN".
  98061. **
  98062. ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
  98063. ** of one of the following forms: column = expression column > expression
  98064. ** column >= expression column < expression column <= expression
  98065. ** expression = column expression > column expression >= column
  98066. ** expression < column expression <= column column IN
  98067. ** (expression-list) column IN (subquery) column IS NULL
  98068. */
  98069. static int allowedOp(int op){
  98070. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  98071. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  98072. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  98073. assert( TK_GE==TK_EQ+4 );
  98074. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  98075. }
  98076. /*
  98077. ** Swap two objects of type TYPE.
  98078. */
  98079. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  98080. /*
  98081. ** Commute a comparison operator. Expressions of the form "X op Y"
  98082. ** are converted into "Y op X".
  98083. **
  98084. ** If left/right precedence rules come into play when determining the
  98085. ** collating
  98086. ** side of the comparison, it remains associated with the same side after
  98087. ** the commutation. So "Y collate NOCASE op X" becomes
  98088. ** "X op Y". This is because any collation sequence on
  98089. ** the left hand side of a comparison overrides any collation sequence
  98090. ** attached to the right. For the same reason the EP_Collate flag
  98091. ** is not commuted.
  98092. */
  98093. static void exprCommute(Parse *pParse, Expr *pExpr){
  98094. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  98095. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  98096. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  98097. if( expRight==expLeft ){
  98098. /* Either X and Y both have COLLATE operator or neither do */
  98099. if( expRight ){
  98100. /* Both X and Y have COLLATE operators. Make sure X is always
  98101. ** used by clearing the EP_Collate flag from Y. */
  98102. pExpr->pRight->flags &= ~EP_Collate;
  98103. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  98104. /* Neither X nor Y have COLLATE operators, but X has a non-default
  98105. ** collating sequence. So add the EP_Collate marker on X to cause
  98106. ** it to be searched first. */
  98107. pExpr->pLeft->flags |= EP_Collate;
  98108. }
  98109. }
  98110. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  98111. if( pExpr->op>=TK_GT ){
  98112. assert( TK_LT==TK_GT+2 );
  98113. assert( TK_GE==TK_LE+2 );
  98114. assert( TK_GT>TK_EQ );
  98115. assert( TK_GT<TK_LE );
  98116. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  98117. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  98118. }
  98119. }
  98120. /*
  98121. ** Translate from TK_xx operator to WO_xx bitmask.
  98122. */
  98123. static u16 operatorMask(int op){
  98124. u16 c;
  98125. assert( allowedOp(op) );
  98126. if( op==TK_IN ){
  98127. c = WO_IN;
  98128. }else if( op==TK_ISNULL ){
  98129. c = WO_ISNULL;
  98130. }else{
  98131. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  98132. c = (u16)(WO_EQ<<(op-TK_EQ));
  98133. }
  98134. assert( op!=TK_ISNULL || c==WO_ISNULL );
  98135. assert( op!=TK_IN || c==WO_IN );
  98136. assert( op!=TK_EQ || c==WO_EQ );
  98137. assert( op!=TK_LT || c==WO_LT );
  98138. assert( op!=TK_LE || c==WO_LE );
  98139. assert( op!=TK_GT || c==WO_GT );
  98140. assert( op!=TK_GE || c==WO_GE );
  98141. return c;
  98142. }
  98143. /*
  98144. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  98145. ** where X is a reference to the iColumn of table iCur and <op> is one of
  98146. ** the WO_xx operator codes specified by the op parameter.
  98147. ** Return a pointer to the term. Return 0 if not found.
  98148. **
  98149. ** The term returned might by Y=<expr> if there is another constraint in
  98150. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  98151. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  98152. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  98153. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  98154. ** and the second is for the column number. There are 22 slots in aEquiv[]
  98155. ** so that means we can look for X plus up to 10 other equivalent values.
  98156. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  98157. ** and ... and A9=A10 and A10=<expr>.
  98158. **
  98159. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  98160. ** then try for the one with no dependencies on <expr> - in other words where
  98161. ** <expr> is a constant expression of some kind. Only return entries of
  98162. ** the form "X <op> Y" where Y is a column in another table if no terms of
  98163. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  98164. ** exist, try to return a term that does not use WO_EQUIV.
  98165. */
  98166. static WhereTerm *findTerm(
  98167. WhereClause *pWC, /* The WHERE clause to be searched */
  98168. int iCur, /* Cursor number of LHS */
  98169. int iColumn, /* Column number of LHS */
  98170. Bitmask notReady, /* RHS must not overlap with this mask */
  98171. u32 op, /* Mask of WO_xx values describing operator */
  98172. Index *pIdx /* Must be compatible with this index, if not NULL */
  98173. ){
  98174. WhereTerm *pTerm; /* Term being examined as possible result */
  98175. WhereTerm *pResult = 0; /* The answer to return */
  98176. WhereClause *pWCOrig = pWC; /* Original pWC value */
  98177. int j, k; /* Loop counters */
  98178. Expr *pX; /* Pointer to an expression */
  98179. Parse *pParse; /* Parsing context */
  98180. int iOrigCol = iColumn; /* Original value of iColumn */
  98181. int nEquiv = 2; /* Number of entires in aEquiv[] */
  98182. int iEquiv = 2; /* Number of entries of aEquiv[] processed so far */
  98183. int aEquiv[22]; /* iCur,iColumn and up to 10 other equivalents */
  98184. assert( iCur>=0 );
  98185. aEquiv[0] = iCur;
  98186. aEquiv[1] = iColumn;
  98187. for(;;){
  98188. for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
  98189. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  98190. if( pTerm->leftCursor==iCur
  98191. && pTerm->u.leftColumn==iColumn
  98192. ){
  98193. if( (pTerm->prereqRight & notReady)==0
  98194. && (pTerm->eOperator & op & WO_ALL)!=0
  98195. ){
  98196. if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
  98197. CollSeq *pColl;
  98198. char idxaff;
  98199. pX = pTerm->pExpr;
  98200. pParse = pWC->pParse;
  98201. idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
  98202. if( !sqlite3IndexAffinityOk(pX, idxaff) ){
  98203. continue;
  98204. }
  98205. /* Figure out the collation sequence required from an index for
  98206. ** it to be useful for optimising expression pX. Store this
  98207. ** value in variable pColl.
  98208. */
  98209. assert(pX->pLeft);
  98210. pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
  98211. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  98212. for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
  98213. if( NEVER(j>=pIdx->nColumn) ) return 0;
  98214. }
  98215. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
  98216. continue;
  98217. }
  98218. }
  98219. if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
  98220. pResult = pTerm;
  98221. goto findTerm_success;
  98222. }else if( pResult==0 ){
  98223. pResult = pTerm;
  98224. }
  98225. }
  98226. if( (pTerm->eOperator & WO_EQUIV)!=0
  98227. && nEquiv<ArraySize(aEquiv)
  98228. ){
  98229. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  98230. assert( pX->op==TK_COLUMN );
  98231. for(j=0; j<nEquiv; j+=2){
  98232. if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
  98233. }
  98234. if( j==nEquiv ){
  98235. aEquiv[j] = pX->iTable;
  98236. aEquiv[j+1] = pX->iColumn;
  98237. nEquiv += 2;
  98238. }
  98239. }
  98240. }
  98241. }
  98242. }
  98243. if( iEquiv>=nEquiv ) break;
  98244. iCur = aEquiv[iEquiv++];
  98245. iColumn = aEquiv[iEquiv++];
  98246. }
  98247. findTerm_success:
  98248. return pResult;
  98249. }
  98250. /* Forward reference */
  98251. static void exprAnalyze(SrcList*, WhereClause*, int);
  98252. /*
  98253. ** Call exprAnalyze on all terms in a WHERE clause.
  98254. **
  98255. **
  98256. */
  98257. static void exprAnalyzeAll(
  98258. SrcList *pTabList, /* the FROM clause */
  98259. WhereClause *pWC /* the WHERE clause to be analyzed */
  98260. ){
  98261. int i;
  98262. for(i=pWC->nTerm-1; i>=0; i--){
  98263. exprAnalyze(pTabList, pWC, i);
  98264. }
  98265. }
  98266. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  98267. /*
  98268. ** Check to see if the given expression is a LIKE or GLOB operator that
  98269. ** can be optimized using inequality constraints. Return TRUE if it is
  98270. ** so and false if not.
  98271. **
  98272. ** In order for the operator to be optimizible, the RHS must be a string
  98273. ** literal that does not begin with a wildcard.
  98274. */
  98275. static int isLikeOrGlob(
  98276. Parse *pParse, /* Parsing and code generating context */
  98277. Expr *pExpr, /* Test this expression */
  98278. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  98279. int *pisComplete, /* True if the only wildcard is % in the last character */
  98280. int *pnoCase /* True if uppercase is equivalent to lowercase */
  98281. ){
  98282. const char *z = 0; /* String on RHS of LIKE operator */
  98283. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  98284. ExprList *pList; /* List of operands to the LIKE operator */
  98285. int c; /* One character in z[] */
  98286. int cnt; /* Number of non-wildcard prefix characters */
  98287. char wc[3]; /* Wildcard characters */
  98288. sqlite3 *db = pParse->db; /* Database connection */
  98289. sqlite3_value *pVal = 0;
  98290. int op; /* Opcode of pRight */
  98291. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  98292. return 0;
  98293. }
  98294. #ifdef SQLITE_EBCDIC
  98295. if( *pnoCase ) return 0;
  98296. #endif
  98297. pList = pExpr->x.pList;
  98298. pLeft = pList->a[1].pExpr;
  98299. if( pLeft->op!=TK_COLUMN
  98300. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  98301. || IsVirtual(pLeft->pTab)
  98302. ){
  98303. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  98304. ** be the name of an indexed column with TEXT affinity. */
  98305. return 0;
  98306. }
  98307. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  98308. pRight = pList->a[0].pExpr;
  98309. op = pRight->op;
  98310. if( op==TK_REGISTER ){
  98311. op = pRight->op2;
  98312. }
  98313. if( op==TK_VARIABLE ){
  98314. Vdbe *pReprepare = pParse->pReprepare;
  98315. int iCol = pRight->iColumn;
  98316. pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
  98317. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  98318. z = (char *)sqlite3_value_text(pVal);
  98319. }
  98320. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  98321. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  98322. }else if( op==TK_STRING ){
  98323. z = pRight->u.zToken;
  98324. }
  98325. if( z ){
  98326. cnt = 0;
  98327. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  98328. cnt++;
  98329. }
  98330. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  98331. Expr *pPrefix;
  98332. *pisComplete = c==wc[0] && z[cnt+1]==0;
  98333. pPrefix = sqlite3Expr(db, TK_STRING, z);
  98334. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  98335. *ppPrefix = pPrefix;
  98336. if( op==TK_VARIABLE ){
  98337. Vdbe *v = pParse->pVdbe;
  98338. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  98339. if( *pisComplete && pRight->u.zToken[1] ){
  98340. /* If the rhs of the LIKE expression is a variable, and the current
  98341. ** value of the variable means there is no need to invoke the LIKE
  98342. ** function, then no OP_Variable will be added to the program.
  98343. ** This causes problems for the sqlite3_bind_parameter_name()
  98344. ** API. To workaround them, add a dummy OP_Variable here.
  98345. */
  98346. int r1 = sqlite3GetTempReg(pParse);
  98347. sqlite3ExprCodeTarget(pParse, pRight, r1);
  98348. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  98349. sqlite3ReleaseTempReg(pParse, r1);
  98350. }
  98351. }
  98352. }else{
  98353. z = 0;
  98354. }
  98355. }
  98356. sqlite3ValueFree(pVal);
  98357. return (z!=0);
  98358. }
  98359. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  98360. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98361. /*
  98362. ** Check to see if the given expression is of the form
  98363. **
  98364. ** column MATCH expr
  98365. **
  98366. ** If it is then return TRUE. If not, return FALSE.
  98367. */
  98368. static int isMatchOfColumn(
  98369. Expr *pExpr /* Test this expression */
  98370. ){
  98371. ExprList *pList;
  98372. if( pExpr->op!=TK_FUNCTION ){
  98373. return 0;
  98374. }
  98375. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  98376. return 0;
  98377. }
  98378. pList = pExpr->x.pList;
  98379. if( pList->nExpr!=2 ){
  98380. return 0;
  98381. }
  98382. if( pList->a[1].pExpr->op != TK_COLUMN ){
  98383. return 0;
  98384. }
  98385. return 1;
  98386. }
  98387. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  98388. /*
  98389. ** If the pBase expression originated in the ON or USING clause of
  98390. ** a join, then transfer the appropriate markings over to derived.
  98391. */
  98392. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  98393. pDerived->flags |= pBase->flags & EP_FromJoin;
  98394. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  98395. }
  98396. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  98397. /*
  98398. ** Analyze a term that consists of two or more OR-connected
  98399. ** subterms. So in:
  98400. **
  98401. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  98402. ** ^^^^^^^^^^^^^^^^^^^^
  98403. **
  98404. ** This routine analyzes terms such as the middle term in the above example.
  98405. ** A WhereOrTerm object is computed and attached to the term under
  98406. ** analysis, regardless of the outcome of the analysis. Hence:
  98407. **
  98408. ** WhereTerm.wtFlags |= TERM_ORINFO
  98409. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  98410. **
  98411. ** The term being analyzed must have two or more of OR-connected subterms.
  98412. ** A single subterm might be a set of AND-connected sub-subterms.
  98413. ** Examples of terms under analysis:
  98414. **
  98415. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  98416. ** (B) x=expr1 OR expr2=x OR x=expr3
  98417. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  98418. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  98419. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  98420. **
  98421. ** CASE 1:
  98422. **
  98423. ** If all subterms are of the form T.C=expr for some single column of C and
  98424. ** a single table T (as shown in example B above) then create a new virtual
  98425. ** term that is an equivalent IN expression. In other words, if the term
  98426. ** being analyzed is:
  98427. **
  98428. ** x = expr1 OR expr2 = x OR x = expr3
  98429. **
  98430. ** then create a new virtual term like this:
  98431. **
  98432. ** x IN (expr1,expr2,expr3)
  98433. **
  98434. ** CASE 2:
  98435. **
  98436. ** If all subterms are indexable by a single table T, then set
  98437. **
  98438. ** WhereTerm.eOperator = WO_OR
  98439. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  98440. **
  98441. ** A subterm is "indexable" if it is of the form
  98442. ** "T.C <op> <expr>" where C is any column of table T and
  98443. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  98444. ** A subterm is also indexable if it is an AND of two or more
  98445. ** subsubterms at least one of which is indexable. Indexable AND
  98446. ** subterms have their eOperator set to WO_AND and they have
  98447. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  98448. **
  98449. ** From another point of view, "indexable" means that the subterm could
  98450. ** potentially be used with an index if an appropriate index exists.
  98451. ** This analysis does not consider whether or not the index exists; that
  98452. ** is something the bestIndex() routine will determine. This analysis
  98453. ** only looks at whether subterms appropriate for indexing exist.
  98454. **
  98455. ** All examples A through E above all satisfy case 2. But if a term
  98456. ** also statisfies case 1 (such as B) we know that the optimizer will
  98457. ** always prefer case 1, so in that case we pretend that case 2 is not
  98458. ** satisfied.
  98459. **
  98460. ** It might be the case that multiple tables are indexable. For example,
  98461. ** (E) above is indexable on tables P, Q, and R.
  98462. **
  98463. ** Terms that satisfy case 2 are candidates for lookup by using
  98464. ** separate indices to find rowids for each subterm and composing
  98465. ** the union of all rowids using a RowSet object. This is similar
  98466. ** to "bitmap indices" in other database engines.
  98467. **
  98468. ** OTHERWISE:
  98469. **
  98470. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  98471. ** zero. This term is not useful for search.
  98472. */
  98473. static void exprAnalyzeOrTerm(
  98474. SrcList *pSrc, /* the FROM clause */
  98475. WhereClause *pWC, /* the complete WHERE clause */
  98476. int idxTerm /* Index of the OR-term to be analyzed */
  98477. ){
  98478. Parse *pParse = pWC->pParse; /* Parser context */
  98479. sqlite3 *db = pParse->db; /* Database connection */
  98480. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  98481. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  98482. WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  98483. int i; /* Loop counters */
  98484. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  98485. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  98486. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  98487. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  98488. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  98489. /*
  98490. ** Break the OR clause into its separate subterms. The subterms are
  98491. ** stored in a WhereClause structure containing within the WhereOrInfo
  98492. ** object that is attached to the original OR clause term.
  98493. */
  98494. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  98495. assert( pExpr->op==TK_OR );
  98496. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  98497. if( pOrInfo==0 ) return;
  98498. pTerm->wtFlags |= TERM_ORINFO;
  98499. pOrWc = &pOrInfo->wc;
  98500. whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
  98501. whereSplit(pOrWc, pExpr, TK_OR);
  98502. exprAnalyzeAll(pSrc, pOrWc);
  98503. if( db->mallocFailed ) return;
  98504. assert( pOrWc->nTerm>=2 );
  98505. /*
  98506. ** Compute the set of tables that might satisfy cases 1 or 2.
  98507. */
  98508. indexable = ~(Bitmask)0;
  98509. chngToIN = ~(Bitmask)0;
  98510. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  98511. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  98512. WhereAndInfo *pAndInfo;
  98513. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  98514. chngToIN = 0;
  98515. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  98516. if( pAndInfo ){
  98517. WhereClause *pAndWC;
  98518. WhereTerm *pAndTerm;
  98519. int j;
  98520. Bitmask b = 0;
  98521. pOrTerm->u.pAndInfo = pAndInfo;
  98522. pOrTerm->wtFlags |= TERM_ANDINFO;
  98523. pOrTerm->eOperator = WO_AND;
  98524. pAndWC = &pAndInfo->wc;
  98525. whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
  98526. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  98527. exprAnalyzeAll(pSrc, pAndWC);
  98528. pAndWC->pOuter = pWC;
  98529. testcase( db->mallocFailed );
  98530. if( !db->mallocFailed ){
  98531. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  98532. assert( pAndTerm->pExpr );
  98533. if( allowedOp(pAndTerm->pExpr->op) ){
  98534. b |= getMask(pMaskSet, pAndTerm->leftCursor);
  98535. }
  98536. }
  98537. }
  98538. indexable &= b;
  98539. }
  98540. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  98541. /* Skip this term for now. We revisit it when we process the
  98542. ** corresponding TERM_VIRTUAL term */
  98543. }else{
  98544. Bitmask b;
  98545. b = getMask(pMaskSet, pOrTerm->leftCursor);
  98546. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  98547. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  98548. b |= getMask(pMaskSet, pOther->leftCursor);
  98549. }
  98550. indexable &= b;
  98551. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  98552. chngToIN = 0;
  98553. }else{
  98554. chngToIN &= b;
  98555. }
  98556. }
  98557. }
  98558. /*
  98559. ** Record the set of tables that satisfy case 2. The set might be
  98560. ** empty.
  98561. */
  98562. pOrInfo->indexable = indexable;
  98563. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  98564. /*
  98565. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  98566. ** we have to do some additional checking to see if case 1 really
  98567. ** is satisfied.
  98568. **
  98569. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  98570. ** that there is no possibility of transforming the OR clause into an
  98571. ** IN operator because one or more terms in the OR clause contain
  98572. ** something other than == on a column in the single table. The 1-bit
  98573. ** case means that every term of the OR clause is of the form
  98574. ** "table.column=expr" for some single table. The one bit that is set
  98575. ** will correspond to the common table. We still need to check to make
  98576. ** sure the same column is used on all terms. The 2-bit case is when
  98577. ** the all terms are of the form "table1.column=table2.column". It
  98578. ** might be possible to form an IN operator with either table1.column
  98579. ** or table2.column as the LHS if either is common to every term of
  98580. ** the OR clause.
  98581. **
  98582. ** Note that terms of the form "table.column1=table.column2" (the
  98583. ** same table on both sizes of the ==) cannot be optimized.
  98584. */
  98585. if( chngToIN ){
  98586. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  98587. int iColumn = -1; /* Column index on lhs of IN operator */
  98588. int iCursor = -1; /* Table cursor common to all terms */
  98589. int j = 0; /* Loop counter */
  98590. /* Search for a table and column that appears on one side or the
  98591. ** other of the == operator in every subterm. That table and column
  98592. ** will be recorded in iCursor and iColumn. There might not be any
  98593. ** such table and column. Set okToChngToIN if an appropriate table
  98594. ** and column is found but leave okToChngToIN false if not found.
  98595. */
  98596. for(j=0; j<2 && !okToChngToIN; j++){
  98597. pOrTerm = pOrWc->a;
  98598. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  98599. assert( pOrTerm->eOperator & WO_EQ );
  98600. pOrTerm->wtFlags &= ~TERM_OR_OK;
  98601. if( pOrTerm->leftCursor==iCursor ){
  98602. /* This is the 2-bit case and we are on the second iteration and
  98603. ** current term is from the first iteration. So skip this term. */
  98604. assert( j==1 );
  98605. continue;
  98606. }
  98607. if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
  98608. /* This term must be of the form t1.a==t2.b where t2 is in the
  98609. ** chngToIN set but t1 is not. This term will be either preceeded
  98610. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  98611. ** and use its inversion. */
  98612. testcase( pOrTerm->wtFlags & TERM_COPIED );
  98613. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  98614. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  98615. continue;
  98616. }
  98617. iColumn = pOrTerm->u.leftColumn;
  98618. iCursor = pOrTerm->leftCursor;
  98619. break;
  98620. }
  98621. if( i<0 ){
  98622. /* No candidate table+column was found. This can only occur
  98623. ** on the second iteration */
  98624. assert( j==1 );
  98625. assert( IsPowerOfTwo(chngToIN) );
  98626. assert( chngToIN==getMask(pMaskSet, iCursor) );
  98627. break;
  98628. }
  98629. testcase( j==1 );
  98630. /* We have found a candidate table and column. Check to see if that
  98631. ** table and column is common to every term in the OR clause */
  98632. okToChngToIN = 1;
  98633. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  98634. assert( pOrTerm->eOperator & WO_EQ );
  98635. if( pOrTerm->leftCursor!=iCursor ){
  98636. pOrTerm->wtFlags &= ~TERM_OR_OK;
  98637. }else if( pOrTerm->u.leftColumn!=iColumn ){
  98638. okToChngToIN = 0;
  98639. }else{
  98640. int affLeft, affRight;
  98641. /* If the right-hand side is also a column, then the affinities
  98642. ** of both right and left sides must be such that no type
  98643. ** conversions are required on the right. (Ticket #2249)
  98644. */
  98645. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  98646. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  98647. if( affRight!=0 && affRight!=affLeft ){
  98648. okToChngToIN = 0;
  98649. }else{
  98650. pOrTerm->wtFlags |= TERM_OR_OK;
  98651. }
  98652. }
  98653. }
  98654. }
  98655. /* At this point, okToChngToIN is true if original pTerm satisfies
  98656. ** case 1. In that case, construct a new virtual term that is
  98657. ** pTerm converted into an IN operator.
  98658. **
  98659. ** EV: R-00211-15100
  98660. */
  98661. if( okToChngToIN ){
  98662. Expr *pDup; /* A transient duplicate expression */
  98663. ExprList *pList = 0; /* The RHS of the IN operator */
  98664. Expr *pLeft = 0; /* The LHS of the IN operator */
  98665. Expr *pNew; /* The complete IN operator */
  98666. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  98667. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  98668. assert( pOrTerm->eOperator & WO_EQ );
  98669. assert( pOrTerm->leftCursor==iCursor );
  98670. assert( pOrTerm->u.leftColumn==iColumn );
  98671. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  98672. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
  98673. pLeft = pOrTerm->pExpr->pLeft;
  98674. }
  98675. assert( pLeft!=0 );
  98676. pDup = sqlite3ExprDup(db, pLeft, 0);
  98677. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  98678. if( pNew ){
  98679. int idxNew;
  98680. transferJoinMarkings(pNew, pExpr);
  98681. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  98682. pNew->x.pList = pList;
  98683. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  98684. testcase( idxNew==0 );
  98685. exprAnalyze(pSrc, pWC, idxNew);
  98686. pTerm = &pWC->a[idxTerm];
  98687. pWC->a[idxNew].iParent = idxTerm;
  98688. pTerm->nChild = 1;
  98689. }else{
  98690. sqlite3ExprListDelete(db, pList);
  98691. }
  98692. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  98693. }
  98694. }
  98695. }
  98696. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  98697. /*
  98698. ** The input to this routine is an WhereTerm structure with only the
  98699. ** "pExpr" field filled in. The job of this routine is to analyze the
  98700. ** subexpression and populate all the other fields of the WhereTerm
  98701. ** structure.
  98702. **
  98703. ** If the expression is of the form "<expr> <op> X" it gets commuted
  98704. ** to the standard form of "X <op> <expr>".
  98705. **
  98706. ** If the expression is of the form "X <op> Y" where both X and Y are
  98707. ** columns, then the original expression is unchanged and a new virtual
  98708. ** term of the form "Y <op> X" is added to the WHERE clause and
  98709. ** analyzed separately. The original term is marked with TERM_COPIED
  98710. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  98711. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  98712. ** is a commuted copy of a prior term.) The original term has nChild=1
  98713. ** and the copy has idxParent set to the index of the original term.
  98714. */
  98715. static void exprAnalyze(
  98716. SrcList *pSrc, /* the FROM clause */
  98717. WhereClause *pWC, /* the WHERE clause */
  98718. int idxTerm /* Index of the term to be analyzed */
  98719. ){
  98720. WhereTerm *pTerm; /* The term to be analyzed */
  98721. WhereMaskSet *pMaskSet; /* Set of table index masks */
  98722. Expr *pExpr; /* The expression to be analyzed */
  98723. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  98724. Bitmask prereqAll; /* Prerequesites of pExpr */
  98725. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  98726. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  98727. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  98728. int noCase = 0; /* LIKE/GLOB distinguishes case */
  98729. int op; /* Top-level operator. pExpr->op */
  98730. Parse *pParse = pWC->pParse; /* Parsing context */
  98731. sqlite3 *db = pParse->db; /* Database connection */
  98732. if( db->mallocFailed ){
  98733. return;
  98734. }
  98735. pTerm = &pWC->a[idxTerm];
  98736. pMaskSet = pWC->pMaskSet;
  98737. pExpr = pTerm->pExpr;
  98738. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  98739. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  98740. op = pExpr->op;
  98741. if( op==TK_IN ){
  98742. assert( pExpr->pRight==0 );
  98743. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  98744. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  98745. }else{
  98746. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  98747. }
  98748. }else if( op==TK_ISNULL ){
  98749. pTerm->prereqRight = 0;
  98750. }else{
  98751. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  98752. }
  98753. prereqAll = exprTableUsage(pMaskSet, pExpr);
  98754. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  98755. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  98756. prereqAll |= x;
  98757. extraRight = x-1; /* ON clause terms may not be used with an index
  98758. ** on left table of a LEFT JOIN. Ticket #3015 */
  98759. }
  98760. pTerm->prereqAll = prereqAll;
  98761. pTerm->leftCursor = -1;
  98762. pTerm->iParent = -1;
  98763. pTerm->eOperator = 0;
  98764. if( allowedOp(op) ){
  98765. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  98766. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  98767. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  98768. if( pLeft->op==TK_COLUMN ){
  98769. pTerm->leftCursor = pLeft->iTable;
  98770. pTerm->u.leftColumn = pLeft->iColumn;
  98771. pTerm->eOperator = operatorMask(op) & opMask;
  98772. }
  98773. if( pRight && pRight->op==TK_COLUMN ){
  98774. WhereTerm *pNew;
  98775. Expr *pDup;
  98776. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  98777. if( pTerm->leftCursor>=0 ){
  98778. int idxNew;
  98779. pDup = sqlite3ExprDup(db, pExpr, 0);
  98780. if( db->mallocFailed ){
  98781. sqlite3ExprDelete(db, pDup);
  98782. return;
  98783. }
  98784. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  98785. if( idxNew==0 ) return;
  98786. pNew = &pWC->a[idxNew];
  98787. pNew->iParent = idxTerm;
  98788. pTerm = &pWC->a[idxTerm];
  98789. pTerm->nChild = 1;
  98790. pTerm->wtFlags |= TERM_COPIED;
  98791. if( pExpr->op==TK_EQ
  98792. && !ExprHasProperty(pExpr, EP_FromJoin)
  98793. && OptimizationEnabled(db, SQLITE_Transitive)
  98794. ){
  98795. pTerm->eOperator |= WO_EQUIV;
  98796. eExtraOp = WO_EQUIV;
  98797. }
  98798. }else{
  98799. pDup = pExpr;
  98800. pNew = pTerm;
  98801. }
  98802. exprCommute(pParse, pDup);
  98803. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  98804. pNew->leftCursor = pLeft->iTable;
  98805. pNew->u.leftColumn = pLeft->iColumn;
  98806. testcase( (prereqLeft | extraRight) != prereqLeft );
  98807. pNew->prereqRight = prereqLeft | extraRight;
  98808. pNew->prereqAll = prereqAll;
  98809. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  98810. }
  98811. }
  98812. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  98813. /* If a term is the BETWEEN operator, create two new virtual terms
  98814. ** that define the range that the BETWEEN implements. For example:
  98815. **
  98816. ** a BETWEEN b AND c
  98817. **
  98818. ** is converted into:
  98819. **
  98820. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  98821. **
  98822. ** The two new terms are added onto the end of the WhereClause object.
  98823. ** The new terms are "dynamic" and are children of the original BETWEEN
  98824. ** term. That means that if the BETWEEN term is coded, the children are
  98825. ** skipped. Or, if the children are satisfied by an index, the original
  98826. ** BETWEEN term is skipped.
  98827. */
  98828. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  98829. ExprList *pList = pExpr->x.pList;
  98830. int i;
  98831. static const u8 ops[] = {TK_GE, TK_LE};
  98832. assert( pList!=0 );
  98833. assert( pList->nExpr==2 );
  98834. for(i=0; i<2; i++){
  98835. Expr *pNewExpr;
  98836. int idxNew;
  98837. pNewExpr = sqlite3PExpr(pParse, ops[i],
  98838. sqlite3ExprDup(db, pExpr->pLeft, 0),
  98839. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  98840. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  98841. testcase( idxNew==0 );
  98842. exprAnalyze(pSrc, pWC, idxNew);
  98843. pTerm = &pWC->a[idxTerm];
  98844. pWC->a[idxNew].iParent = idxTerm;
  98845. }
  98846. pTerm->nChild = 2;
  98847. }
  98848. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  98849. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  98850. /* Analyze a term that is composed of two or more subterms connected by
  98851. ** an OR operator.
  98852. */
  98853. else if( pExpr->op==TK_OR ){
  98854. assert( pWC->op==TK_AND );
  98855. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  98856. pTerm = &pWC->a[idxTerm];
  98857. }
  98858. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  98859. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  98860. /* Add constraints to reduce the search space on a LIKE or GLOB
  98861. ** operator.
  98862. **
  98863. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  98864. **
  98865. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  98866. **
  98867. ** The last character of the prefix "abc" is incremented to form the
  98868. ** termination condition "abd".
  98869. */
  98870. if( pWC->op==TK_AND
  98871. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  98872. ){
  98873. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  98874. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  98875. Expr *pNewExpr1;
  98876. Expr *pNewExpr2;
  98877. int idxNew1;
  98878. int idxNew2;
  98879. Token sCollSeqName; /* Name of collating sequence */
  98880. pLeft = pExpr->x.pList->a[1].pExpr;
  98881. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  98882. if( !db->mallocFailed ){
  98883. u8 c, *pC; /* Last character before the first wildcard */
  98884. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  98885. c = *pC;
  98886. if( noCase ){
  98887. /* The point is to increment the last character before the first
  98888. ** wildcard. But if we increment '@', that will push it into the
  98889. ** alphabetic range where case conversions will mess up the
  98890. ** inequality. To avoid this, make sure to also run the full
  98891. ** LIKE on all candidate expressions by clearing the isComplete flag
  98892. */
  98893. if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
  98894. c = sqlite3UpperToLower[c];
  98895. }
  98896. *pC = c + 1;
  98897. }
  98898. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  98899. sCollSeqName.n = 6;
  98900. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  98901. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  98902. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  98903. pStr1, 0);
  98904. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  98905. testcase( idxNew1==0 );
  98906. exprAnalyze(pSrc, pWC, idxNew1);
  98907. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  98908. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  98909. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  98910. pStr2, 0);
  98911. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  98912. testcase( idxNew2==0 );
  98913. exprAnalyze(pSrc, pWC, idxNew2);
  98914. pTerm = &pWC->a[idxTerm];
  98915. if( isComplete ){
  98916. pWC->a[idxNew1].iParent = idxTerm;
  98917. pWC->a[idxNew2].iParent = idxTerm;
  98918. pTerm->nChild = 2;
  98919. }
  98920. }
  98921. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  98922. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98923. /* Add a WO_MATCH auxiliary term to the constraint set if the
  98924. ** current expression is of the form: column MATCH expr.
  98925. ** This information is used by the xBestIndex methods of
  98926. ** virtual tables. The native query optimizer does not attempt
  98927. ** to do anything with MATCH functions.
  98928. */
  98929. if( isMatchOfColumn(pExpr) ){
  98930. int idxNew;
  98931. Expr *pRight, *pLeft;
  98932. WhereTerm *pNewTerm;
  98933. Bitmask prereqColumn, prereqExpr;
  98934. pRight = pExpr->x.pList->a[0].pExpr;
  98935. pLeft = pExpr->x.pList->a[1].pExpr;
  98936. prereqExpr = exprTableUsage(pMaskSet, pRight);
  98937. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  98938. if( (prereqExpr & prereqColumn)==0 ){
  98939. Expr *pNewExpr;
  98940. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  98941. 0, sqlite3ExprDup(db, pRight, 0), 0);
  98942. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  98943. testcase( idxNew==0 );
  98944. pNewTerm = &pWC->a[idxNew];
  98945. pNewTerm->prereqRight = prereqExpr;
  98946. pNewTerm->leftCursor = pLeft->iTable;
  98947. pNewTerm->u.leftColumn = pLeft->iColumn;
  98948. pNewTerm->eOperator = WO_MATCH;
  98949. pNewTerm->iParent = idxTerm;
  98950. pTerm = &pWC->a[idxTerm];
  98951. pTerm->nChild = 1;
  98952. pTerm->wtFlags |= TERM_COPIED;
  98953. pNewTerm->prereqAll = pTerm->prereqAll;
  98954. }
  98955. }
  98956. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  98957. #ifdef SQLITE_ENABLE_STAT3
  98958. /* When sqlite_stat3 histogram data is available an operator of the
  98959. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  98960. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  98961. ** virtual term of that form.
  98962. **
  98963. ** Note that the virtual term must be tagged with TERM_VNULL. This
  98964. ** TERM_VNULL tag will suppress the not-null check at the beginning
  98965. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  98966. ** the start of the loop will prevent any results from being returned.
  98967. */
  98968. if( pExpr->op==TK_NOTNULL
  98969. && pExpr->pLeft->op==TK_COLUMN
  98970. && pExpr->pLeft->iColumn>=0
  98971. ){
  98972. Expr *pNewExpr;
  98973. Expr *pLeft = pExpr->pLeft;
  98974. int idxNew;
  98975. WhereTerm *pNewTerm;
  98976. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  98977. sqlite3ExprDup(db, pLeft, 0),
  98978. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  98979. idxNew = whereClauseInsert(pWC, pNewExpr,
  98980. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  98981. if( idxNew ){
  98982. pNewTerm = &pWC->a[idxNew];
  98983. pNewTerm->prereqRight = 0;
  98984. pNewTerm->leftCursor = pLeft->iTable;
  98985. pNewTerm->u.leftColumn = pLeft->iColumn;
  98986. pNewTerm->eOperator = WO_GT;
  98987. pNewTerm->iParent = idxTerm;
  98988. pTerm = &pWC->a[idxTerm];
  98989. pTerm->nChild = 1;
  98990. pTerm->wtFlags |= TERM_COPIED;
  98991. pNewTerm->prereqAll = pTerm->prereqAll;
  98992. }
  98993. }
  98994. #endif /* SQLITE_ENABLE_STAT */
  98995. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  98996. ** an index for tables to the left of the join.
  98997. */
  98998. pTerm->prereqRight |= extraRight;
  98999. }
  99000. /*
  99001. ** This function searches the expression list passed as the second argument
  99002. ** for an expression of type TK_COLUMN that refers to the same column and
  99003. ** uses the same collation sequence as the iCol'th column of index pIdx.
  99004. ** Argument iBase is the cursor number used for the table that pIdx refers
  99005. ** to.
  99006. **
  99007. ** If such an expression is found, its index in pList->a[] is returned. If
  99008. ** no expression is found, -1 is returned.
  99009. */
  99010. static int findIndexCol(
  99011. Parse *pParse, /* Parse context */
  99012. ExprList *pList, /* Expression list to search */
  99013. int iBase, /* Cursor for table associated with pIdx */
  99014. Index *pIdx, /* Index to match column of */
  99015. int iCol /* Column of index to match */
  99016. ){
  99017. int i;
  99018. const char *zColl = pIdx->azColl[iCol];
  99019. for(i=0; i<pList->nExpr; i++){
  99020. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  99021. if( p->op==TK_COLUMN
  99022. && p->iColumn==pIdx->aiColumn[iCol]
  99023. && p->iTable==iBase
  99024. ){
  99025. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  99026. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  99027. return i;
  99028. }
  99029. }
  99030. }
  99031. return -1;
  99032. }
  99033. /*
  99034. ** This routine determines if pIdx can be used to assist in processing a
  99035. ** DISTINCT qualifier. In other words, it tests whether or not using this
  99036. ** index for the outer loop guarantees that rows with equal values for
  99037. ** all expressions in the pDistinct list are delivered grouped together.
  99038. **
  99039. ** For example, the query
  99040. **
  99041. ** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
  99042. **
  99043. ** can benefit from any index on columns "b" and "c".
  99044. */
  99045. static int isDistinctIndex(
  99046. Parse *pParse, /* Parsing context */
  99047. WhereClause *pWC, /* The WHERE clause */
  99048. Index *pIdx, /* The index being considered */
  99049. int base, /* Cursor number for the table pIdx is on */
  99050. ExprList *pDistinct, /* The DISTINCT expressions */
  99051. int nEqCol /* Number of index columns with == */
  99052. ){
  99053. Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
  99054. int i; /* Iterator variable */
  99055. assert( pDistinct!=0 );
  99056. if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
  99057. testcase( pDistinct->nExpr==BMS-1 );
  99058. /* Loop through all the expressions in the distinct list. If any of them
  99059. ** are not simple column references, return early. Otherwise, test if the
  99060. ** WHERE clause contains a "col=X" clause. If it does, the expression
  99061. ** can be ignored. If it does not, and the column does not belong to the
  99062. ** same table as index pIdx, return early. Finally, if there is no
  99063. ** matching "col=X" expression and the column is on the same table as pIdx,
  99064. ** set the corresponding bit in variable mask.
  99065. */
  99066. for(i=0; i<pDistinct->nExpr; i++){
  99067. WhereTerm *pTerm;
  99068. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  99069. if( p->op!=TK_COLUMN ) return 0;
  99070. pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
  99071. if( pTerm ){
  99072. Expr *pX = pTerm->pExpr;
  99073. CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  99074. CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
  99075. if( p1==p2 ) continue;
  99076. }
  99077. if( p->iTable!=base ) return 0;
  99078. mask |= (((Bitmask)1) << i);
  99079. }
  99080. for(i=nEqCol; mask && i<pIdx->nColumn; i++){
  99081. int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
  99082. if( iExpr<0 ) break;
  99083. mask &= ~(((Bitmask)1) << iExpr);
  99084. }
  99085. return (mask==0);
  99086. }
  99087. /*
  99088. ** Return true if the DISTINCT expression-list passed as the third argument
  99089. ** is redundant. A DISTINCT list is redundant if the database contains a
  99090. ** UNIQUE index that guarantees that the result of the query will be distinct
  99091. ** anyway.
  99092. */
  99093. static int isDistinctRedundant(
  99094. Parse *pParse,
  99095. SrcList *pTabList,
  99096. WhereClause *pWC,
  99097. ExprList *pDistinct
  99098. ){
  99099. Table *pTab;
  99100. Index *pIdx;
  99101. int i;
  99102. int iBase;
  99103. /* If there is more than one table or sub-select in the FROM clause of
  99104. ** this query, then it will not be possible to show that the DISTINCT
  99105. ** clause is redundant. */
  99106. if( pTabList->nSrc!=1 ) return 0;
  99107. iBase = pTabList->a[0].iCursor;
  99108. pTab = pTabList->a[0].pTab;
  99109. /* If any of the expressions is an IPK column on table iBase, then return
  99110. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  99111. ** current SELECT is a correlated sub-query.
  99112. */
  99113. for(i=0; i<pDistinct->nExpr; i++){
  99114. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  99115. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  99116. }
  99117. /* Loop through all indices on the table, checking each to see if it makes
  99118. ** the DISTINCT qualifier redundant. It does so if:
  99119. **
  99120. ** 1. The index is itself UNIQUE, and
  99121. **
  99122. ** 2. All of the columns in the index are either part of the pDistinct
  99123. ** list, or else the WHERE clause contains a term of the form "col=X",
  99124. ** where X is a constant value. The collation sequences of the
  99125. ** comparison and select-list expressions must match those of the index.
  99126. **
  99127. ** 3. All of those index columns for which the WHERE clause does not
  99128. ** contain a "col=X" term are subject to a NOT NULL constraint.
  99129. */
  99130. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99131. if( pIdx->onError==OE_None ) continue;
  99132. for(i=0; i<pIdx->nColumn; i++){
  99133. int iCol = pIdx->aiColumn[i];
  99134. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  99135. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  99136. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  99137. break;
  99138. }
  99139. }
  99140. }
  99141. if( i==pIdx->nColumn ){
  99142. /* This index implies that the DISTINCT qualifier is redundant. */
  99143. return 1;
  99144. }
  99145. }
  99146. return 0;
  99147. }
  99148. /*
  99149. ** Prepare a crude estimate of the logarithm of the input value.
  99150. ** The results need not be exact. This is only used for estimating
  99151. ** the total cost of performing operations with O(logN) or O(NlogN)
  99152. ** complexity. Because N is just a guess, it is no great tragedy if
  99153. ** logN is a little off.
  99154. */
  99155. static double estLog(double N){
  99156. double logN = 1;
  99157. double x = 10;
  99158. while( N>x ){
  99159. logN += 1;
  99160. x *= 10;
  99161. }
  99162. return logN;
  99163. }
  99164. /*
  99165. ** Two routines for printing the content of an sqlite3_index_info
  99166. ** structure. Used for testing and debugging only. If neither
  99167. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  99168. ** are no-ops.
  99169. */
  99170. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  99171. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  99172. int i;
  99173. if( !sqlite3WhereTrace ) return;
  99174. for(i=0; i<p->nConstraint; i++){
  99175. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  99176. i,
  99177. p->aConstraint[i].iColumn,
  99178. p->aConstraint[i].iTermOffset,
  99179. p->aConstraint[i].op,
  99180. p->aConstraint[i].usable);
  99181. }
  99182. for(i=0; i<p->nOrderBy; i++){
  99183. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  99184. i,
  99185. p->aOrderBy[i].iColumn,
  99186. p->aOrderBy[i].desc);
  99187. }
  99188. }
  99189. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  99190. int i;
  99191. if( !sqlite3WhereTrace ) return;
  99192. for(i=0; i<p->nConstraint; i++){
  99193. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  99194. i,
  99195. p->aConstraintUsage[i].argvIndex,
  99196. p->aConstraintUsage[i].omit);
  99197. }
  99198. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  99199. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  99200. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  99201. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  99202. }
  99203. #else
  99204. #define TRACE_IDX_INPUTS(A)
  99205. #define TRACE_IDX_OUTPUTS(A)
  99206. #endif
  99207. /*
  99208. ** Required because bestIndex() is called by bestOrClauseIndex()
  99209. */
  99210. static void bestIndex(WhereBestIdx*);
  99211. /*
  99212. ** This routine attempts to find an scanning strategy that can be used
  99213. ** to optimize an 'OR' expression that is part of a WHERE clause.
  99214. **
  99215. ** The table associated with FROM clause term pSrc may be either a
  99216. ** regular B-Tree table or a virtual table.
  99217. */
  99218. static void bestOrClauseIndex(WhereBestIdx *p){
  99219. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  99220. WhereClause *pWC = p->pWC; /* The WHERE clause */
  99221. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  99222. const int iCur = pSrc->iCursor; /* The cursor of the table */
  99223. const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
  99224. WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
  99225. WhereTerm *pTerm; /* A single term of the WHERE clause */
  99226. /* The OR-clause optimization is disallowed if the INDEXED BY or
  99227. ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
  99228. if( pSrc->notIndexed || pSrc->pIndex!=0 ){
  99229. return;
  99230. }
  99231. if( pWC->wctrlFlags & WHERE_AND_ONLY ){
  99232. return;
  99233. }
  99234. /* Search the WHERE clause terms for a usable WO_OR term. */
  99235. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  99236. if( (pTerm->eOperator & WO_OR)!=0
  99237. && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
  99238. && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
  99239. ){
  99240. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  99241. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  99242. WhereTerm *pOrTerm;
  99243. int flags = WHERE_MULTI_OR;
  99244. double rTotal = 0;
  99245. double nRow = 0;
  99246. Bitmask used = 0;
  99247. WhereBestIdx sBOI;
  99248. sBOI = *p;
  99249. sBOI.pOrderBy = 0;
  99250. sBOI.pDistinct = 0;
  99251. sBOI.ppIdxInfo = 0;
  99252. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  99253. WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
  99254. (pOrTerm - pOrWC->a), (pTerm - pWC->a)
  99255. ));
  99256. if( (pOrTerm->eOperator& WO_AND)!=0 ){
  99257. sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
  99258. bestIndex(&sBOI);
  99259. }else if( pOrTerm->leftCursor==iCur ){
  99260. WhereClause tempWC;
  99261. tempWC.pParse = pWC->pParse;
  99262. tempWC.pMaskSet = pWC->pMaskSet;
  99263. tempWC.pOuter = pWC;
  99264. tempWC.op = TK_AND;
  99265. tempWC.a = pOrTerm;
  99266. tempWC.wctrlFlags = 0;
  99267. tempWC.nTerm = 1;
  99268. sBOI.pWC = &tempWC;
  99269. bestIndex(&sBOI);
  99270. }else{
  99271. continue;
  99272. }
  99273. rTotal += sBOI.cost.rCost;
  99274. nRow += sBOI.cost.plan.nRow;
  99275. used |= sBOI.cost.used;
  99276. if( rTotal>=p->cost.rCost ) break;
  99277. }
  99278. /* If there is an ORDER BY clause, increase the scan cost to account
  99279. ** for the cost of the sort. */
  99280. if( p->pOrderBy!=0 ){
  99281. WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
  99282. rTotal, rTotal+nRow*estLog(nRow)));
  99283. rTotal += nRow*estLog(nRow);
  99284. }
  99285. /* If the cost of scanning using this OR term for optimization is
  99286. ** less than the current cost stored in pCost, replace the contents
  99287. ** of pCost. */
  99288. WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
  99289. if( rTotal<p->cost.rCost ){
  99290. p->cost.rCost = rTotal;
  99291. p->cost.used = used;
  99292. p->cost.plan.nRow = nRow;
  99293. p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
  99294. p->cost.plan.wsFlags = flags;
  99295. p->cost.plan.u.pTerm = pTerm;
  99296. }
  99297. }
  99298. }
  99299. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  99300. }
  99301. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  99302. /*
  99303. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  99304. ** could be used with an index to access pSrc, assuming an appropriate
  99305. ** index existed.
  99306. */
  99307. static int termCanDriveIndex(
  99308. WhereTerm *pTerm, /* WHERE clause term to check */
  99309. struct SrcList_item *pSrc, /* Table we are trying to access */
  99310. Bitmask notReady /* Tables in outer loops of the join */
  99311. ){
  99312. char aff;
  99313. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  99314. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  99315. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  99316. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  99317. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  99318. return 1;
  99319. }
  99320. #endif
  99321. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  99322. /*
  99323. ** If the query plan for pSrc specified in pCost is a full table scan
  99324. ** and indexing is allows (if there is no NOT INDEXED clause) and it
  99325. ** possible to construct a transient index that would perform better
  99326. ** than a full table scan even when the cost of constructing the index
  99327. ** is taken into account, then alter the query plan to use the
  99328. ** transient index.
  99329. */
  99330. static void bestAutomaticIndex(WhereBestIdx *p){
  99331. Parse *pParse = p->pParse; /* The parsing context */
  99332. WhereClause *pWC = p->pWC; /* The WHERE clause */
  99333. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  99334. double nTableRow; /* Rows in the input table */
  99335. double logN; /* log(nTableRow) */
  99336. double costTempIdx; /* per-query cost of the transient index */
  99337. WhereTerm *pTerm; /* A single term of the WHERE clause */
  99338. WhereTerm *pWCEnd; /* End of pWC->a[] */
  99339. Table *pTable; /* Table tht might be indexed */
  99340. if( pParse->nQueryLoop<=(double)1 ){
  99341. /* There is no point in building an automatic index for a single scan */
  99342. return;
  99343. }
  99344. if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
  99345. /* Automatic indices are disabled at run-time */
  99346. return;
  99347. }
  99348. if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
  99349. && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
  99350. ){
  99351. /* We already have some kind of index in use for this query. */
  99352. return;
  99353. }
  99354. if( pSrc->viaCoroutine ){
  99355. /* Cannot index a co-routine */
  99356. return;
  99357. }
  99358. if( pSrc->notIndexed ){
  99359. /* The NOT INDEXED clause appears in the SQL. */
  99360. return;
  99361. }
  99362. if( pSrc->isCorrelated ){
  99363. /* The source is a correlated sub-query. No point in indexing it. */
  99364. return;
  99365. }
  99366. assert( pParse->nQueryLoop >= (double)1 );
  99367. pTable = pSrc->pTab;
  99368. nTableRow = pTable->nRowEst;
  99369. logN = estLog(nTableRow);
  99370. costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
  99371. if( costTempIdx>=p->cost.rCost ){
  99372. /* The cost of creating the transient table would be greater than
  99373. ** doing the full table scan */
  99374. return;
  99375. }
  99376. /* Search for any equality comparison term */
  99377. pWCEnd = &pWC->a[pWC->nTerm];
  99378. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  99379. if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
  99380. WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
  99381. p->cost.rCost, costTempIdx));
  99382. p->cost.rCost = costTempIdx;
  99383. p->cost.plan.nRow = logN + 1;
  99384. p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
  99385. p->cost.used = pTerm->prereqRight;
  99386. break;
  99387. }
  99388. }
  99389. }
  99390. #else
  99391. # define bestAutomaticIndex(A) /* no-op */
  99392. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  99393. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  99394. /*
  99395. ** Generate code to construct the Index object for an automatic index
  99396. ** and to set up the WhereLevel object pLevel so that the code generator
  99397. ** makes use of the automatic index.
  99398. */
  99399. static void constructAutomaticIndex(
  99400. Parse *pParse, /* The parsing context */
  99401. WhereClause *pWC, /* The WHERE clause */
  99402. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  99403. Bitmask notReady, /* Mask of cursors that are not available */
  99404. WhereLevel *pLevel /* Write new index here */
  99405. ){
  99406. int nColumn; /* Number of columns in the constructed index */
  99407. WhereTerm *pTerm; /* A single term of the WHERE clause */
  99408. WhereTerm *pWCEnd; /* End of pWC->a[] */
  99409. int nByte; /* Byte of memory needed for pIdx */
  99410. Index *pIdx; /* Object describing the transient index */
  99411. Vdbe *v; /* Prepared statement under construction */
  99412. int addrInit; /* Address of the initialization bypass jump */
  99413. Table *pTable; /* The table being indexed */
  99414. KeyInfo *pKeyinfo; /* Key information for the index */
  99415. int addrTop; /* Top of the index fill loop */
  99416. int regRecord; /* Register holding an index record */
  99417. int n; /* Column counter */
  99418. int i; /* Loop counter */
  99419. int mxBitCol; /* Maximum column in pSrc->colUsed */
  99420. CollSeq *pColl; /* Collating sequence to on a column */
  99421. Bitmask idxCols; /* Bitmap of columns used for indexing */
  99422. Bitmask extraCols; /* Bitmap of additional columns */
  99423. /* Generate code to skip over the creation and initialization of the
  99424. ** transient index on 2nd and subsequent iterations of the loop. */
  99425. v = pParse->pVdbe;
  99426. assert( v!=0 );
  99427. addrInit = sqlite3CodeOnce(pParse);
  99428. /* Count the number of columns that will be added to the index
  99429. ** and used to match WHERE clause constraints */
  99430. nColumn = 0;
  99431. pTable = pSrc->pTab;
  99432. pWCEnd = &pWC->a[pWC->nTerm];
  99433. idxCols = 0;
  99434. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  99435. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  99436. int iCol = pTerm->u.leftColumn;
  99437. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  99438. testcase( iCol==BMS );
  99439. testcase( iCol==BMS-1 );
  99440. if( (idxCols & cMask)==0 ){
  99441. nColumn++;
  99442. idxCols |= cMask;
  99443. }
  99444. }
  99445. }
  99446. assert( nColumn>0 );
  99447. pLevel->plan.nEq = nColumn;
  99448. /* Count the number of additional columns needed to create a
  99449. ** covering index. A "covering index" is an index that contains all
  99450. ** columns that are needed by the query. With a covering index, the
  99451. ** original table never needs to be accessed. Automatic indices must
  99452. ** be a covering index because the index will not be updated if the
  99453. ** original table changes and the index and table cannot both be used
  99454. ** if they go out of sync.
  99455. */
  99456. extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
  99457. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  99458. testcase( pTable->nCol==BMS-1 );
  99459. testcase( pTable->nCol==BMS-2 );
  99460. for(i=0; i<mxBitCol; i++){
  99461. if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
  99462. }
  99463. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  99464. nColumn += pTable->nCol - BMS + 1;
  99465. }
  99466. pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
  99467. /* Construct the Index object to describe this index */
  99468. nByte = sizeof(Index);
  99469. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  99470. nByte += nColumn*sizeof(char*); /* Index.azColl */
  99471. nByte += nColumn; /* Index.aSortOrder */
  99472. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  99473. if( pIdx==0 ) return;
  99474. pLevel->plan.u.pIdx = pIdx;
  99475. pIdx->azColl = (char**)&pIdx[1];
  99476. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  99477. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  99478. pIdx->zName = "auto-index";
  99479. pIdx->nColumn = nColumn;
  99480. pIdx->pTable = pTable;
  99481. n = 0;
  99482. idxCols = 0;
  99483. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  99484. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  99485. int iCol = pTerm->u.leftColumn;
  99486. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  99487. if( (idxCols & cMask)==0 ){
  99488. Expr *pX = pTerm->pExpr;
  99489. idxCols |= cMask;
  99490. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  99491. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  99492. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  99493. n++;
  99494. }
  99495. }
  99496. }
  99497. assert( (u32)n==pLevel->plan.nEq );
  99498. /* Add additional columns needed to make the automatic index into
  99499. ** a covering index */
  99500. for(i=0; i<mxBitCol; i++){
  99501. if( extraCols & (((Bitmask)1)<<i) ){
  99502. pIdx->aiColumn[n] = i;
  99503. pIdx->azColl[n] = "BINARY";
  99504. n++;
  99505. }
  99506. }
  99507. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  99508. for(i=BMS-1; i<pTable->nCol; i++){
  99509. pIdx->aiColumn[n] = i;
  99510. pIdx->azColl[n] = "BINARY";
  99511. n++;
  99512. }
  99513. }
  99514. assert( n==nColumn );
  99515. /* Create the automatic index */
  99516. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  99517. assert( pLevel->iIdxCur>=0 );
  99518. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  99519. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  99520. VdbeComment((v, "for %s", pTable->zName));
  99521. /* Fill the automatic index with content */
  99522. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  99523. regRecord = sqlite3GetTempReg(pParse);
  99524. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
  99525. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  99526. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  99527. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  99528. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  99529. sqlite3VdbeJumpHere(v, addrTop);
  99530. sqlite3ReleaseTempReg(pParse, regRecord);
  99531. /* Jump here when skipping the initialization */
  99532. sqlite3VdbeJumpHere(v, addrInit);
  99533. }
  99534. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  99535. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99536. /*
  99537. ** Allocate and populate an sqlite3_index_info structure. It is the
  99538. ** responsibility of the caller to eventually release the structure
  99539. ** by passing the pointer returned by this function to sqlite3_free().
  99540. */
  99541. static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
  99542. Parse *pParse = p->pParse;
  99543. WhereClause *pWC = p->pWC;
  99544. struct SrcList_item *pSrc = p->pSrc;
  99545. ExprList *pOrderBy = p->pOrderBy;
  99546. int i, j;
  99547. int nTerm;
  99548. struct sqlite3_index_constraint *pIdxCons;
  99549. struct sqlite3_index_orderby *pIdxOrderBy;
  99550. struct sqlite3_index_constraint_usage *pUsage;
  99551. WhereTerm *pTerm;
  99552. int nOrderBy;
  99553. sqlite3_index_info *pIdxInfo;
  99554. WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
  99555. /* Count the number of possible WHERE clause constraints referring
  99556. ** to this virtual table */
  99557. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  99558. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  99559. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  99560. testcase( pTerm->eOperator & WO_IN );
  99561. testcase( pTerm->eOperator & WO_ISNULL );
  99562. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  99563. if( pTerm->wtFlags & TERM_VNULL ) continue;
  99564. nTerm++;
  99565. }
  99566. /* If the ORDER BY clause contains only columns in the current
  99567. ** virtual table then allocate space for the aOrderBy part of
  99568. ** the sqlite3_index_info structure.
  99569. */
  99570. nOrderBy = 0;
  99571. if( pOrderBy ){
  99572. int n = pOrderBy->nExpr;
  99573. for(i=0; i<n; i++){
  99574. Expr *pExpr = pOrderBy->a[i].pExpr;
  99575. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  99576. }
  99577. if( i==n){
  99578. nOrderBy = n;
  99579. }
  99580. }
  99581. /* Allocate the sqlite3_index_info structure
  99582. */
  99583. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  99584. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  99585. + sizeof(*pIdxOrderBy)*nOrderBy );
  99586. if( pIdxInfo==0 ){
  99587. sqlite3ErrorMsg(pParse, "out of memory");
  99588. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  99589. return 0;
  99590. }
  99591. /* Initialize the structure. The sqlite3_index_info structure contains
  99592. ** many fields that are declared "const" to prevent xBestIndex from
  99593. ** changing them. We have to do some funky casting in order to
  99594. ** initialize those fields.
  99595. */
  99596. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  99597. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  99598. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  99599. *(int*)&pIdxInfo->nConstraint = nTerm;
  99600. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  99601. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  99602. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  99603. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  99604. pUsage;
  99605. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  99606. u8 op;
  99607. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  99608. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  99609. testcase( pTerm->eOperator & WO_IN );
  99610. testcase( pTerm->eOperator & WO_ISNULL );
  99611. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  99612. if( pTerm->wtFlags & TERM_VNULL ) continue;
  99613. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  99614. pIdxCons[j].iTermOffset = i;
  99615. op = (u8)pTerm->eOperator & WO_ALL;
  99616. if( op==WO_IN ) op = WO_EQ;
  99617. pIdxCons[j].op = op;
  99618. /* The direct assignment in the previous line is possible only because
  99619. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  99620. ** following asserts verify this fact. */
  99621. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  99622. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  99623. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  99624. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  99625. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  99626. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  99627. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  99628. j++;
  99629. }
  99630. for(i=0; i<nOrderBy; i++){
  99631. Expr *pExpr = pOrderBy->a[i].pExpr;
  99632. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  99633. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  99634. }
  99635. return pIdxInfo;
  99636. }
  99637. /*
  99638. ** The table object reference passed as the second argument to this function
  99639. ** must represent a virtual table. This function invokes the xBestIndex()
  99640. ** method of the virtual table with the sqlite3_index_info pointer passed
  99641. ** as the argument.
  99642. **
  99643. ** If an error occurs, pParse is populated with an error message and a
  99644. ** non-zero value is returned. Otherwise, 0 is returned and the output
  99645. ** part of the sqlite3_index_info structure is left populated.
  99646. **
  99647. ** Whether or not an error is returned, it is the responsibility of the
  99648. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  99649. ** that this is required.
  99650. */
  99651. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  99652. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  99653. int i;
  99654. int rc;
  99655. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  99656. TRACE_IDX_INPUTS(p);
  99657. rc = pVtab->pModule->xBestIndex(pVtab, p);
  99658. TRACE_IDX_OUTPUTS(p);
  99659. if( rc!=SQLITE_OK ){
  99660. if( rc==SQLITE_NOMEM ){
  99661. pParse->db->mallocFailed = 1;
  99662. }else if( !pVtab->zErrMsg ){
  99663. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  99664. }else{
  99665. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  99666. }
  99667. }
  99668. sqlite3_free(pVtab->zErrMsg);
  99669. pVtab->zErrMsg = 0;
  99670. for(i=0; i<p->nConstraint; i++){
  99671. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  99672. sqlite3ErrorMsg(pParse,
  99673. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  99674. }
  99675. }
  99676. return pParse->nErr;
  99677. }
  99678. /*
  99679. ** Compute the best index for a virtual table.
  99680. **
  99681. ** The best index is computed by the xBestIndex method of the virtual
  99682. ** table module. This routine is really just a wrapper that sets up
  99683. ** the sqlite3_index_info structure that is used to communicate with
  99684. ** xBestIndex.
  99685. **
  99686. ** In a join, this routine might be called multiple times for the
  99687. ** same virtual table. The sqlite3_index_info structure is created
  99688. ** and initialized on the first invocation and reused on all subsequent
  99689. ** invocations. The sqlite3_index_info structure is also used when
  99690. ** code is generated to access the virtual table. The whereInfoDelete()
  99691. ** routine takes care of freeing the sqlite3_index_info structure after
  99692. ** everybody has finished with it.
  99693. */
  99694. static void bestVirtualIndex(WhereBestIdx *p){
  99695. Parse *pParse = p->pParse; /* The parsing context */
  99696. WhereClause *pWC = p->pWC; /* The WHERE clause */
  99697. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  99698. Table *pTab = pSrc->pTab;
  99699. sqlite3_index_info *pIdxInfo;
  99700. struct sqlite3_index_constraint *pIdxCons;
  99701. struct sqlite3_index_constraint_usage *pUsage;
  99702. WhereTerm *pTerm;
  99703. int i, j;
  99704. int nOrderBy;
  99705. int bAllowIN; /* Allow IN optimizations */
  99706. double rCost;
  99707. /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
  99708. ** malloc in allocateIndexInfo() fails and this function returns leaving
  99709. ** wsFlags in an uninitialized state, the caller may behave unpredictably.
  99710. */
  99711. memset(&p->cost, 0, sizeof(p->cost));
  99712. p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
  99713. /* If the sqlite3_index_info structure has not been previously
  99714. ** allocated and initialized, then allocate and initialize it now.
  99715. */
  99716. pIdxInfo = *p->ppIdxInfo;
  99717. if( pIdxInfo==0 ){
  99718. *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
  99719. }
  99720. if( pIdxInfo==0 ){
  99721. return;
  99722. }
  99723. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  99724. ** to will have been initialized, either during the current invocation or
  99725. ** during some prior invocation. Now we just have to customize the
  99726. ** details of pIdxInfo for the current invocation and pass it to
  99727. ** xBestIndex.
  99728. */
  99729. /* The module name must be defined. Also, by this point there must
  99730. ** be a pointer to an sqlite3_vtab structure. Otherwise
  99731. ** sqlite3ViewGetColumnNames() would have picked up the error.
  99732. */
  99733. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  99734. assert( sqlite3GetVTable(pParse->db, pTab) );
  99735. /* Try once or twice. On the first attempt, allow IN optimizations.
  99736. ** If an IN optimization is accepted by the virtual table xBestIndex
  99737. ** method, but the pInfo->aConstrainUsage.omit flag is not set, then
  99738. ** the query will not work because it might allow duplicate rows in
  99739. ** output. In that case, run the xBestIndex method a second time
  99740. ** without the IN constraints. Usually this loop only runs once.
  99741. ** The loop will exit using a "break" statement.
  99742. */
  99743. for(bAllowIN=1; 1; bAllowIN--){
  99744. assert( bAllowIN==0 || bAllowIN==1 );
  99745. /* Set the aConstraint[].usable fields and initialize all
  99746. ** output variables to zero.
  99747. **
  99748. ** aConstraint[].usable is true for constraints where the right-hand
  99749. ** side contains only references to tables to the left of the current
  99750. ** table. In other words, if the constraint is of the form:
  99751. **
  99752. ** column = expr
  99753. **
  99754. ** and we are evaluating a join, then the constraint on column is
  99755. ** only valid if all tables referenced in expr occur to the left
  99756. ** of the table containing column.
  99757. **
  99758. ** The aConstraints[] array contains entries for all constraints
  99759. ** on the current table. That way we only have to compute it once
  99760. ** even though we might try to pick the best index multiple times.
  99761. ** For each attempt at picking an index, the order of tables in the
  99762. ** join might be different so we have to recompute the usable flag
  99763. ** each time.
  99764. */
  99765. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  99766. pUsage = pIdxInfo->aConstraintUsage;
  99767. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  99768. j = pIdxCons->iTermOffset;
  99769. pTerm = &pWC->a[j];
  99770. if( (pTerm->prereqRight&p->notReady)==0
  99771. && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
  99772. ){
  99773. pIdxCons->usable = 1;
  99774. }else{
  99775. pIdxCons->usable = 0;
  99776. }
  99777. }
  99778. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  99779. if( pIdxInfo->needToFreeIdxStr ){
  99780. sqlite3_free(pIdxInfo->idxStr);
  99781. }
  99782. pIdxInfo->idxStr = 0;
  99783. pIdxInfo->idxNum = 0;
  99784. pIdxInfo->needToFreeIdxStr = 0;
  99785. pIdxInfo->orderByConsumed = 0;
  99786. /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  99787. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
  99788. nOrderBy = pIdxInfo->nOrderBy;
  99789. if( !p->pOrderBy ){
  99790. pIdxInfo->nOrderBy = 0;
  99791. }
  99792. if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
  99793. return;
  99794. }
  99795. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  99796. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  99797. if( pUsage[i].argvIndex>0 ){
  99798. j = pIdxCons->iTermOffset;
  99799. pTerm = &pWC->a[j];
  99800. p->cost.used |= pTerm->prereqRight;
  99801. if( (pTerm->eOperator & WO_IN)!=0 ){
  99802. if( pUsage[i].omit==0 ){
  99803. /* Do not attempt to use an IN constraint if the virtual table
  99804. ** says that the equivalent EQ constraint cannot be safely omitted.
  99805. ** If we do attempt to use such a constraint, some rows might be
  99806. ** repeated in the output. */
  99807. break;
  99808. }
  99809. /* A virtual table that is constrained by an IN clause may not
  99810. ** consume the ORDER BY clause because (1) the order of IN terms
  99811. ** is not necessarily related to the order of output terms and
  99812. ** (2) Multiple outputs from a single IN value will not merge
  99813. ** together. */
  99814. pIdxInfo->orderByConsumed = 0;
  99815. }
  99816. }
  99817. }
  99818. if( i>=pIdxInfo->nConstraint ) break;
  99819. }
  99820. /* The orderByConsumed signal is only valid if all outer loops collectively
  99821. ** generate just a single row of output.
  99822. */
  99823. if( pIdxInfo->orderByConsumed ){
  99824. for(i=0; i<p->i; i++){
  99825. if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
  99826. pIdxInfo->orderByConsumed = 0;
  99827. }
  99828. }
  99829. }
  99830. /* If there is an ORDER BY clause, and the selected virtual table index
  99831. ** does not satisfy it, increase the cost of the scan accordingly. This
  99832. ** matches the processing for non-virtual tables in bestBtreeIndex().
  99833. */
  99834. rCost = pIdxInfo->estimatedCost;
  99835. if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
  99836. rCost += estLog(rCost)*rCost;
  99837. }
  99838. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  99839. ** inital value of lowestCost in this loop. If it is, then the
  99840. ** (cost<lowestCost) test below will never be true.
  99841. **
  99842. ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
  99843. ** is defined.
  99844. */
  99845. if( (SQLITE_BIG_DBL/((double)2))<rCost ){
  99846. p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
  99847. }else{
  99848. p->cost.rCost = rCost;
  99849. }
  99850. p->cost.plan.u.pVtabIdx = pIdxInfo;
  99851. if( pIdxInfo->orderByConsumed ){
  99852. p->cost.plan.wsFlags |= WHERE_ORDERED;
  99853. p->cost.plan.nOBSat = nOrderBy;
  99854. }else{
  99855. p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
  99856. }
  99857. p->cost.plan.nEq = 0;
  99858. pIdxInfo->nOrderBy = nOrderBy;
  99859. /* Try to find a more efficient access pattern by using multiple indexes
  99860. ** to optimize an OR expression within the WHERE clause.
  99861. */
  99862. bestOrClauseIndex(p);
  99863. }
  99864. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  99865. #ifdef SQLITE_ENABLE_STAT3
  99866. /*
  99867. ** Estimate the location of a particular key among all keys in an
  99868. ** index. Store the results in aStat as follows:
  99869. **
  99870. ** aStat[0] Est. number of rows less than pVal
  99871. ** aStat[1] Est. number of rows equal to pVal
  99872. **
  99873. ** Return SQLITE_OK on success.
  99874. */
  99875. static int whereKeyStats(
  99876. Parse *pParse, /* Database connection */
  99877. Index *pIdx, /* Index to consider domain of */
  99878. sqlite3_value *pVal, /* Value to consider */
  99879. int roundUp, /* Round up if true. Round down if false */
  99880. tRowcnt *aStat /* OUT: stats written here */
  99881. ){
  99882. tRowcnt n;
  99883. IndexSample *aSample;
  99884. int i, eType;
  99885. int isEq = 0;
  99886. i64 v;
  99887. double r, rS;
  99888. assert( roundUp==0 || roundUp==1 );
  99889. assert( pIdx->nSample>0 );
  99890. if( pVal==0 ) return SQLITE_ERROR;
  99891. n = pIdx->aiRowEst[0];
  99892. aSample = pIdx->aSample;
  99893. eType = sqlite3_value_type(pVal);
  99894. if( eType==SQLITE_INTEGER ){
  99895. v = sqlite3_value_int64(pVal);
  99896. r = (i64)v;
  99897. for(i=0; i<pIdx->nSample; i++){
  99898. if( aSample[i].eType==SQLITE_NULL ) continue;
  99899. if( aSample[i].eType>=SQLITE_TEXT ) break;
  99900. if( aSample[i].eType==SQLITE_INTEGER ){
  99901. if( aSample[i].u.i>=v ){
  99902. isEq = aSample[i].u.i==v;
  99903. break;
  99904. }
  99905. }else{
  99906. assert( aSample[i].eType==SQLITE_FLOAT );
  99907. if( aSample[i].u.r>=r ){
  99908. isEq = aSample[i].u.r==r;
  99909. break;
  99910. }
  99911. }
  99912. }
  99913. }else if( eType==SQLITE_FLOAT ){
  99914. r = sqlite3_value_double(pVal);
  99915. for(i=0; i<pIdx->nSample; i++){
  99916. if( aSample[i].eType==SQLITE_NULL ) continue;
  99917. if( aSample[i].eType>=SQLITE_TEXT ) break;
  99918. if( aSample[i].eType==SQLITE_FLOAT ){
  99919. rS = aSample[i].u.r;
  99920. }else{
  99921. rS = aSample[i].u.i;
  99922. }
  99923. if( rS>=r ){
  99924. isEq = rS==r;
  99925. break;
  99926. }
  99927. }
  99928. }else if( eType==SQLITE_NULL ){
  99929. i = 0;
  99930. if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
  99931. }else{
  99932. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  99933. for(i=0; i<pIdx->nSample; i++){
  99934. if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
  99935. break;
  99936. }
  99937. }
  99938. if( i<pIdx->nSample ){
  99939. sqlite3 *db = pParse->db;
  99940. CollSeq *pColl;
  99941. const u8 *z;
  99942. if( eType==SQLITE_BLOB ){
  99943. z = (const u8 *)sqlite3_value_blob(pVal);
  99944. pColl = db->pDfltColl;
  99945. assert( pColl->enc==SQLITE_UTF8 );
  99946. }else{
  99947. pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
  99948. if( pColl==0 ){
  99949. return SQLITE_ERROR;
  99950. }
  99951. z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
  99952. if( !z ){
  99953. return SQLITE_NOMEM;
  99954. }
  99955. assert( z && pColl && pColl->xCmp );
  99956. }
  99957. n = sqlite3ValueBytes(pVal, pColl->enc);
  99958. for(; i<pIdx->nSample; i++){
  99959. int c;
  99960. int eSampletype = aSample[i].eType;
  99961. if( eSampletype<eType ) continue;
  99962. if( eSampletype!=eType ) break;
  99963. #ifndef SQLITE_OMIT_UTF16
  99964. if( pColl->enc!=SQLITE_UTF8 ){
  99965. int nSample;
  99966. char *zSample = sqlite3Utf8to16(
  99967. db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
  99968. );
  99969. if( !zSample ){
  99970. assert( db->mallocFailed );
  99971. return SQLITE_NOMEM;
  99972. }
  99973. c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
  99974. sqlite3DbFree(db, zSample);
  99975. }else
  99976. #endif
  99977. {
  99978. c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
  99979. }
  99980. if( c>=0 ){
  99981. if( c==0 ) isEq = 1;
  99982. break;
  99983. }
  99984. }
  99985. }
  99986. }
  99987. /* At this point, aSample[i] is the first sample that is greater than
  99988. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  99989. ** than pVal. If aSample[i]==pVal, then isEq==1.
  99990. */
  99991. if( isEq ){
  99992. assert( i<pIdx->nSample );
  99993. aStat[0] = aSample[i].nLt;
  99994. aStat[1] = aSample[i].nEq;
  99995. }else{
  99996. tRowcnt iLower, iUpper, iGap;
  99997. if( i==0 ){
  99998. iLower = 0;
  99999. iUpper = aSample[0].nLt;
  100000. }else{
  100001. iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
  100002. iLower = aSample[i-1].nEq + aSample[i-1].nLt;
  100003. }
  100004. aStat[1] = pIdx->avgEq;
  100005. if( iLower>=iUpper ){
  100006. iGap = 0;
  100007. }else{
  100008. iGap = iUpper - iLower;
  100009. }
  100010. if( roundUp ){
  100011. iGap = (iGap*2)/3;
  100012. }else{
  100013. iGap = iGap/3;
  100014. }
  100015. aStat[0] = iLower + iGap;
  100016. }
  100017. return SQLITE_OK;
  100018. }
  100019. #endif /* SQLITE_ENABLE_STAT3 */
  100020. /*
  100021. ** If expression pExpr represents a literal value, set *pp to point to
  100022. ** an sqlite3_value structure containing the same value, with affinity
  100023. ** aff applied to it, before returning. It is the responsibility of the
  100024. ** caller to eventually release this structure by passing it to
  100025. ** sqlite3ValueFree().
  100026. **
  100027. ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
  100028. ** is an SQL variable that currently has a non-NULL value bound to it,
  100029. ** create an sqlite3_value structure containing this value, again with
  100030. ** affinity aff applied to it, instead.
  100031. **
  100032. ** If neither of the above apply, set *pp to NULL.
  100033. **
  100034. ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
  100035. */
  100036. #ifdef SQLITE_ENABLE_STAT3
  100037. static int valueFromExpr(
  100038. Parse *pParse,
  100039. Expr *pExpr,
  100040. u8 aff,
  100041. sqlite3_value **pp
  100042. ){
  100043. if( pExpr->op==TK_VARIABLE
  100044. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  100045. ){
  100046. int iVar = pExpr->iColumn;
  100047. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  100048. *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
  100049. return SQLITE_OK;
  100050. }
  100051. return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
  100052. }
  100053. #endif
  100054. /*
  100055. ** This function is used to estimate the number of rows that will be visited
  100056. ** by scanning an index for a range of values. The range may have an upper
  100057. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  100058. ** and lower bounds are represented by pLower and pUpper respectively. For
  100059. ** example, assuming that index p is on t1(a):
  100060. **
  100061. ** ... FROM t1 WHERE a > ? AND a < ? ...
  100062. ** |_____| |_____|
  100063. ** | |
  100064. ** pLower pUpper
  100065. **
  100066. ** If either of the upper or lower bound is not present, then NULL is passed in
  100067. ** place of the corresponding WhereTerm.
  100068. **
  100069. ** The nEq parameter is passed the index of the index column subject to the
  100070. ** range constraint. Or, equivalently, the number of equality constraints
  100071. ** optimized by the proposed index scan. For example, assuming index p is
  100072. ** on t1(a, b), and the SQL query is:
  100073. **
  100074. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  100075. **
  100076. ** then nEq should be passed the value 1 (as the range restricted column,
  100077. ** b, is the second left-most column of the index). Or, if the query is:
  100078. **
  100079. ** ... FROM t1 WHERE a > ? AND a < ? ...
  100080. **
  100081. ** then nEq should be passed 0.
  100082. **
  100083. ** The returned value is an integer divisor to reduce the estimated
  100084. ** search space. A return value of 1 means that range constraints are
  100085. ** no help at all. A return value of 2 means range constraints are
  100086. ** expected to reduce the search space by half. And so forth...
  100087. **
  100088. ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
  100089. ** reduces the search space by a factor of 4. Hence a single constraint (x>?)
  100090. ** results in a return of 4 and a range constraint (x>? AND x<?) results
  100091. ** in a return of 16.
  100092. */
  100093. static int whereRangeScanEst(
  100094. Parse *pParse, /* Parsing & code generating context */
  100095. Index *p, /* The index containing the range-compared column; "x" */
  100096. int nEq, /* index into p->aCol[] of the range-compared column */
  100097. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  100098. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  100099. double *pRangeDiv /* OUT: Reduce search space by this divisor */
  100100. ){
  100101. int rc = SQLITE_OK;
  100102. #ifdef SQLITE_ENABLE_STAT3
  100103. if( nEq==0 && p->nSample ){
  100104. sqlite3_value *pRangeVal;
  100105. tRowcnt iLower = 0;
  100106. tRowcnt iUpper = p->aiRowEst[0];
  100107. tRowcnt a[2];
  100108. u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  100109. if( pLower ){
  100110. Expr *pExpr = pLower->pExpr->pRight;
  100111. rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
  100112. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  100113. if( rc==SQLITE_OK
  100114. && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
  100115. ){
  100116. iLower = a[0];
  100117. if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
  100118. }
  100119. sqlite3ValueFree(pRangeVal);
  100120. }
  100121. if( rc==SQLITE_OK && pUpper ){
  100122. Expr *pExpr = pUpper->pExpr->pRight;
  100123. rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
  100124. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  100125. if( rc==SQLITE_OK
  100126. && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
  100127. ){
  100128. iUpper = a[0];
  100129. if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
  100130. }
  100131. sqlite3ValueFree(pRangeVal);
  100132. }
  100133. if( rc==SQLITE_OK ){
  100134. if( iUpper<=iLower ){
  100135. *pRangeDiv = (double)p->aiRowEst[0];
  100136. }else{
  100137. *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
  100138. }
  100139. WHERETRACE(("range scan regions: %u..%u div=%g\n",
  100140. (u32)iLower, (u32)iUpper, *pRangeDiv));
  100141. return SQLITE_OK;
  100142. }
  100143. }
  100144. #else
  100145. UNUSED_PARAMETER(pParse);
  100146. UNUSED_PARAMETER(p);
  100147. UNUSED_PARAMETER(nEq);
  100148. #endif
  100149. assert( pLower || pUpper );
  100150. *pRangeDiv = (double)1;
  100151. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
  100152. if( pUpper ) *pRangeDiv *= (double)4;
  100153. return rc;
  100154. }
  100155. #ifdef SQLITE_ENABLE_STAT3
  100156. /*
  100157. ** Estimate the number of rows that will be returned based on
  100158. ** an equality constraint x=VALUE and where that VALUE occurs in
  100159. ** the histogram data. This only works when x is the left-most
  100160. ** column of an index and sqlite_stat3 histogram data is available
  100161. ** for that index. When pExpr==NULL that means the constraint is
  100162. ** "x IS NULL" instead of "x=VALUE".
  100163. **
  100164. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  100165. ** If unable to make an estimate, leave *pnRow unchanged and return
  100166. ** non-zero.
  100167. **
  100168. ** This routine can fail if it is unable to load a collating sequence
  100169. ** required for string comparison, or if unable to allocate memory
  100170. ** for a UTF conversion required for comparison. The error is stored
  100171. ** in the pParse structure.
  100172. */
  100173. static int whereEqualScanEst(
  100174. Parse *pParse, /* Parsing & code generating context */
  100175. Index *p, /* The index whose left-most column is pTerm */
  100176. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  100177. double *pnRow /* Write the revised row estimate here */
  100178. ){
  100179. sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
  100180. u8 aff; /* Column affinity */
  100181. int rc; /* Subfunction return code */
  100182. tRowcnt a[2]; /* Statistics */
  100183. assert( p->aSample!=0 );
  100184. assert( p->nSample>0 );
  100185. aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  100186. if( pExpr ){
  100187. rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
  100188. if( rc ) goto whereEqualScanEst_cancel;
  100189. }else{
  100190. pRhs = sqlite3ValueNew(pParse->db);
  100191. }
  100192. if( pRhs==0 ) return SQLITE_NOTFOUND;
  100193. rc = whereKeyStats(pParse, p, pRhs, 0, a);
  100194. if( rc==SQLITE_OK ){
  100195. WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
  100196. *pnRow = a[1];
  100197. }
  100198. whereEqualScanEst_cancel:
  100199. sqlite3ValueFree(pRhs);
  100200. return rc;
  100201. }
  100202. #endif /* defined(SQLITE_ENABLE_STAT3) */
  100203. #ifdef SQLITE_ENABLE_STAT3
  100204. /*
  100205. ** Estimate the number of rows that will be returned based on
  100206. ** an IN constraint where the right-hand side of the IN operator
  100207. ** is a list of values. Example:
  100208. **
  100209. ** WHERE x IN (1,2,3,4)
  100210. **
  100211. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  100212. ** If unable to make an estimate, leave *pnRow unchanged and return
  100213. ** non-zero.
  100214. **
  100215. ** This routine can fail if it is unable to load a collating sequence
  100216. ** required for string comparison, or if unable to allocate memory
  100217. ** for a UTF conversion required for comparison. The error is stored
  100218. ** in the pParse structure.
  100219. */
  100220. static int whereInScanEst(
  100221. Parse *pParse, /* Parsing & code generating context */
  100222. Index *p, /* The index whose left-most column is pTerm */
  100223. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  100224. double *pnRow /* Write the revised row estimate here */
  100225. ){
  100226. int rc = SQLITE_OK; /* Subfunction return code */
  100227. double nEst; /* Number of rows for a single term */
  100228. double nRowEst = (double)0; /* New estimate of the number of rows */
  100229. int i; /* Loop counter */
  100230. assert( p->aSample!=0 );
  100231. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  100232. nEst = p->aiRowEst[0];
  100233. rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
  100234. nRowEst += nEst;
  100235. }
  100236. if( rc==SQLITE_OK ){
  100237. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  100238. *pnRow = nRowEst;
  100239. WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
  100240. }
  100241. return rc;
  100242. }
  100243. #endif /* defined(SQLITE_ENABLE_STAT3) */
  100244. /*
  100245. ** Check to see if column iCol of the table with cursor iTab will appear
  100246. ** in sorted order according to the current query plan.
  100247. **
  100248. ** Return values:
  100249. **
  100250. ** 0 iCol is not ordered
  100251. ** 1 iCol has only a single value
  100252. ** 2 iCol is in ASC order
  100253. ** 3 iCol is in DESC order
  100254. */
  100255. static int isOrderedColumn(
  100256. WhereBestIdx *p,
  100257. int iTab,
  100258. int iCol
  100259. ){
  100260. int i, j;
  100261. WhereLevel *pLevel = &p->aLevel[p->i-1];
  100262. Index *pIdx;
  100263. u8 sortOrder;
  100264. for(i=p->i-1; i>=0; i--, pLevel--){
  100265. if( pLevel->iTabCur!=iTab ) continue;
  100266. if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  100267. return 1;
  100268. }
  100269. assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
  100270. if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
  100271. if( iCol<0 ){
  100272. sortOrder = 0;
  100273. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  100274. }else{
  100275. int n = pIdx->nColumn;
  100276. for(j=0; j<n; j++){
  100277. if( iCol==pIdx->aiColumn[j] ) break;
  100278. }
  100279. if( j>=n ) return 0;
  100280. sortOrder = pIdx->aSortOrder[j];
  100281. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  100282. }
  100283. }else{
  100284. if( iCol!=(-1) ) return 0;
  100285. sortOrder = 0;
  100286. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  100287. }
  100288. if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
  100289. assert( sortOrder==0 || sortOrder==1 );
  100290. testcase( sortOrder==1 );
  100291. sortOrder = 1 - sortOrder;
  100292. }
  100293. return sortOrder+2;
  100294. }
  100295. return 0;
  100296. }
  100297. /*
  100298. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  100299. ** clause, either in whole or in part. The return value is the
  100300. ** cumulative number of terms in the ORDER BY clause that are satisfied
  100301. ** by the index pIdx and other indices in outer loops.
  100302. **
  100303. ** The table being queried has a cursor number of "base". pIdx is the
  100304. ** index that is postulated for use to access the table.
  100305. **
  100306. ** The *pbRev value is set to 0 order 1 depending on whether or not
  100307. ** pIdx should be run in the forward order or in reverse order.
  100308. */
  100309. static int isSortingIndex(
  100310. WhereBestIdx *p, /* Best index search context */
  100311. Index *pIdx, /* The index we are testing */
  100312. int base, /* Cursor number for the table to be sorted */
  100313. int *pbRev, /* Set to 1 for reverse-order scan of pIdx */
  100314. int *pbObUnique /* ORDER BY column values will different in every row */
  100315. ){
  100316. int i; /* Number of pIdx terms used */
  100317. int j; /* Number of ORDER BY terms satisfied */
  100318. int sortOrder = 2; /* 0: forward. 1: backward. 2: unknown */
  100319. int nTerm; /* Number of ORDER BY terms */
  100320. struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
  100321. Table *pTab = pIdx->pTable; /* Table that owns index pIdx */
  100322. ExprList *pOrderBy; /* The ORDER BY clause */
  100323. Parse *pParse = p->pParse; /* Parser context */
  100324. sqlite3 *db = pParse->db; /* Database connection */
  100325. int nPriorSat; /* ORDER BY terms satisfied by outer loops */
  100326. int seenRowid = 0; /* True if an ORDER BY rowid term is seen */
  100327. int uniqueNotNull; /* pIdx is UNIQUE with all terms are NOT NULL */
  100328. int outerObUnique; /* Outer loops generate different values in
  100329. ** every row for the ORDER BY columns */
  100330. if( p->i==0 ){
  100331. nPriorSat = 0;
  100332. outerObUnique = 1;
  100333. }else{
  100334. u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
  100335. nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
  100336. if( (wsFlags & WHERE_ORDERED)==0 ){
  100337. /* This loop cannot be ordered unless the next outer loop is
  100338. ** also ordered */
  100339. return nPriorSat;
  100340. }
  100341. if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
  100342. /* Only look at the outer-most loop if the OrderByIdxJoin
  100343. ** optimization is disabled */
  100344. return nPriorSat;
  100345. }
  100346. testcase( wsFlags & WHERE_OB_UNIQUE );
  100347. testcase( wsFlags & WHERE_ALL_UNIQUE );
  100348. outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
  100349. }
  100350. pOrderBy = p->pOrderBy;
  100351. assert( pOrderBy!=0 );
  100352. if( pIdx->bUnordered ){
  100353. /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
  100354. ** be used for sorting */
  100355. return nPriorSat;
  100356. }
  100357. nTerm = pOrderBy->nExpr;
  100358. uniqueNotNull = pIdx->onError!=OE_None;
  100359. assert( nTerm>0 );
  100360. /* Argument pIdx must either point to a 'real' named index structure,
  100361. ** or an index structure allocated on the stack by bestBtreeIndex() to
  100362. ** represent the rowid index that is part of every table. */
  100363. assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
  100364. /* Match terms of the ORDER BY clause against columns of
  100365. ** the index.
  100366. **
  100367. ** Note that indices have pIdx->nColumn regular columns plus
  100368. ** one additional column containing the rowid. The rowid column
  100369. ** of the index is also allowed to match against the ORDER BY
  100370. ** clause.
  100371. */
  100372. j = nPriorSat;
  100373. for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
  100374. Expr *pOBExpr; /* The expression of the ORDER BY pOBItem */
  100375. CollSeq *pColl; /* The collating sequence of pOBExpr */
  100376. int termSortOrder; /* Sort order for this term */
  100377. int iColumn; /* The i-th column of the index. -1 for rowid */
  100378. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  100379. int isEq; /* Subject to an == or IS NULL constraint */
  100380. int isMatch; /* ORDER BY term matches the index term */
  100381. const char *zColl; /* Name of collating sequence for i-th index term */
  100382. WhereTerm *pConstraint; /* A constraint in the WHERE clause */
  100383. /* If the next term of the ORDER BY clause refers to anything other than
  100384. ** a column in the "base" table, then this index will not be of any
  100385. ** further use in handling the ORDER BY. */
  100386. pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
  100387. if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
  100388. break;
  100389. }
  100390. /* Find column number and collating sequence for the next entry
  100391. ** in the index */
  100392. if( pIdx->zName && i<pIdx->nColumn ){
  100393. iColumn = pIdx->aiColumn[i];
  100394. if( iColumn==pIdx->pTable->iPKey ){
  100395. iColumn = -1;
  100396. }
  100397. iSortOrder = pIdx->aSortOrder[i];
  100398. zColl = pIdx->azColl[i];
  100399. assert( zColl!=0 );
  100400. }else{
  100401. iColumn = -1;
  100402. iSortOrder = 0;
  100403. zColl = 0;
  100404. }
  100405. /* Check to see if the column number and collating sequence of the
  100406. ** index match the column number and collating sequence of the ORDER BY
  100407. ** clause entry. Set isMatch to 1 if they both match. */
  100408. if( pOBExpr->iColumn==iColumn ){
  100409. if( zColl ){
  100410. pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
  100411. if( !pColl ) pColl = db->pDfltColl;
  100412. isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
  100413. }else{
  100414. isMatch = 1;
  100415. }
  100416. }else{
  100417. isMatch = 0;
  100418. }
  100419. /* termSortOrder is 0 or 1 for whether or not the access loop should
  100420. ** run forward or backwards (respectively) in order to satisfy this
  100421. ** term of the ORDER BY clause. */
  100422. assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
  100423. assert( iSortOrder==0 || iSortOrder==1 );
  100424. termSortOrder = iSortOrder ^ pOBItem->sortOrder;
  100425. /* If X is the column in the index and ORDER BY clause, check to see
  100426. ** if there are any X= or X IS NULL constraints in the WHERE clause. */
  100427. pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
  100428. WO_EQ|WO_ISNULL|WO_IN, pIdx);
  100429. if( pConstraint==0 ){
  100430. isEq = 0;
  100431. }else if( (pConstraint->eOperator & WO_IN)!=0 ){
  100432. isEq = 0;
  100433. }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
  100434. uniqueNotNull = 0;
  100435. isEq = 1; /* "X IS NULL" means X has only a single value */
  100436. }else if( pConstraint->prereqRight==0 ){
  100437. isEq = 1; /* Constraint "X=constant" means X has only a single value */
  100438. }else{
  100439. Expr *pRight = pConstraint->pExpr->pRight;
  100440. if( pRight->op==TK_COLUMN ){
  100441. WHERETRACE((" .. isOrderedColumn(tab=%d,col=%d)",
  100442. pRight->iTable, pRight->iColumn));
  100443. isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
  100444. WHERETRACE((" -> isEq=%d\n", isEq));
  100445. /* If the constraint is of the form X=Y where Y is an ordered value
  100446. ** in an outer loop, then make sure the sort order of Y matches the
  100447. ** sort order required for X. */
  100448. if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
  100449. testcase( isEq==2 );
  100450. testcase( isEq==3 );
  100451. break;
  100452. }
  100453. }else{
  100454. isEq = 0; /* "X=expr" places no ordering constraints on X */
  100455. }
  100456. }
  100457. if( !isMatch ){
  100458. if( isEq==0 ){
  100459. break;
  100460. }else{
  100461. continue;
  100462. }
  100463. }else if( isEq!=1 ){
  100464. if( sortOrder==2 ){
  100465. sortOrder = termSortOrder;
  100466. }else if( termSortOrder!=sortOrder ){
  100467. break;
  100468. }
  100469. }
  100470. j++;
  100471. pOBItem++;
  100472. if( iColumn<0 ){
  100473. seenRowid = 1;
  100474. break;
  100475. }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
  100476. testcase( isEq==0 );
  100477. testcase( isEq==2 );
  100478. testcase( isEq==3 );
  100479. uniqueNotNull = 0;
  100480. }
  100481. }
  100482. if( seenRowid ){
  100483. uniqueNotNull = 1;
  100484. }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
  100485. uniqueNotNull = 0;
  100486. }
  100487. /* If we have not found at least one ORDER BY term that matches the
  100488. ** index, then show no progress. */
  100489. if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
  100490. /* Either the outer queries must generate rows where there are no two
  100491. ** rows with the same values in all ORDER BY columns, or else this
  100492. ** loop must generate just a single row of output. Example: Suppose
  100493. ** the outer loops generate A=1 and A=1, and this loop generates B=3
  100494. ** and B=4. Then without the following test, ORDER BY A,B would
  100495. ** generate the wrong order output: 1,3 1,4 1,3 1,4
  100496. */
  100497. if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
  100498. *pbObUnique = uniqueNotNull;
  100499. /* Return the necessary scan order back to the caller */
  100500. *pbRev = sortOrder & 1;
  100501. /* If there was an "ORDER BY rowid" term that matched, or it is only
  100502. ** possible for a single row from this table to match, then skip over
  100503. ** any additional ORDER BY terms dealing with this table.
  100504. */
  100505. if( uniqueNotNull ){
  100506. /* Advance j over additional ORDER BY terms associated with base */
  100507. WhereMaskSet *pMS = p->pWC->pMaskSet;
  100508. Bitmask m = ~getMask(pMS, base);
  100509. while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
  100510. j++;
  100511. }
  100512. }
  100513. return j;
  100514. }
  100515. /*
  100516. ** Find the best query plan for accessing a particular table. Write the
  100517. ** best query plan and its cost into the p->cost.
  100518. **
  100519. ** The lowest cost plan wins. The cost is an estimate of the amount of
  100520. ** CPU and disk I/O needed to process the requested result.
  100521. ** Factors that influence cost include:
  100522. **
  100523. ** * The estimated number of rows that will be retrieved. (The
  100524. ** fewer the better.)
  100525. **
  100526. ** * Whether or not sorting must occur.
  100527. **
  100528. ** * Whether or not there must be separate lookups in the
  100529. ** index and in the main table.
  100530. **
  100531. ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
  100532. ** the SQL statement, then this function only considers plans using the
  100533. ** named index. If no such plan is found, then the returned cost is
  100534. ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
  100535. ** then the cost is calculated in the usual way.
  100536. **
  100537. ** If a NOT INDEXED clause was attached to the table
  100538. ** in the SELECT statement, then no indexes are considered. However, the
  100539. ** selected plan may still take advantage of the built-in rowid primary key
  100540. ** index.
  100541. */
  100542. static void bestBtreeIndex(WhereBestIdx *p){
  100543. Parse *pParse = p->pParse; /* The parsing context */
  100544. WhereClause *pWC = p->pWC; /* The WHERE clause */
  100545. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  100546. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  100547. Index *pProbe; /* An index we are evaluating */
  100548. Index *pIdx; /* Copy of pProbe, or zero for IPK index */
  100549. int eqTermMask; /* Current mask of valid equality operators */
  100550. int idxEqTermMask; /* Index mask of valid equality operators */
  100551. Index sPk; /* A fake index object for the primary key */
  100552. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  100553. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  100554. int wsFlagMask; /* Allowed flags in p->cost.plan.wsFlag */
  100555. int nPriorSat; /* ORDER BY terms satisfied by outer loops */
  100556. int nOrderBy; /* Number of ORDER BY terms */
  100557. char bSortInit; /* Initializer for bSort in inner loop */
  100558. char bDistInit; /* Initializer for bDist in inner loop */
  100559. /* Initialize the cost to a worst-case value */
  100560. memset(&p->cost, 0, sizeof(p->cost));
  100561. p->cost.rCost = SQLITE_BIG_DBL;
  100562. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  100563. ** use an index to satisfy IS NULL constraints on that table. This is
  100564. ** because columns might end up being NULL if the table does not match -
  100565. ** a circumstance which the index cannot help us discover. Ticket #2177.
  100566. */
  100567. if( pSrc->jointype & JT_LEFT ){
  100568. idxEqTermMask = WO_EQ|WO_IN;
  100569. }else{
  100570. idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  100571. }
  100572. if( pSrc->pIndex ){
  100573. /* An INDEXED BY clause specifies a particular index to use */
  100574. pIdx = pProbe = pSrc->pIndex;
  100575. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  100576. eqTermMask = idxEqTermMask;
  100577. }else{
  100578. /* There is no INDEXED BY clause. Create a fake Index object in local
  100579. ** variable sPk to represent the rowid primary key index. Make this
  100580. ** fake index the first in a chain of Index objects with all of the real
  100581. ** indices to follow */
  100582. Index *pFirst; /* First of real indices on the table */
  100583. memset(&sPk, 0, sizeof(Index));
  100584. sPk.nColumn = 1;
  100585. sPk.aiColumn = &aiColumnPk;
  100586. sPk.aiRowEst = aiRowEstPk;
  100587. sPk.onError = OE_Replace;
  100588. sPk.pTable = pSrc->pTab;
  100589. aiRowEstPk[0] = pSrc->pTab->nRowEst;
  100590. aiRowEstPk[1] = 1;
  100591. pFirst = pSrc->pTab->pIndex;
  100592. if( pSrc->notIndexed==0 ){
  100593. /* The real indices of the table are only considered if the
  100594. ** NOT INDEXED qualifier is omitted from the FROM clause */
  100595. sPk.pNext = pFirst;
  100596. }
  100597. pProbe = &sPk;
  100598. wsFlagMask = ~(
  100599. WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
  100600. );
  100601. eqTermMask = WO_EQ|WO_IN;
  100602. pIdx = 0;
  100603. }
  100604. nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
  100605. if( p->i ){
  100606. nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
  100607. bSortInit = nPriorSat<nOrderBy;
  100608. bDistInit = 0;
  100609. }else{
  100610. nPriorSat = 0;
  100611. bSortInit = nOrderBy>0;
  100612. bDistInit = p->pDistinct!=0;
  100613. }
  100614. /* Loop over all indices looking for the best one to use
  100615. */
  100616. for(; pProbe; pIdx=pProbe=pProbe->pNext){
  100617. const tRowcnt * const aiRowEst = pProbe->aiRowEst;
  100618. WhereCost pc; /* Cost of using pProbe */
  100619. double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
  100620. /* The following variables are populated based on the properties of
  100621. ** index being evaluated. They are then used to determine the expected
  100622. ** cost and number of rows returned.
  100623. **
  100624. ** pc.plan.nEq:
  100625. ** Number of equality terms that can be implemented using the index.
  100626. ** In other words, the number of initial fields in the index that
  100627. ** are used in == or IN or NOT NULL constraints of the WHERE clause.
  100628. **
  100629. ** nInMul:
  100630. ** The "in-multiplier". This is an estimate of how many seek operations
  100631. ** SQLite must perform on the index in question. For example, if the
  100632. ** WHERE clause is:
  100633. **
  100634. ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
  100635. **
  100636. ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
  100637. ** set to 9. Given the same schema and either of the following WHERE
  100638. ** clauses:
  100639. **
  100640. ** WHERE a = 1
  100641. ** WHERE a >= 2
  100642. **
  100643. ** nInMul is set to 1.
  100644. **
  100645. ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
  100646. ** the sub-select is assumed to return 25 rows for the purposes of
  100647. ** determining nInMul.
  100648. **
  100649. ** bInEst:
  100650. ** Set to true if there was at least one "x IN (SELECT ...)" term used
  100651. ** in determining the value of nInMul. Note that the RHS of the
  100652. ** IN operator must be a SELECT, not a value list, for this variable
  100653. ** to be true.
  100654. **
  100655. ** rangeDiv:
  100656. ** An estimate of a divisor by which to reduce the search space due
  100657. ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
  100658. ** data, a single inequality reduces the search space to 1/4rd its
  100659. ** original size (rangeDiv==4). Two inequalities reduce the search
  100660. ** space to 1/16th of its original size (rangeDiv==16).
  100661. **
  100662. ** bSort:
  100663. ** Boolean. True if there is an ORDER BY clause that will require an
  100664. ** external sort (i.e. scanning the index being evaluated will not
  100665. ** correctly order records).
  100666. **
  100667. ** bDist:
  100668. ** Boolean. True if there is a DISTINCT clause that will require an
  100669. ** external btree.
  100670. **
  100671. ** bLookup:
  100672. ** Boolean. True if a table lookup is required for each index entry
  100673. ** visited. In other words, true if this is not a covering index.
  100674. ** This is always false for the rowid primary key index of a table.
  100675. ** For other indexes, it is true unless all the columns of the table
  100676. ** used by the SELECT statement are present in the index (such an
  100677. ** index is sometimes described as a covering index).
  100678. ** For example, given the index on (a, b), the second of the following
  100679. ** two queries requires table b-tree lookups in order to find the value
  100680. ** of column c, but the first does not because columns a and b are
  100681. ** both available in the index.
  100682. **
  100683. ** SELECT a, b FROM tbl WHERE a = 1;
  100684. ** SELECT a, b, c FROM tbl WHERE a = 1;
  100685. */
  100686. int bInEst = 0; /* True if "x IN (SELECT...)" seen */
  100687. int nInMul = 1; /* Number of distinct equalities to lookup */
  100688. double rangeDiv = (double)1; /* Estimated reduction in search space */
  100689. int nBound = 0; /* Number of range constraints seen */
  100690. char bSort = bSortInit; /* True if external sort required */
  100691. char bDist = bDistInit; /* True if index cannot help with DISTINCT */
  100692. char bLookup = 0; /* True if not a covering index */
  100693. WhereTerm *pTerm; /* A single term of the WHERE clause */
  100694. #ifdef SQLITE_ENABLE_STAT3
  100695. WhereTerm *pFirstTerm = 0; /* First term matching the index */
  100696. #endif
  100697. WHERETRACE((
  100698. " %s(%s):\n",
  100699. pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
  100700. ));
  100701. memset(&pc, 0, sizeof(pc));
  100702. pc.plan.nOBSat = nPriorSat;
  100703. /* Determine the values of pc.plan.nEq and nInMul */
  100704. for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
  100705. int j = pProbe->aiColumn[pc.plan.nEq];
  100706. pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
  100707. if( pTerm==0 ) break;
  100708. pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
  100709. testcase( pTerm->pWC!=pWC );
  100710. if( pTerm->eOperator & WO_IN ){
  100711. Expr *pExpr = pTerm->pExpr;
  100712. pc.plan.wsFlags |= WHERE_COLUMN_IN;
  100713. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  100714. /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
  100715. nInMul *= 25;
  100716. bInEst = 1;
  100717. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  100718. /* "x IN (value, value, ...)" */
  100719. nInMul *= pExpr->x.pList->nExpr;
  100720. }
  100721. }else if( pTerm->eOperator & WO_ISNULL ){
  100722. pc.plan.wsFlags |= WHERE_COLUMN_NULL;
  100723. }
  100724. #ifdef SQLITE_ENABLE_STAT3
  100725. if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
  100726. #endif
  100727. pc.used |= pTerm->prereqRight;
  100728. }
  100729. /* If the index being considered is UNIQUE, and there is an equality
  100730. ** constraint for all columns in the index, then this search will find
  100731. ** at most a single row. In this case set the WHERE_UNIQUE flag to
  100732. ** indicate this to the caller.
  100733. **
  100734. ** Otherwise, if the search may find more than one row, test to see if
  100735. ** there is a range constraint on indexed column (pc.plan.nEq+1) that
  100736. ** can be optimized using the index.
  100737. */
  100738. if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
  100739. testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
  100740. testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
  100741. if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
  100742. pc.plan.wsFlags |= WHERE_UNIQUE;
  100743. if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  100744. pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
  100745. }
  100746. }
  100747. }else if( pProbe->bUnordered==0 ){
  100748. int j;
  100749. j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
  100750. if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
  100751. WhereTerm *pTop, *pBtm;
  100752. pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
  100753. pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
  100754. whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
  100755. if( pTop ){
  100756. nBound = 1;
  100757. pc.plan.wsFlags |= WHERE_TOP_LIMIT;
  100758. pc.used |= pTop->prereqRight;
  100759. testcase( pTop->pWC!=pWC );
  100760. }
  100761. if( pBtm ){
  100762. nBound++;
  100763. pc.plan.wsFlags |= WHERE_BTM_LIMIT;
  100764. pc.used |= pBtm->prereqRight;
  100765. testcase( pBtm->pWC!=pWC );
  100766. }
  100767. pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
  100768. }
  100769. }
  100770. /* If there is an ORDER BY clause and the index being considered will
  100771. ** naturally scan rows in the required order, set the appropriate flags
  100772. ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
  100773. ** the index will scan rows in a different order, set the bSort
  100774. ** variable. */
  100775. if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
  100776. int bRev = 2;
  100777. int bObUnique = 0;
  100778. WHERETRACE((" --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
  100779. pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
  100780. WHERETRACE((" --> after isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
  100781. bRev, bObUnique, pc.plan.nOBSat));
  100782. if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  100783. pc.plan.wsFlags |= WHERE_ORDERED;
  100784. if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
  100785. }
  100786. if( nOrderBy==pc.plan.nOBSat ){
  100787. bSort = 0;
  100788. pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
  100789. }
  100790. if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
  100791. }
  100792. /* If there is a DISTINCT qualifier and this index will scan rows in
  100793. ** order of the DISTINCT expressions, clear bDist and set the appropriate
  100794. ** flags in pc.plan.wsFlags. */
  100795. if( bDist
  100796. && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
  100797. && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
  100798. ){
  100799. bDist = 0;
  100800. pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
  100801. }
  100802. /* If currently calculating the cost of using an index (not the IPK
  100803. ** index), determine if all required column data may be obtained without
  100804. ** using the main table (i.e. if the index is a covering
  100805. ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
  100806. ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true. */
  100807. if( pIdx ){
  100808. Bitmask m = pSrc->colUsed;
  100809. int j;
  100810. for(j=0; j<pIdx->nColumn; j++){
  100811. int x = pIdx->aiColumn[j];
  100812. if( x<BMS-1 ){
  100813. m &= ~(((Bitmask)1)<<x);
  100814. }
  100815. }
  100816. if( m==0 ){
  100817. pc.plan.wsFlags |= WHERE_IDX_ONLY;
  100818. }else{
  100819. bLookup = 1;
  100820. }
  100821. }
  100822. /*
  100823. ** Estimate the number of rows of output. For an "x IN (SELECT...)"
  100824. ** constraint, do not let the estimate exceed half the rows in the table.
  100825. */
  100826. pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
  100827. if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
  100828. pc.plan.nRow = aiRowEst[0]/2;
  100829. nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
  100830. }
  100831. #ifdef SQLITE_ENABLE_STAT3
  100832. /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
  100833. ** and we do not think that values of x are unique and if histogram
  100834. ** data is available for column x, then it might be possible
  100835. ** to get a better estimate on the number of rows based on
  100836. ** VALUE and how common that value is according to the histogram.
  100837. */
  100838. if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
  100839. && pFirstTerm!=0 && aiRowEst[1]>1 ){
  100840. assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
  100841. if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
  100842. testcase( pFirstTerm->eOperator & WO_EQ );
  100843. testcase( pFirstTerm->eOperator & WO_EQUIV );
  100844. testcase( pFirstTerm->eOperator & WO_ISNULL );
  100845. whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
  100846. &pc.plan.nRow);
  100847. }else if( bInEst==0 ){
  100848. assert( pFirstTerm->eOperator & WO_IN );
  100849. whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
  100850. &pc.plan.nRow);
  100851. }
  100852. }
  100853. #endif /* SQLITE_ENABLE_STAT3 */
  100854. /* Adjust the number of output rows and downward to reflect rows
  100855. ** that are excluded by range constraints.
  100856. */
  100857. pc.plan.nRow = pc.plan.nRow/rangeDiv;
  100858. if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
  100859. /* Experiments run on real SQLite databases show that the time needed
  100860. ** to do a binary search to locate a row in a table or index is roughly
  100861. ** log10(N) times the time to move from one row to the next row within
  100862. ** a table or index. The actual times can vary, with the size of
  100863. ** records being an important factor. Both moves and searches are
  100864. ** slower with larger records, presumably because fewer records fit
  100865. ** on one page and hence more pages have to be fetched.
  100866. **
  100867. ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
  100868. ** not give us data on the relative sizes of table and index records.
  100869. ** So this computation assumes table records are about twice as big
  100870. ** as index records
  100871. */
  100872. if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
  100873. ==WHERE_IDX_ONLY
  100874. && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  100875. && sqlite3GlobalConfig.bUseCis
  100876. && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
  100877. ){
  100878. /* This index is not useful for indexing, but it is a covering index.
  100879. ** A full-scan of the index might be a little faster than a full-scan
  100880. ** of the table, so give this case a cost slightly less than a table
  100881. ** scan. */
  100882. pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
  100883. pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
  100884. }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  100885. /* The cost of a full table scan is a number of move operations equal
  100886. ** to the number of rows in the table.
  100887. **
  100888. ** We add an additional 4x penalty to full table scans. This causes
  100889. ** the cost function to err on the side of choosing an index over
  100890. ** choosing a full scan. This 4x full-scan penalty is an arguable
  100891. ** decision and one which we expect to revisit in the future. But
  100892. ** it seems to be working well enough at the moment.
  100893. */
  100894. pc.rCost = aiRowEst[0]*4;
  100895. pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
  100896. if( pIdx ){
  100897. pc.plan.wsFlags &= ~WHERE_ORDERED;
  100898. pc.plan.nOBSat = nPriorSat;
  100899. }
  100900. }else{
  100901. log10N = estLog(aiRowEst[0]);
  100902. pc.rCost = pc.plan.nRow;
  100903. if( pIdx ){
  100904. if( bLookup ){
  100905. /* For an index lookup followed by a table lookup:
  100906. ** nInMul index searches to find the start of each index range
  100907. ** + nRow steps through the index
  100908. ** + nRow table searches to lookup the table entry using the rowid
  100909. */
  100910. pc.rCost += (nInMul + pc.plan.nRow)*log10N;
  100911. }else{
  100912. /* For a covering index:
  100913. ** nInMul index searches to find the initial entry
  100914. ** + nRow steps through the index
  100915. */
  100916. pc.rCost += nInMul*log10N;
  100917. }
  100918. }else{
  100919. /* For a rowid primary key lookup:
  100920. ** nInMult table searches to find the initial entry for each range
  100921. ** + nRow steps through the table
  100922. */
  100923. pc.rCost += nInMul*log10N;
  100924. }
  100925. }
  100926. /* Add in the estimated cost of sorting the result. Actual experimental
  100927. ** measurements of sorting performance in SQLite show that sorting time
  100928. ** adds C*N*log10(N) to the cost, where N is the number of rows to be
  100929. ** sorted and C is a factor between 1.95 and 4.3. We will split the
  100930. ** difference and select C of 3.0.
  100931. */
  100932. if( bSort ){
  100933. double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
  100934. m *= (double)(pc.plan.nOBSat ? 2 : 3);
  100935. pc.rCost += pc.plan.nRow*m;
  100936. }
  100937. if( bDist ){
  100938. pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
  100939. }
  100940. /**** Cost of using this index has now been computed ****/
  100941. /* If there are additional constraints on this table that cannot
  100942. ** be used with the current index, but which might lower the number
  100943. ** of output rows, adjust the nRow value accordingly. This only
  100944. ** matters if the current index is the least costly, so do not bother
  100945. ** with this step if we already know this index will not be chosen.
  100946. ** Also, never reduce the output row count below 2 using this step.
  100947. **
  100948. ** It is critical that the notValid mask be used here instead of
  100949. ** the notReady mask. When computing an "optimal" index, the notReady
  100950. ** mask will only have one bit set - the bit for the current table.
  100951. ** The notValid mask, on the other hand, always has all bits set for
  100952. ** tables that are not in outer loops. If notReady is used here instead
  100953. ** of notValid, then a optimal index that depends on inner joins loops
  100954. ** might be selected even when there exists an optimal index that has
  100955. ** no such dependency.
  100956. */
  100957. if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
  100958. int k; /* Loop counter */
  100959. int nSkipEq = pc.plan.nEq; /* Number of == constraints to skip */
  100960. int nSkipRange = nBound; /* Number of < constraints to skip */
  100961. Bitmask thisTab; /* Bitmap for pSrc */
  100962. thisTab = getMask(pWC->pMaskSet, iCur);
  100963. for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
  100964. if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
  100965. if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
  100966. if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
  100967. if( nSkipEq ){
  100968. /* Ignore the first pc.plan.nEq equality matches since the index
  100969. ** has already accounted for these */
  100970. nSkipEq--;
  100971. }else{
  100972. /* Assume each additional equality match reduces the result
  100973. ** set size by a factor of 10 */
  100974. pc.plan.nRow /= 10;
  100975. }
  100976. }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
  100977. if( nSkipRange ){
  100978. /* Ignore the first nSkipRange range constraints since the index
  100979. ** has already accounted for these */
  100980. nSkipRange--;
  100981. }else{
  100982. /* Assume each additional range constraint reduces the result
  100983. ** set size by a factor of 3. Indexed range constraints reduce
  100984. ** the search space by a larger factor: 4. We make indexed range
  100985. ** more selective intentionally because of the subjective
  100986. ** observation that indexed range constraints really are more
  100987. ** selective in practice, on average. */
  100988. pc.plan.nRow /= 3;
  100989. }
  100990. }else if( (pTerm->eOperator & WO_NOOP)==0 ){
  100991. /* Any other expression lowers the output row count by half */
  100992. pc.plan.nRow /= 2;
  100993. }
  100994. }
  100995. if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
  100996. }
  100997. WHERETRACE((
  100998. " nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
  100999. " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
  101000. " used=0x%llx nOBSat=%d\n",
  101001. pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
  101002. p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
  101003. pc.plan.nOBSat
  101004. ));
  101005. /* If this index is the best we have seen so far, then record this
  101006. ** index and its cost in the p->cost structure.
  101007. */
  101008. if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
  101009. p->cost = pc;
  101010. p->cost.plan.wsFlags &= wsFlagMask;
  101011. p->cost.plan.u.pIdx = pIdx;
  101012. }
  101013. /* If there was an INDEXED BY clause, then only that one index is
  101014. ** considered. */
  101015. if( pSrc->pIndex ) break;
  101016. /* Reset masks for the next index in the loop */
  101017. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  101018. eqTermMask = idxEqTermMask;
  101019. }
  101020. /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
  101021. ** is set, then reverse the order that the index will be scanned
  101022. ** in. This is used for application testing, to help find cases
  101023. ** where application behavior depends on the (undefined) order that
  101024. ** SQLite outputs rows in in the absence of an ORDER BY clause. */
  101025. if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
  101026. p->cost.plan.wsFlags |= WHERE_REVERSE;
  101027. }
  101028. assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
  101029. assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
  101030. assert( pSrc->pIndex==0
  101031. || p->cost.plan.u.pIdx==0
  101032. || p->cost.plan.u.pIdx==pSrc->pIndex
  101033. );
  101034. WHERETRACE((" best index is %s cost=%.1f\n",
  101035. p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
  101036. p->cost.rCost));
  101037. bestOrClauseIndex(p);
  101038. bestAutomaticIndex(p);
  101039. p->cost.plan.wsFlags |= eqTermMask;
  101040. }
  101041. /*
  101042. ** Find the query plan for accessing table pSrc->pTab. Write the
  101043. ** best query plan and its cost into the WhereCost object supplied
  101044. ** as the last parameter. This function may calculate the cost of
  101045. ** both real and virtual table scans.
  101046. **
  101047. ** This function does not take ORDER BY or DISTINCT into account. Nor
  101048. ** does it remember the virtual table query plan. All it does is compute
  101049. ** the cost while determining if an OR optimization is applicable. The
  101050. ** details will be reconsidered later if the optimization is found to be
  101051. ** applicable.
  101052. */
  101053. static void bestIndex(WhereBestIdx *p){
  101054. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101055. if( IsVirtual(p->pSrc->pTab) ){
  101056. sqlite3_index_info *pIdxInfo = 0;
  101057. p->ppIdxInfo = &pIdxInfo;
  101058. bestVirtualIndex(p);
  101059. assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
  101060. if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
  101061. sqlite3_free(pIdxInfo->idxStr);
  101062. }
  101063. sqlite3DbFree(p->pParse->db, pIdxInfo);
  101064. }else
  101065. #endif
  101066. {
  101067. bestBtreeIndex(p);
  101068. }
  101069. }
  101070. /*
  101071. ** Disable a term in the WHERE clause. Except, do not disable the term
  101072. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  101073. ** or USING clause of that join.
  101074. **
  101075. ** Consider the term t2.z='ok' in the following queries:
  101076. **
  101077. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  101078. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  101079. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  101080. **
  101081. ** The t2.z='ok' is disabled in the in (2) because it originates
  101082. ** in the ON clause. The term is disabled in (3) because it is not part
  101083. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  101084. **
  101085. ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
  101086. ** completely satisfied by indices.
  101087. **
  101088. ** Disabling a term causes that term to not be tested in the inner loop
  101089. ** of the join. Disabling is an optimization. When terms are satisfied
  101090. ** by indices, we disable them to prevent redundant tests in the inner
  101091. ** loop. We would get the correct results if nothing were ever disabled,
  101092. ** but joins might run a little slower. The trick is to disable as much
  101093. ** as we can without disabling too much. If we disabled in (1), we'd get
  101094. ** the wrong answer. See ticket #813.
  101095. */
  101096. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  101097. if( pTerm
  101098. && (pTerm->wtFlags & TERM_CODED)==0
  101099. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  101100. ){
  101101. pTerm->wtFlags |= TERM_CODED;
  101102. if( pTerm->iParent>=0 ){
  101103. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  101104. if( (--pOther->nChild)==0 ){
  101105. disableTerm(pLevel, pOther);
  101106. }
  101107. }
  101108. }
  101109. }
  101110. /*
  101111. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  101112. ** to the n registers starting at base.
  101113. **
  101114. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  101115. ** beginning and end of zAff are ignored. If all entries in zAff are
  101116. ** SQLITE_AFF_NONE, then no code gets generated.
  101117. **
  101118. ** This routine makes its own copy of zAff so that the caller is free
  101119. ** to modify zAff after this routine returns.
  101120. */
  101121. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  101122. Vdbe *v = pParse->pVdbe;
  101123. if( zAff==0 ){
  101124. assert( pParse->db->mallocFailed );
  101125. return;
  101126. }
  101127. assert( v!=0 );
  101128. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  101129. ** and end of the affinity string.
  101130. */
  101131. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  101132. n--;
  101133. base++;
  101134. zAff++;
  101135. }
  101136. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  101137. n--;
  101138. }
  101139. /* Code the OP_Affinity opcode if there is anything left to do. */
  101140. if( n>0 ){
  101141. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  101142. sqlite3VdbeChangeP4(v, -1, zAff, n);
  101143. sqlite3ExprCacheAffinityChange(pParse, base, n);
  101144. }
  101145. }
  101146. /*
  101147. ** Generate code for a single equality term of the WHERE clause. An equality
  101148. ** term can be either X=expr or X IN (...). pTerm is the term to be
  101149. ** coded.
  101150. **
  101151. ** The current value for the constraint is left in register iReg.
  101152. **
  101153. ** For a constraint of the form X=expr, the expression is evaluated and its
  101154. ** result is left on the stack. For constraints of the form X IN (...)
  101155. ** this routine sets up a loop that will iterate over all values of X.
  101156. */
  101157. static int codeEqualityTerm(
  101158. Parse *pParse, /* The parsing context */
  101159. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  101160. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  101161. int iEq, /* Index of the equality term within this level */
  101162. int iTarget /* Attempt to leave results in this register */
  101163. ){
  101164. Expr *pX = pTerm->pExpr;
  101165. Vdbe *v = pParse->pVdbe;
  101166. int iReg; /* Register holding results */
  101167. assert( iTarget>0 );
  101168. if( pX->op==TK_EQ ){
  101169. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  101170. }else if( pX->op==TK_ISNULL ){
  101171. iReg = iTarget;
  101172. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  101173. #ifndef SQLITE_OMIT_SUBQUERY
  101174. }else{
  101175. int eType;
  101176. int iTab;
  101177. struct InLoop *pIn;
  101178. u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  101179. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
  101180. && pLevel->plan.u.pIdx->aSortOrder[iEq]
  101181. ){
  101182. testcase( iEq==0 );
  101183. testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
  101184. testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
  101185. testcase( bRev );
  101186. bRev = !bRev;
  101187. }
  101188. assert( pX->op==TK_IN );
  101189. iReg = iTarget;
  101190. eType = sqlite3FindInIndex(pParse, pX, 0);
  101191. if( eType==IN_INDEX_INDEX_DESC ){
  101192. testcase( bRev );
  101193. bRev = !bRev;
  101194. }
  101195. iTab = pX->iTable;
  101196. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  101197. assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
  101198. if( pLevel->u.in.nIn==0 ){
  101199. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  101200. }
  101201. pLevel->u.in.nIn++;
  101202. pLevel->u.in.aInLoop =
  101203. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  101204. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  101205. pIn = pLevel->u.in.aInLoop;
  101206. if( pIn ){
  101207. pIn += pLevel->u.in.nIn - 1;
  101208. pIn->iCur = iTab;
  101209. if( eType==IN_INDEX_ROWID ){
  101210. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  101211. }else{
  101212. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  101213. }
  101214. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  101215. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  101216. }else{
  101217. pLevel->u.in.nIn = 0;
  101218. }
  101219. #endif
  101220. }
  101221. disableTerm(pLevel, pTerm);
  101222. return iReg;
  101223. }
  101224. /*
  101225. ** Generate code that will evaluate all == and IN constraints for an
  101226. ** index.
  101227. **
  101228. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  101229. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  101230. ** The index has as many as three equality constraints, but in this
  101231. ** example, the third "c" value is an inequality. So only two
  101232. ** constraints are coded. This routine will generate code to evaluate
  101233. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  101234. ** in consecutive registers and the index of the first register is returned.
  101235. **
  101236. ** In the example above nEq==2. But this subroutine works for any value
  101237. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  101238. ** The only thing it does is allocate the pLevel->iMem memory cell and
  101239. ** compute the affinity string.
  101240. **
  101241. ** This routine always allocates at least one memory cell and returns
  101242. ** the index of that memory cell. The code that
  101243. ** calls this routine will use that memory cell to store the termination
  101244. ** key value of the loop. If one or more IN operators appear, then
  101245. ** this routine allocates an additional nEq memory cells for internal
  101246. ** use.
  101247. **
  101248. ** Before returning, *pzAff is set to point to a buffer containing a
  101249. ** copy of the column affinity string of the index allocated using
  101250. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  101251. ** with equality constraints that use NONE affinity are set to
  101252. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  101253. **
  101254. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  101255. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  101256. **
  101257. ** In the example above, the index on t1(a) has TEXT affinity. But since
  101258. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  101259. ** no conversion should be attempted before using a t2.b value as part of
  101260. ** a key to search the index. Hence the first byte in the returned affinity
  101261. ** string in this example would be set to SQLITE_AFF_NONE.
  101262. */
  101263. static int codeAllEqualityTerms(
  101264. Parse *pParse, /* Parsing context */
  101265. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  101266. WhereClause *pWC, /* The WHERE clause */
  101267. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  101268. int nExtraReg, /* Number of extra registers to allocate */
  101269. char **pzAff /* OUT: Set to point to affinity string */
  101270. ){
  101271. int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
  101272. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  101273. Index *pIdx; /* The index being used for this loop */
  101274. int iCur = pLevel->iTabCur; /* The cursor of the table */
  101275. WhereTerm *pTerm; /* A single constraint term */
  101276. int j; /* Loop counter */
  101277. int regBase; /* Base register */
  101278. int nReg; /* Number of registers to allocate */
  101279. char *zAff; /* Affinity string to return */
  101280. /* This module is only called on query plans that use an index. */
  101281. assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  101282. pIdx = pLevel->plan.u.pIdx;
  101283. /* Figure out how many memory cells we will need then allocate them.
  101284. */
  101285. regBase = pParse->nMem + 1;
  101286. nReg = pLevel->plan.nEq + nExtraReg;
  101287. pParse->nMem += nReg;
  101288. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  101289. if( !zAff ){
  101290. pParse->db->mallocFailed = 1;
  101291. }
  101292. /* Evaluate the equality constraints
  101293. */
  101294. assert( pIdx->nColumn>=nEq );
  101295. for(j=0; j<nEq; j++){
  101296. int r1;
  101297. int k = pIdx->aiColumn[j];
  101298. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
  101299. if( pTerm==0 ) break;
  101300. /* The following true for indices with redundant columns.
  101301. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  101302. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  101303. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101304. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
  101305. if( r1!=regBase+j ){
  101306. if( nReg==1 ){
  101307. sqlite3ReleaseTempReg(pParse, regBase);
  101308. regBase = r1;
  101309. }else{
  101310. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  101311. }
  101312. }
  101313. testcase( pTerm->eOperator & WO_ISNULL );
  101314. testcase( pTerm->eOperator & WO_IN );
  101315. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  101316. Expr *pRight = pTerm->pExpr->pRight;
  101317. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  101318. if( zAff ){
  101319. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  101320. zAff[j] = SQLITE_AFF_NONE;
  101321. }
  101322. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  101323. zAff[j] = SQLITE_AFF_NONE;
  101324. }
  101325. }
  101326. }
  101327. }
  101328. *pzAff = zAff;
  101329. return regBase;
  101330. }
  101331. #ifndef SQLITE_OMIT_EXPLAIN
  101332. /*
  101333. ** This routine is a helper for explainIndexRange() below
  101334. **
  101335. ** pStr holds the text of an expression that we are building up one term
  101336. ** at a time. This routine adds a new term to the end of the expression.
  101337. ** Terms are separated by AND so add the "AND" text for second and subsequent
  101338. ** terms only.
  101339. */
  101340. static void explainAppendTerm(
  101341. StrAccum *pStr, /* The text expression being built */
  101342. int iTerm, /* Index of this term. First is zero */
  101343. const char *zColumn, /* Name of the column */
  101344. const char *zOp /* Name of the operator */
  101345. ){
  101346. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  101347. sqlite3StrAccumAppend(pStr, zColumn, -1);
  101348. sqlite3StrAccumAppend(pStr, zOp, 1);
  101349. sqlite3StrAccumAppend(pStr, "?", 1);
  101350. }
  101351. /*
  101352. ** Argument pLevel describes a strategy for scanning table pTab. This
  101353. ** function returns a pointer to a string buffer containing a description
  101354. ** of the subset of table rows scanned by the strategy in the form of an
  101355. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  101356. **
  101357. ** For example, if the query:
  101358. **
  101359. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  101360. **
  101361. ** is run and there is an index on (a, b), then this function returns a
  101362. ** string similar to:
  101363. **
  101364. ** "a=? AND b>?"
  101365. **
  101366. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  101367. ** It is the responsibility of the caller to free the buffer when it is
  101368. ** no longer required.
  101369. */
  101370. static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
  101371. WherePlan *pPlan = &pLevel->plan;
  101372. Index *pIndex = pPlan->u.pIdx;
  101373. int nEq = pPlan->nEq;
  101374. int i, j;
  101375. Column *aCol = pTab->aCol;
  101376. int *aiColumn = pIndex->aiColumn;
  101377. StrAccum txt;
  101378. if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  101379. return 0;
  101380. }
  101381. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  101382. txt.db = db;
  101383. sqlite3StrAccumAppend(&txt, " (", 2);
  101384. for(i=0; i<nEq; i++){
  101385. explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
  101386. }
  101387. j = i;
  101388. if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
  101389. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  101390. explainAppendTerm(&txt, i++, z, ">");
  101391. }
  101392. if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
  101393. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  101394. explainAppendTerm(&txt, i, z, "<");
  101395. }
  101396. sqlite3StrAccumAppend(&txt, ")", 1);
  101397. return sqlite3StrAccumFinish(&txt);
  101398. }
  101399. /*
  101400. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  101401. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  101402. ** record is added to the output to describe the table scan strategy in
  101403. ** pLevel.
  101404. */
  101405. static void explainOneScan(
  101406. Parse *pParse, /* Parse context */
  101407. SrcList *pTabList, /* Table list this loop refers to */
  101408. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  101409. int iLevel, /* Value for "level" column of output */
  101410. int iFrom, /* Value for "from" column of output */
  101411. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  101412. ){
  101413. if( pParse->explain==2 ){
  101414. u32 flags = pLevel->plan.wsFlags;
  101415. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  101416. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  101417. sqlite3 *db = pParse->db; /* Database handle */
  101418. char *zMsg; /* Text to add to EQP output */
  101419. sqlite3_int64 nRow; /* Expected number of rows visited by scan */
  101420. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  101421. int isSearch; /* True for a SEARCH. False for SCAN. */
  101422. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  101423. isSearch = (pLevel->plan.nEq>0)
  101424. || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  101425. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  101426. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  101427. if( pItem->pSelect ){
  101428. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  101429. }else{
  101430. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  101431. }
  101432. if( pItem->zAlias ){
  101433. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  101434. }
  101435. if( (flags & WHERE_INDEXED)!=0 ){
  101436. char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
  101437. zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
  101438. ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
  101439. ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
  101440. ((flags & WHERE_TEMP_INDEX)?"":" "),
  101441. ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
  101442. zWhere
  101443. );
  101444. sqlite3DbFree(db, zWhere);
  101445. }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  101446. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  101447. if( flags&WHERE_ROWID_EQ ){
  101448. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  101449. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  101450. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  101451. }else if( flags&WHERE_BTM_LIMIT ){
  101452. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  101453. }else if( flags&WHERE_TOP_LIMIT ){
  101454. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  101455. }
  101456. }
  101457. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101458. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  101459. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  101460. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  101461. pVtabIdx->idxNum, pVtabIdx->idxStr);
  101462. }
  101463. #endif
  101464. if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
  101465. testcase( wctrlFlags & WHERE_ORDERBY_MIN );
  101466. nRow = 1;
  101467. }else{
  101468. nRow = (sqlite3_int64)pLevel->plan.nRow;
  101469. }
  101470. zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
  101471. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  101472. }
  101473. }
  101474. #else
  101475. # define explainOneScan(u,v,w,x,y,z)
  101476. #endif /* SQLITE_OMIT_EXPLAIN */
  101477. /*
  101478. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  101479. ** implementation described by pWInfo.
  101480. */
  101481. static Bitmask codeOneLoopStart(
  101482. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  101483. int iLevel, /* Which level of pWInfo->a[] should be coded */
  101484. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  101485. Bitmask notReady /* Which tables are currently available */
  101486. ){
  101487. int j, k; /* Loop counters */
  101488. int iCur; /* The VDBE cursor for the table */
  101489. int addrNxt; /* Where to jump to continue with the next IN case */
  101490. int omitTable; /* True if we use the index only */
  101491. int bRev; /* True if we need to scan in reverse order */
  101492. WhereLevel *pLevel; /* The where level to be coded */
  101493. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  101494. WhereTerm *pTerm; /* A WHERE clause term */
  101495. Parse *pParse; /* Parsing context */
  101496. Vdbe *v; /* The prepared stmt under constructions */
  101497. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  101498. int addrBrk; /* Jump here to break out of the loop */
  101499. int addrCont; /* Jump here to continue with next cycle */
  101500. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  101501. int iReleaseReg = 0; /* Temp register to free before returning */
  101502. Bitmask newNotReady; /* Return value */
  101503. pParse = pWInfo->pParse;
  101504. v = pParse->pVdbe;
  101505. pWC = pWInfo->pWC;
  101506. pLevel = &pWInfo->a[iLevel];
  101507. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  101508. iCur = pTabItem->iCursor;
  101509. bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  101510. omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
  101511. && (wctrlFlags & WHERE_FORCE_TABLE)==0;
  101512. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  101513. /* Create labels for the "break" and "continue" instructions
  101514. ** for the current loop. Jump to addrBrk to break out of a loop.
  101515. ** Jump to cont to go immediately to the next iteration of the
  101516. ** loop.
  101517. **
  101518. ** When there is an IN operator, we also have a "addrNxt" label that
  101519. ** means to continue with the next IN value combination. When
  101520. ** there are no IN operators in the constraints, the "addrNxt" label
  101521. ** is the same as "addrBrk".
  101522. */
  101523. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  101524. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  101525. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  101526. ** initialize a memory cell that records if this table matches any
  101527. ** row of the left table of the join.
  101528. */
  101529. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  101530. pLevel->iLeftJoin = ++pParse->nMem;
  101531. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  101532. VdbeComment((v, "init LEFT JOIN no-match flag"));
  101533. }
  101534. /* Special case of a FROM clause subquery implemented as a co-routine */
  101535. if( pTabItem->viaCoroutine ){
  101536. int regYield = pTabItem->regReturn;
  101537. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  101538. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  101539. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  101540. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  101541. pLevel->op = OP_Goto;
  101542. }else
  101543. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101544. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  101545. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  101546. ** to access the data.
  101547. */
  101548. int iReg; /* P3 Value for OP_VFilter */
  101549. int addrNotFound;
  101550. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  101551. int nConstraint = pVtabIdx->nConstraint;
  101552. struct sqlite3_index_constraint_usage *aUsage =
  101553. pVtabIdx->aConstraintUsage;
  101554. const struct sqlite3_index_constraint *aConstraint =
  101555. pVtabIdx->aConstraint;
  101556. sqlite3ExprCachePush(pParse);
  101557. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  101558. addrNotFound = pLevel->addrBrk;
  101559. for(j=1; j<=nConstraint; j++){
  101560. for(k=0; k<nConstraint; k++){
  101561. if( aUsage[k].argvIndex==j ){
  101562. int iTarget = iReg+j+1;
  101563. pTerm = &pWC->a[aConstraint[k].iTermOffset];
  101564. if( pTerm->eOperator & WO_IN ){
  101565. codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
  101566. addrNotFound = pLevel->addrNxt;
  101567. }else{
  101568. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  101569. }
  101570. break;
  101571. }
  101572. }
  101573. if( k==nConstraint ) break;
  101574. }
  101575. sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
  101576. sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
  101577. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
  101578. pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
  101579. pVtabIdx->needToFreeIdxStr = 0;
  101580. for(j=0; j<nConstraint; j++){
  101581. if( aUsage[j].omit ){
  101582. int iTerm = aConstraint[j].iTermOffset;
  101583. disableTerm(pLevel, &pWC->a[iTerm]);
  101584. }
  101585. }
  101586. pLevel->op = OP_VNext;
  101587. pLevel->p1 = iCur;
  101588. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  101589. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  101590. sqlite3ExprCachePop(pParse, 1);
  101591. }else
  101592. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  101593. if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
  101594. /* Case 1: We can directly reference a single row using an
  101595. ** equality comparison against the ROWID field. Or
  101596. ** we reference multiple rows using a "rowid IN (...)"
  101597. ** construct.
  101598. */
  101599. iReleaseReg = sqlite3GetTempReg(pParse);
  101600. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  101601. assert( pTerm!=0 );
  101602. assert( pTerm->pExpr!=0 );
  101603. assert( omitTable==0 );
  101604. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101605. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
  101606. addrNxt = pLevel->addrNxt;
  101607. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  101608. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  101609. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  101610. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  101611. VdbeComment((v, "pk"));
  101612. pLevel->op = OP_Noop;
  101613. }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
  101614. /* Case 2: We have an inequality comparison against the ROWID field.
  101615. */
  101616. int testOp = OP_Noop;
  101617. int start;
  101618. int memEndValue = 0;
  101619. WhereTerm *pStart, *pEnd;
  101620. assert( omitTable==0 );
  101621. pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
  101622. pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
  101623. if( bRev ){
  101624. pTerm = pStart;
  101625. pStart = pEnd;
  101626. pEnd = pTerm;
  101627. }
  101628. if( pStart ){
  101629. Expr *pX; /* The expression that defines the start bound */
  101630. int r1, rTemp; /* Registers for holding the start boundary */
  101631. /* The following constant maps TK_xx codes into corresponding
  101632. ** seek opcodes. It depends on a particular ordering of TK_xx
  101633. */
  101634. const u8 aMoveOp[] = {
  101635. /* TK_GT */ OP_SeekGt,
  101636. /* TK_LE */ OP_SeekLe,
  101637. /* TK_LT */ OP_SeekLt,
  101638. /* TK_GE */ OP_SeekGe
  101639. };
  101640. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  101641. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  101642. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  101643. testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101644. pX = pStart->pExpr;
  101645. assert( pX!=0 );
  101646. assert( pStart->leftCursor==iCur );
  101647. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  101648. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  101649. VdbeComment((v, "pk"));
  101650. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  101651. sqlite3ReleaseTempReg(pParse, rTemp);
  101652. disableTerm(pLevel, pStart);
  101653. }else{
  101654. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  101655. }
  101656. if( pEnd ){
  101657. Expr *pX;
  101658. pX = pEnd->pExpr;
  101659. assert( pX!=0 );
  101660. assert( pEnd->leftCursor==iCur );
  101661. testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101662. memEndValue = ++pParse->nMem;
  101663. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  101664. if( pX->op==TK_LT || pX->op==TK_GT ){
  101665. testOp = bRev ? OP_Le : OP_Ge;
  101666. }else{
  101667. testOp = bRev ? OP_Lt : OP_Gt;
  101668. }
  101669. disableTerm(pLevel, pEnd);
  101670. }
  101671. start = sqlite3VdbeCurrentAddr(v);
  101672. pLevel->op = bRev ? OP_Prev : OP_Next;
  101673. pLevel->p1 = iCur;
  101674. pLevel->p2 = start;
  101675. if( pStart==0 && pEnd==0 ){
  101676. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  101677. }else{
  101678. assert( pLevel->p5==0 );
  101679. }
  101680. if( testOp!=OP_Noop ){
  101681. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  101682. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  101683. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  101684. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  101685. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  101686. }
  101687. }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
  101688. /* Case 3: A scan using an index.
  101689. **
  101690. ** The WHERE clause may contain zero or more equality
  101691. ** terms ("==" or "IN" operators) that refer to the N
  101692. ** left-most columns of the index. It may also contain
  101693. ** inequality constraints (>, <, >= or <=) on the indexed
  101694. ** column that immediately follows the N equalities. Only
  101695. ** the right-most column can be an inequality - the rest must
  101696. ** use the "==" and "IN" operators. For example, if the
  101697. ** index is on (x,y,z), then the following clauses are all
  101698. ** optimized:
  101699. **
  101700. ** x=5
  101701. ** x=5 AND y=10
  101702. ** x=5 AND y<10
  101703. ** x=5 AND y>5 AND y<10
  101704. ** x=5 AND y=5 AND z<=10
  101705. **
  101706. ** The z<10 term of the following cannot be used, only
  101707. ** the x=5 term:
  101708. **
  101709. ** x=5 AND z<10
  101710. **
  101711. ** N may be zero if there are inequality constraints.
  101712. ** If there are no inequality constraints, then N is at
  101713. ** least one.
  101714. **
  101715. ** This case is also used when there are no WHERE clause
  101716. ** constraints but an index is selected anyway, in order
  101717. ** to force the output order to conform to an ORDER BY.
  101718. */
  101719. static const u8 aStartOp[] = {
  101720. 0,
  101721. 0,
  101722. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  101723. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  101724. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  101725. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  101726. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  101727. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  101728. };
  101729. static const u8 aEndOp[] = {
  101730. OP_Noop, /* 0: (!end_constraints) */
  101731. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  101732. OP_IdxLT /* 2: (end_constraints && bRev) */
  101733. };
  101734. int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
  101735. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  101736. int regBase; /* Base register holding constraint values */
  101737. int r1; /* Temp register */
  101738. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  101739. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  101740. int startEq; /* True if range start uses ==, >= or <= */
  101741. int endEq; /* True if range end uses ==, >= or <= */
  101742. int start_constraints; /* Start of range is constrained */
  101743. int nConstraint; /* Number of constraint terms */
  101744. Index *pIdx; /* The index we will be using */
  101745. int iIdxCur; /* The VDBE cursor for the index */
  101746. int nExtraReg = 0; /* Number of extra registers needed */
  101747. int op; /* Instruction opcode */
  101748. char *zStartAff; /* Affinity for start of range constraint */
  101749. char *zEndAff; /* Affinity for end of range constraint */
  101750. pIdx = pLevel->plan.u.pIdx;
  101751. iIdxCur = pLevel->iIdxCur;
  101752. k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
  101753. /* If this loop satisfies a sort order (pOrderBy) request that
  101754. ** was passed to this function to implement a "SELECT min(x) ..."
  101755. ** query, then the caller will only allow the loop to run for
  101756. ** a single iteration. This means that the first row returned
  101757. ** should not have a NULL value stored in 'x'. If column 'x' is
  101758. ** the first one after the nEq equality constraints in the index,
  101759. ** this requires some special handling.
  101760. */
  101761. if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
  101762. && (pLevel->plan.wsFlags&WHERE_ORDERED)
  101763. && (pIdx->nColumn>nEq)
  101764. ){
  101765. /* assert( pOrderBy->nExpr==1 ); */
  101766. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  101767. isMinQuery = 1;
  101768. nExtraReg = 1;
  101769. }
  101770. /* Find any inequality constraint terms for the start and end
  101771. ** of the range.
  101772. */
  101773. if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
  101774. pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
  101775. nExtraReg = 1;
  101776. }
  101777. if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
  101778. pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
  101779. nExtraReg = 1;
  101780. }
  101781. /* Generate code to evaluate all constraint terms using == or IN
  101782. ** and store the values of those terms in an array of registers
  101783. ** starting at regBase.
  101784. */
  101785. regBase = codeAllEqualityTerms(
  101786. pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
  101787. );
  101788. zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
  101789. addrNxt = pLevel->addrNxt;
  101790. /* If we are doing a reverse order scan on an ascending index, or
  101791. ** a forward order scan on a descending index, interchange the
  101792. ** start and end terms (pRangeStart and pRangeEnd).
  101793. */
  101794. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  101795. || (bRev && pIdx->nColumn==nEq)
  101796. ){
  101797. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  101798. }
  101799. testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
  101800. testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
  101801. testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
  101802. testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
  101803. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  101804. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  101805. start_constraints = pRangeStart || nEq>0;
  101806. /* Seek the index cursor to the start of the range. */
  101807. nConstraint = nEq;
  101808. if( pRangeStart ){
  101809. Expr *pRight = pRangeStart->pExpr->pRight;
  101810. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  101811. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  101812. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  101813. }
  101814. if( zStartAff ){
  101815. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  101816. /* Since the comparison is to be performed with no conversions
  101817. ** applied to the operands, set the affinity to apply to pRight to
  101818. ** SQLITE_AFF_NONE. */
  101819. zStartAff[nEq] = SQLITE_AFF_NONE;
  101820. }
  101821. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  101822. zStartAff[nEq] = SQLITE_AFF_NONE;
  101823. }
  101824. }
  101825. nConstraint++;
  101826. testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101827. }else if( isMinQuery ){
  101828. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  101829. nConstraint++;
  101830. startEq = 0;
  101831. start_constraints = 1;
  101832. }
  101833. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  101834. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  101835. assert( op!=0 );
  101836. testcase( op==OP_Rewind );
  101837. testcase( op==OP_Last );
  101838. testcase( op==OP_SeekGt );
  101839. testcase( op==OP_SeekGe );
  101840. testcase( op==OP_SeekLe );
  101841. testcase( op==OP_SeekLt );
  101842. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  101843. /* Load the value for the inequality constraint at the end of the
  101844. ** range (if any).
  101845. */
  101846. nConstraint = nEq;
  101847. if( pRangeEnd ){
  101848. Expr *pRight = pRangeEnd->pExpr->pRight;
  101849. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  101850. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  101851. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  101852. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  101853. }
  101854. if( zEndAff ){
  101855. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  101856. /* Since the comparison is to be performed with no conversions
  101857. ** applied to the operands, set the affinity to apply to pRight to
  101858. ** SQLITE_AFF_NONE. */
  101859. zEndAff[nEq] = SQLITE_AFF_NONE;
  101860. }
  101861. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  101862. zEndAff[nEq] = SQLITE_AFF_NONE;
  101863. }
  101864. }
  101865. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  101866. nConstraint++;
  101867. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  101868. }
  101869. sqlite3DbFree(pParse->db, zStartAff);
  101870. sqlite3DbFree(pParse->db, zEndAff);
  101871. /* Top of the loop body */
  101872. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  101873. /* Check if the index cursor is past the end of the range. */
  101874. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  101875. testcase( op==OP_Noop );
  101876. testcase( op==OP_IdxGE );
  101877. testcase( op==OP_IdxLT );
  101878. if( op!=OP_Noop ){
  101879. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  101880. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  101881. }
  101882. /* If there are inequality constraints, check that the value
  101883. ** of the table column that the inequality contrains is not NULL.
  101884. ** If it is, jump to the next iteration of the loop.
  101885. */
  101886. r1 = sqlite3GetTempReg(pParse);
  101887. testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
  101888. testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
  101889. if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  101890. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  101891. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  101892. }
  101893. sqlite3ReleaseTempReg(pParse, r1);
  101894. /* Seek the table cursor, if required */
  101895. disableTerm(pLevel, pRangeStart);
  101896. disableTerm(pLevel, pRangeEnd);
  101897. if( !omitTable ){
  101898. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  101899. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  101900. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  101901. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  101902. }
  101903. /* Record the instruction used to terminate the loop. Disable
  101904. ** WHERE clause terms made redundant by the index range scan.
  101905. */
  101906. if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
  101907. pLevel->op = OP_Noop;
  101908. }else if( bRev ){
  101909. pLevel->op = OP_Prev;
  101910. }else{
  101911. pLevel->op = OP_Next;
  101912. }
  101913. pLevel->p1 = iIdxCur;
  101914. if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
  101915. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  101916. }else{
  101917. assert( pLevel->p5==0 );
  101918. }
  101919. }else
  101920. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  101921. if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  101922. /* Case 4: Two or more separately indexed terms connected by OR
  101923. **
  101924. ** Example:
  101925. **
  101926. ** CREATE TABLE t1(a,b,c,d);
  101927. ** CREATE INDEX i1 ON t1(a);
  101928. ** CREATE INDEX i2 ON t1(b);
  101929. ** CREATE INDEX i3 ON t1(c);
  101930. **
  101931. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  101932. **
  101933. ** In the example, there are three indexed terms connected by OR.
  101934. ** The top of the loop looks like this:
  101935. **
  101936. ** Null 1 # Zero the rowset in reg 1
  101937. **
  101938. ** Then, for each indexed term, the following. The arguments to
  101939. ** RowSetTest are such that the rowid of the current row is inserted
  101940. ** into the RowSet. If it is already present, control skips the
  101941. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  101942. **
  101943. ** sqlite3WhereBegin(<term>)
  101944. ** RowSetTest # Insert rowid into rowset
  101945. ** Gosub 2 A
  101946. ** sqlite3WhereEnd()
  101947. **
  101948. ** Following the above, code to terminate the loop. Label A, the target
  101949. ** of the Gosub above, jumps to the instruction right after the Goto.
  101950. **
  101951. ** Null 1 # Zero the rowset in reg 1
  101952. ** Goto B # The loop is finished.
  101953. **
  101954. ** A: <loop body> # Return data, whatever.
  101955. **
  101956. ** Return 2 # Jump back to the Gosub
  101957. **
  101958. ** B: <after the loop>
  101959. **
  101960. */
  101961. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  101962. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  101963. Index *pCov = 0; /* Potential covering index (or NULL) */
  101964. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  101965. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  101966. int regRowset = 0; /* Register for RowSet object */
  101967. int regRowid = 0; /* Register holding rowid */
  101968. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  101969. int iRetInit; /* Address of regReturn init */
  101970. int untestedTerms = 0; /* Some terms not completely tested */
  101971. int ii; /* Loop counter */
  101972. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  101973. pTerm = pLevel->plan.u.pTerm;
  101974. assert( pTerm!=0 );
  101975. assert( pTerm->eOperator & WO_OR );
  101976. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  101977. pOrWc = &pTerm->u.pOrInfo->wc;
  101978. pLevel->op = OP_Return;
  101979. pLevel->p1 = regReturn;
  101980. /* Set up a new SrcList in pOrTab containing the table being scanned
  101981. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  101982. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  101983. */
  101984. if( pWInfo->nLevel>1 ){
  101985. int nNotReady; /* The number of notReady tables */
  101986. struct SrcList_item *origSrc; /* Original list of tables */
  101987. nNotReady = pWInfo->nLevel - iLevel - 1;
  101988. pOrTab = sqlite3StackAllocRaw(pParse->db,
  101989. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  101990. if( pOrTab==0 ) return notReady;
  101991. pOrTab->nAlloc = (i16)(nNotReady + 1);
  101992. pOrTab->nSrc = pOrTab->nAlloc;
  101993. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  101994. origSrc = pWInfo->pTabList->a;
  101995. for(k=1; k<=nNotReady; k++){
  101996. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  101997. }
  101998. }else{
  101999. pOrTab = pWInfo->pTabList;
  102000. }
  102001. /* Initialize the rowset register to contain NULL. An SQL NULL is
  102002. ** equivalent to an empty rowset.
  102003. **
  102004. ** Also initialize regReturn to contain the address of the instruction
  102005. ** immediately following the OP_Return at the bottom of the loop. This
  102006. ** is required in a few obscure LEFT JOIN cases where control jumps
  102007. ** over the top of the loop into the body of it. In this case the
  102008. ** correct response for the end-of-loop code (the OP_Return) is to
  102009. ** fall through to the next instruction, just as an OP_Next does if
  102010. ** called on an uninitialized cursor.
  102011. */
  102012. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  102013. regRowset = ++pParse->nMem;
  102014. regRowid = ++pParse->nMem;
  102015. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  102016. }
  102017. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  102018. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  102019. ** Then for every term xN, evaluate as the subexpression: xN AND z
  102020. ** That way, terms in y that are factored into the disjunction will
  102021. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  102022. **
  102023. ** Actually, each subexpression is converted to "xN AND w" where w is
  102024. ** the "interesting" terms of z - terms that did not originate in the
  102025. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  102026. ** indices.
  102027. **
  102028. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  102029. ** is not contained in the ON clause of a LEFT JOIN.
  102030. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  102031. */
  102032. if( pWC->nTerm>1 ){
  102033. int iTerm;
  102034. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  102035. Expr *pExpr = pWC->a[iTerm].pExpr;
  102036. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  102037. if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
  102038. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  102039. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  102040. pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
  102041. }
  102042. if( pAndExpr ){
  102043. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  102044. }
  102045. }
  102046. for(ii=0; ii<pOrWc->nTerm; ii++){
  102047. WhereTerm *pOrTerm = &pOrWc->a[ii];
  102048. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  102049. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  102050. Expr *pOrExpr = pOrTerm->pExpr;
  102051. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  102052. pAndExpr->pLeft = pOrExpr;
  102053. pOrExpr = pAndExpr;
  102054. }
  102055. /* Loop through table entries that match term pOrTerm. */
  102056. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  102057. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  102058. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  102059. assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
  102060. if( pSubWInfo ){
  102061. WhereLevel *pLvl;
  102062. explainOneScan(
  102063. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  102064. );
  102065. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  102066. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  102067. int r;
  102068. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  102069. regRowid, 0);
  102070. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  102071. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  102072. }
  102073. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  102074. /* The pSubWInfo->untestedTerms flag means that this OR term
  102075. ** contained one or more AND term from a notReady table. The
  102076. ** terms from the notReady table could not be tested and will
  102077. ** need to be tested later.
  102078. */
  102079. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  102080. /* If all of the OR-connected terms are optimized using the same
  102081. ** index, and the index is opened using the same cursor number
  102082. ** by each call to sqlite3WhereBegin() made by this loop, it may
  102083. ** be possible to use that index as a covering index.
  102084. **
  102085. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  102086. ** uses an index, and this is either the first OR-connected term
  102087. ** processed or the index is the same as that used by all previous
  102088. ** terms, set pCov to the candidate covering index. Otherwise, set
  102089. ** pCov to NULL to indicate that no candidate covering index will
  102090. ** be available.
  102091. */
  102092. pLvl = &pSubWInfo->a[0];
  102093. if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
  102094. && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
  102095. && (ii==0 || pLvl->plan.u.pIdx==pCov)
  102096. ){
  102097. assert( pLvl->iIdxCur==iCovCur );
  102098. pCov = pLvl->plan.u.pIdx;
  102099. }else{
  102100. pCov = 0;
  102101. }
  102102. /* Finish the loop through table entries that match term pOrTerm. */
  102103. sqlite3WhereEnd(pSubWInfo);
  102104. }
  102105. }
  102106. }
  102107. pLevel->u.pCovidx = pCov;
  102108. if( pCov ) pLevel->iIdxCur = iCovCur;
  102109. if( pAndExpr ){
  102110. pAndExpr->pLeft = 0;
  102111. sqlite3ExprDelete(pParse->db, pAndExpr);
  102112. }
  102113. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  102114. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  102115. sqlite3VdbeResolveLabel(v, iLoopBody);
  102116. if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
  102117. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  102118. }else
  102119. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  102120. {
  102121. /* Case 5: There is no usable index. We must do a complete
  102122. ** scan of the entire table.
  102123. */
  102124. static const u8 aStep[] = { OP_Next, OP_Prev };
  102125. static const u8 aStart[] = { OP_Rewind, OP_Last };
  102126. assert( bRev==0 || bRev==1 );
  102127. assert( omitTable==0 );
  102128. pLevel->op = aStep[bRev];
  102129. pLevel->p1 = iCur;
  102130. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  102131. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  102132. }
  102133. newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
  102134. /* Insert code to test every subexpression that can be completely
  102135. ** computed using the current set of tables.
  102136. **
  102137. ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
  102138. ** the use of indices become tests that are evaluated against each row of
  102139. ** the relevant input tables.
  102140. */
  102141. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  102142. Expr *pE;
  102143. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  102144. testcase( pTerm->wtFlags & TERM_CODED );
  102145. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  102146. if( (pTerm->prereqAll & newNotReady)!=0 ){
  102147. testcase( pWInfo->untestedTerms==0
  102148. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  102149. pWInfo->untestedTerms = 1;
  102150. continue;
  102151. }
  102152. pE = pTerm->pExpr;
  102153. assert( pE!=0 );
  102154. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  102155. continue;
  102156. }
  102157. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  102158. pTerm->wtFlags |= TERM_CODED;
  102159. }
  102160. /* Insert code to test for implied constraints based on transitivity
  102161. ** of the "==" operator.
  102162. **
  102163. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  102164. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  102165. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  102166. ** the implied "t1.a=123" constraint.
  102167. */
  102168. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  102169. Expr *pE;
  102170. WhereTerm *pAlt;
  102171. Expr sEq;
  102172. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  102173. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  102174. if( pTerm->leftCursor!=iCur ) continue;
  102175. pE = pTerm->pExpr;
  102176. assert( !ExprHasProperty(pE, EP_FromJoin) );
  102177. assert( (pTerm->prereqRight & newNotReady)!=0 );
  102178. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  102179. if( pAlt==0 ) continue;
  102180. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  102181. VdbeNoopComment((v, "begin transitive constraint"));
  102182. sEq = *pAlt->pExpr;
  102183. sEq.pLeft = pE->pLeft;
  102184. sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
  102185. }
  102186. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  102187. ** at least one row of the right table has matched the left table.
  102188. */
  102189. if( pLevel->iLeftJoin ){
  102190. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  102191. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  102192. VdbeComment((v, "record LEFT JOIN hit"));
  102193. sqlite3ExprCacheClear(pParse);
  102194. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  102195. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  102196. testcase( pTerm->wtFlags & TERM_CODED );
  102197. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  102198. if( (pTerm->prereqAll & newNotReady)!=0 ){
  102199. assert( pWInfo->untestedTerms );
  102200. continue;
  102201. }
  102202. assert( pTerm->pExpr );
  102203. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  102204. pTerm->wtFlags |= TERM_CODED;
  102205. }
  102206. }
  102207. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  102208. return newNotReady;
  102209. }
  102210. #if defined(SQLITE_TEST)
  102211. /*
  102212. ** The following variable holds a text description of query plan generated
  102213. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  102214. ** overwrites the previous. This information is used for testing and
  102215. ** analysis only.
  102216. */
  102217. SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  102218. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  102219. #endif /* SQLITE_TEST */
  102220. /*
  102221. ** Free a WhereInfo structure
  102222. */
  102223. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  102224. if( ALWAYS(pWInfo) ){
  102225. int i;
  102226. for(i=0; i<pWInfo->nLevel; i++){
  102227. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  102228. if( pInfo ){
  102229. /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
  102230. if( pInfo->needToFreeIdxStr ){
  102231. sqlite3_free(pInfo->idxStr);
  102232. }
  102233. sqlite3DbFree(db, pInfo);
  102234. }
  102235. if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
  102236. Index *pIdx = pWInfo->a[i].plan.u.pIdx;
  102237. if( pIdx ){
  102238. sqlite3DbFree(db, pIdx->zColAff);
  102239. sqlite3DbFree(db, pIdx);
  102240. }
  102241. }
  102242. }
  102243. whereClauseClear(pWInfo->pWC);
  102244. sqlite3DbFree(db, pWInfo);
  102245. }
  102246. }
  102247. /*
  102248. ** Generate the beginning of the loop used for WHERE clause processing.
  102249. ** The return value is a pointer to an opaque structure that contains
  102250. ** information needed to terminate the loop. Later, the calling routine
  102251. ** should invoke sqlite3WhereEnd() with the return value of this function
  102252. ** in order to complete the WHERE clause processing.
  102253. **
  102254. ** If an error occurs, this routine returns NULL.
  102255. **
  102256. ** The basic idea is to do a nested loop, one loop for each table in
  102257. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  102258. ** same as a SELECT with only a single table in the FROM clause.) For
  102259. ** example, if the SQL is this:
  102260. **
  102261. ** SELECT * FROM t1, t2, t3 WHERE ...;
  102262. **
  102263. ** Then the code generated is conceptually like the following:
  102264. **
  102265. ** foreach row1 in t1 do \ Code generated
  102266. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  102267. ** foreach row3 in t3 do /
  102268. ** ...
  102269. ** end \ Code generated
  102270. ** end |-- by sqlite3WhereEnd()
  102271. ** end /
  102272. **
  102273. ** Note that the loops might not be nested in the order in which they
  102274. ** appear in the FROM clause if a different order is better able to make
  102275. ** use of indices. Note also that when the IN operator appears in
  102276. ** the WHERE clause, it might result in additional nested loops for
  102277. ** scanning through all values on the right-hand side of the IN.
  102278. **
  102279. ** There are Btree cursors associated with each table. t1 uses cursor
  102280. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  102281. ** And so forth. This routine generates code to open those VDBE cursors
  102282. ** and sqlite3WhereEnd() generates the code to close them.
  102283. **
  102284. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  102285. ** in pTabList pointing at their appropriate entries. The [...] code
  102286. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  102287. ** data from the various tables of the loop.
  102288. **
  102289. ** If the WHERE clause is empty, the foreach loops must each scan their
  102290. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  102291. ** the tables have indices and there are terms in the WHERE clause that
  102292. ** refer to those indices, a complete table scan can be avoided and the
  102293. ** code will run much faster. Most of the work of this routine is checking
  102294. ** to see if there are indices that can be used to speed up the loop.
  102295. **
  102296. ** Terms of the WHERE clause are also used to limit which rows actually
  102297. ** make it to the "..." in the middle of the loop. After each "foreach",
  102298. ** terms of the WHERE clause that use only terms in that loop and outer
  102299. ** loops are evaluated and if false a jump is made around all subsequent
  102300. ** inner loops (or around the "..." if the test occurs within the inner-
  102301. ** most loop)
  102302. **
  102303. ** OUTER JOINS
  102304. **
  102305. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  102306. **
  102307. ** foreach row1 in t1 do
  102308. ** flag = 0
  102309. ** foreach row2 in t2 do
  102310. ** start:
  102311. ** ...
  102312. ** flag = 1
  102313. ** end
  102314. ** if flag==0 then
  102315. ** move the row2 cursor to a null row
  102316. ** goto start
  102317. ** fi
  102318. ** end
  102319. **
  102320. ** ORDER BY CLAUSE PROCESSING
  102321. **
  102322. ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  102323. ** if there is one. If there is no ORDER BY clause or if this routine
  102324. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  102325. **
  102326. ** If an index can be used so that the natural output order of the table
  102327. ** scan is correct for the ORDER BY clause, then that index is used and
  102328. ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
  102329. ** is an optimization that prevents an unnecessary sort of the result set
  102330. ** if an index appropriate for the ORDER BY clause already exists.
  102331. **
  102332. ** If the where clause loops cannot be arranged to provide the correct
  102333. ** output order, then WhereInfo.nOBSat is 0.
  102334. */
  102335. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  102336. Parse *pParse, /* The parser context */
  102337. SrcList *pTabList, /* A list of all tables to be scanned */
  102338. Expr *pWhere, /* The WHERE clause */
  102339. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  102340. ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
  102341. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  102342. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  102343. ){
  102344. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  102345. int nTabList; /* Number of elements in pTabList */
  102346. WhereInfo *pWInfo; /* Will become the return value of this function */
  102347. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  102348. Bitmask notReady; /* Cursors that are not yet positioned */
  102349. WhereBestIdx sWBI; /* Best index search context */
  102350. WhereMaskSet *pMaskSet; /* The expression mask set */
  102351. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  102352. int iFrom; /* First unused FROM clause element */
  102353. int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
  102354. int ii; /* Loop counter */
  102355. sqlite3 *db; /* Database connection */
  102356. /* Variable initialization */
  102357. memset(&sWBI, 0, sizeof(sWBI));
  102358. sWBI.pParse = pParse;
  102359. /* The number of tables in the FROM clause is limited by the number of
  102360. ** bits in a Bitmask
  102361. */
  102362. testcase( pTabList->nSrc==BMS );
  102363. if( pTabList->nSrc>BMS ){
  102364. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  102365. return 0;
  102366. }
  102367. /* This function normally generates a nested loop for all tables in
  102368. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  102369. ** only generate code for the first table in pTabList and assume that
  102370. ** any cursors associated with subsequent tables are uninitialized.
  102371. */
  102372. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  102373. /* Allocate and initialize the WhereInfo structure that will become the
  102374. ** return value. A single allocation is used to store the WhereInfo
  102375. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  102376. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  102377. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  102378. ** some architectures. Hence the ROUND8() below.
  102379. */
  102380. db = pParse->db;
  102381. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  102382. pWInfo = sqlite3DbMallocZero(db,
  102383. nByteWInfo +
  102384. sizeof(WhereClause) +
  102385. sizeof(WhereMaskSet)
  102386. );
  102387. if( db->mallocFailed ){
  102388. sqlite3DbFree(db, pWInfo);
  102389. pWInfo = 0;
  102390. goto whereBeginError;
  102391. }
  102392. pWInfo->nLevel = nTabList;
  102393. pWInfo->pParse = pParse;
  102394. pWInfo->pTabList = pTabList;
  102395. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  102396. pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
  102397. pWInfo->wctrlFlags = wctrlFlags;
  102398. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  102399. pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
  102400. sWBI.aLevel = pWInfo->a;
  102401. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  102402. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  102403. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
  102404. /* Split the WHERE clause into separate subexpressions where each
  102405. ** subexpression is separated by an AND operator.
  102406. */
  102407. initMaskSet(pMaskSet);
  102408. whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
  102409. sqlite3ExprCodeConstants(pParse, pWhere);
  102410. whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
  102411. /* Special case: a WHERE clause that is constant. Evaluate the
  102412. ** expression and either jump over all of the code or fall thru.
  102413. */
  102414. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  102415. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  102416. pWhere = 0;
  102417. }
  102418. /* Assign a bit from the bitmask to every term in the FROM clause.
  102419. **
  102420. ** When assigning bitmask values to FROM clause cursors, it must be
  102421. ** the case that if X is the bitmask for the N-th FROM clause term then
  102422. ** the bitmask for all FROM clause terms to the left of the N-th term
  102423. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  102424. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  102425. ** of the join. Subtracting one from the right table bitmask gives a
  102426. ** bitmask for all tables to the left of the join. Knowing the bitmask
  102427. ** for all tables to the left of a left join is important. Ticket #3015.
  102428. **
  102429. ** Note that bitmasks are created for all pTabList->nSrc tables in
  102430. ** pTabList, not just the first nTabList tables. nTabList is normally
  102431. ** equal to pTabList->nSrc but might be shortened to 1 if the
  102432. ** WHERE_ONETABLE_ONLY flag is set.
  102433. */
  102434. for(ii=0; ii<pTabList->nSrc; ii++){
  102435. createMask(pMaskSet, pTabList->a[ii].iCursor);
  102436. }
  102437. #ifndef NDEBUG
  102438. {
  102439. Bitmask toTheLeft = 0;
  102440. for(ii=0; ii<pTabList->nSrc; ii++){
  102441. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  102442. assert( (m-1)==toTheLeft );
  102443. toTheLeft |= m;
  102444. }
  102445. }
  102446. #endif
  102447. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  102448. ** add new virtual terms onto the end of the WHERE clause. We do not
  102449. ** want to analyze these virtual terms, so start analyzing at the end
  102450. ** and work forward so that the added virtual terms are never processed.
  102451. */
  102452. exprAnalyzeAll(pTabList, sWBI.pWC);
  102453. if( db->mallocFailed ){
  102454. goto whereBeginError;
  102455. }
  102456. /* Check if the DISTINCT qualifier, if there is one, is redundant.
  102457. ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
  102458. ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
  102459. */
  102460. if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
  102461. pDistinct = 0;
  102462. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  102463. }
  102464. /* Chose the best index to use for each table in the FROM clause.
  102465. **
  102466. ** This loop fills in the following fields:
  102467. **
  102468. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  102469. ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
  102470. ** pWInfo->a[].nEq The number of == and IN constraints
  102471. ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
  102472. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  102473. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  102474. ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
  102475. **
  102476. ** This loop also figures out the nesting order of tables in the FROM
  102477. ** clause.
  102478. */
  102479. sWBI.notValid = ~(Bitmask)0;
  102480. sWBI.pOrderBy = pOrderBy;
  102481. sWBI.n = nTabList;
  102482. sWBI.pDistinct = pDistinct;
  102483. andFlags = ~0;
  102484. WHERETRACE(("*** Optimizer Start ***\n"));
  102485. for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
  102486. WhereCost bestPlan; /* Most efficient plan seen so far */
  102487. Index *pIdx; /* Index for FROM table at pTabItem */
  102488. int j; /* For looping over FROM tables */
  102489. int bestJ = -1; /* The value of j */
  102490. Bitmask m; /* Bitmask value for j or bestJ */
  102491. int isOptimal; /* Iterator for optimal/non-optimal search */
  102492. int ckOptimal; /* Do the optimal scan check */
  102493. int nUnconstrained; /* Number tables without INDEXED BY */
  102494. Bitmask notIndexed; /* Mask of tables that cannot use an index */
  102495. memset(&bestPlan, 0, sizeof(bestPlan));
  102496. bestPlan.rCost = SQLITE_BIG_DBL;
  102497. WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
  102498. /* Loop through the remaining entries in the FROM clause to find the
  102499. ** next nested loop. The loop tests all FROM clause entries
  102500. ** either once or twice.
  102501. **
  102502. ** The first test is always performed if there are two or more entries
  102503. ** remaining and never performed if there is only one FROM clause entry
  102504. ** to choose from. The first test looks for an "optimal" scan. In
  102505. ** this context an optimal scan is one that uses the same strategy
  102506. ** for the given FROM clause entry as would be selected if the entry
  102507. ** were used as the innermost nested loop. In other words, a table
  102508. ** is chosen such that the cost of running that table cannot be reduced
  102509. ** by waiting for other tables to run first. This "optimal" test works
  102510. ** by first assuming that the FROM clause is on the inner loop and finding
  102511. ** its query plan, then checking to see if that query plan uses any
  102512. ** other FROM clause terms that are sWBI.notValid. If no notValid terms
  102513. ** are used then the "optimal" query plan works.
  102514. **
  102515. ** Note that the WhereCost.nRow parameter for an optimal scan might
  102516. ** not be as small as it would be if the table really were the innermost
  102517. ** join. The nRow value can be reduced by WHERE clause constraints
  102518. ** that do not use indices. But this nRow reduction only happens if the
  102519. ** table really is the innermost join.
  102520. **
  102521. ** The second loop iteration is only performed if no optimal scan
  102522. ** strategies were found by the first iteration. This second iteration
  102523. ** is used to search for the lowest cost scan overall.
  102524. **
  102525. ** Without the optimal scan step (the first iteration) a suboptimal
  102526. ** plan might be chosen for queries like this:
  102527. **
  102528. ** CREATE TABLE t1(a, b);
  102529. ** CREATE TABLE t2(c, d);
  102530. ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
  102531. **
  102532. ** The best strategy is to iterate through table t1 first. However it
  102533. ** is not possible to determine this with a simple greedy algorithm.
  102534. ** Since the cost of a linear scan through table t2 is the same
  102535. ** as the cost of a linear scan through table t1, a simple greedy
  102536. ** algorithm may choose to use t2 for the outer loop, which is a much
  102537. ** costlier approach.
  102538. */
  102539. nUnconstrained = 0;
  102540. notIndexed = 0;
  102541. /* The optimal scan check only occurs if there are two or more tables
  102542. ** available to be reordered */
  102543. if( iFrom==nTabList-1 ){
  102544. ckOptimal = 0; /* Common case of just one table in the FROM clause */
  102545. }else{
  102546. ckOptimal = -1;
  102547. for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
  102548. m = getMask(pMaskSet, sWBI.pSrc->iCursor);
  102549. if( (m & sWBI.notValid)==0 ){
  102550. if( j==iFrom ) iFrom++;
  102551. continue;
  102552. }
  102553. if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
  102554. if( ++ckOptimal ) break;
  102555. if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
  102556. }
  102557. }
  102558. assert( ckOptimal==0 || ckOptimal==1 );
  102559. for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
  102560. for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
  102561. if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
  102562. /* This break and one like it in the ckOptimal computation loop
  102563. ** above prevent table reordering across LEFT and CROSS JOINs.
  102564. ** The LEFT JOIN case is necessary for correctness. The prohibition
  102565. ** against reordering across a CROSS JOIN is an SQLite feature that
  102566. ** allows the developer to control table reordering */
  102567. break;
  102568. }
  102569. m = getMask(pMaskSet, sWBI.pSrc->iCursor);
  102570. if( (m & sWBI.notValid)==0 ){
  102571. assert( j>iFrom );
  102572. continue;
  102573. }
  102574. sWBI.notReady = (isOptimal ? m : sWBI.notValid);
  102575. if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
  102576. WHERETRACE((" === trying table %d (%s) with isOptimal=%d ===\n",
  102577. j, sWBI.pSrc->pTab->zName, isOptimal));
  102578. assert( sWBI.pSrc->pTab );
  102579. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102580. if( IsVirtual(sWBI.pSrc->pTab) ){
  102581. sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
  102582. bestVirtualIndex(&sWBI);
  102583. }else
  102584. #endif
  102585. {
  102586. bestBtreeIndex(&sWBI);
  102587. }
  102588. assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
  102589. /* If an INDEXED BY clause is present, then the plan must use that
  102590. ** index if it uses any index at all */
  102591. assert( sWBI.pSrc->pIndex==0
  102592. || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
  102593. || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
  102594. if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  102595. notIndexed |= m;
  102596. }
  102597. if( isOptimal ){
  102598. pWInfo->a[j].rOptCost = sWBI.cost.rCost;
  102599. }else if( ckOptimal ){
  102600. /* If two or more tables have nearly the same outer loop cost, but
  102601. ** very different inner loop (optimal) cost, we want to choose
  102602. ** for the outer loop that table which benefits the least from
  102603. ** being in the inner loop. The following code scales the
  102604. ** outer loop cost estimate to accomplish that. */
  102605. WHERETRACE((" scaling cost from %.1f to %.1f\n",
  102606. sWBI.cost.rCost,
  102607. sWBI.cost.rCost/pWInfo->a[j].rOptCost));
  102608. sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
  102609. }
  102610. /* Conditions under which this table becomes the best so far:
  102611. **
  102612. ** (1) The table must not depend on other tables that have not
  102613. ** yet run. (In other words, it must not depend on tables
  102614. ** in inner loops.)
  102615. **
  102616. ** (2) (This rule was removed on 2012-11-09. The scaling of the
  102617. ** cost using the optimal scan cost made this rule obsolete.)
  102618. **
  102619. ** (3) All tables have an INDEXED BY clause or this table lacks an
  102620. ** INDEXED BY clause or this table uses the specific
  102621. ** index specified by its INDEXED BY clause. This rule ensures
  102622. ** that a best-so-far is always selected even if an impossible
  102623. ** combination of INDEXED BY clauses are given. The error
  102624. ** will be detected and relayed back to the application later.
  102625. ** The NEVER() comes about because rule (2) above prevents
  102626. ** An indexable full-table-scan from reaching rule (3).
  102627. **
  102628. ** (4) The plan cost must be lower than prior plans, where "cost"
  102629. ** is defined by the compareCost() function above.
  102630. */
  102631. if( (sWBI.cost.used&sWBI.notValid)==0 /* (1) */
  102632. && (nUnconstrained==0 || sWBI.pSrc->pIndex==0 /* (3) */
  102633. || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
  102634. && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan)) /* (4) */
  102635. ){
  102636. WHERETRACE((" === table %d (%s) is best so far\n"
  102637. " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
  102638. j, sWBI.pSrc->pTab->zName,
  102639. sWBI.cost.rCost, sWBI.cost.plan.nRow,
  102640. sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
  102641. bestPlan = sWBI.cost;
  102642. bestJ = j;
  102643. }
  102644. /* In a join like "w JOIN x LEFT JOIN y JOIN z" make sure that
  102645. ** table y (and not table z) is always the next inner loop inside
  102646. ** of table x. */
  102647. if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
  102648. }
  102649. }
  102650. assert( bestJ>=0 );
  102651. assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
  102652. assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
  102653. testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
  102654. testcase( bestJ>iFrom && bestJ<nTabList-1
  102655. && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
  102656. WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
  102657. " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
  102658. bestJ, pTabList->a[bestJ].pTab->zName,
  102659. pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
  102660. bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
  102661. if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
  102662. assert( pWInfo->eDistinct==0 );
  102663. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  102664. }
  102665. andFlags &= bestPlan.plan.wsFlags;
  102666. pLevel->plan = bestPlan.plan;
  102667. pLevel->iTabCur = pTabList->a[bestJ].iCursor;
  102668. testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
  102669. testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
  102670. if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
  102671. if( (wctrlFlags & WHERE_ONETABLE_ONLY)
  102672. && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
  102673. ){
  102674. pLevel->iIdxCur = iIdxCur;
  102675. }else{
  102676. pLevel->iIdxCur = pParse->nTab++;
  102677. }
  102678. }else{
  102679. pLevel->iIdxCur = -1;
  102680. }
  102681. sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
  102682. pLevel->iFrom = (u8)bestJ;
  102683. if( bestPlan.plan.nRow>=(double)1 ){
  102684. pParse->nQueryLoop *= bestPlan.plan.nRow;
  102685. }
  102686. /* Check that if the table scanned by this loop iteration had an
  102687. ** INDEXED BY clause attached to it, that the named index is being
  102688. ** used for the scan. If not, then query compilation has failed.
  102689. ** Return an error.
  102690. */
  102691. pIdx = pTabList->a[bestJ].pIndex;
  102692. if( pIdx ){
  102693. if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
  102694. sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
  102695. goto whereBeginError;
  102696. }else{
  102697. /* If an INDEXED BY clause is used, the bestIndex() function is
  102698. ** guaranteed to find the index specified in the INDEXED BY clause
  102699. ** if it find an index at all. */
  102700. assert( bestPlan.plan.u.pIdx==pIdx );
  102701. }
  102702. }
  102703. }
  102704. WHERETRACE(("*** Optimizer Finished ***\n"));
  102705. if( pParse->nErr || db->mallocFailed ){
  102706. goto whereBeginError;
  102707. }
  102708. if( nTabList ){
  102709. pLevel--;
  102710. pWInfo->nOBSat = pLevel->plan.nOBSat;
  102711. }else{
  102712. pWInfo->nOBSat = 0;
  102713. }
  102714. /* If the total query only selects a single row, then the ORDER BY
  102715. ** clause is irrelevant.
  102716. */
  102717. if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
  102718. assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
  102719. pWInfo->nOBSat = pOrderBy->nExpr;
  102720. }
  102721. /* If the caller is an UPDATE or DELETE statement that is requesting
  102722. ** to use a one-pass algorithm, determine if this is appropriate.
  102723. ** The one-pass algorithm only works if the WHERE clause constraints
  102724. ** the statement to update a single row.
  102725. */
  102726. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  102727. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
  102728. pWInfo->okOnePass = 1;
  102729. pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  102730. }
  102731. /* Open all tables in the pTabList and any indices selected for
  102732. ** searching those tables.
  102733. */
  102734. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  102735. notReady = ~(Bitmask)0;
  102736. pWInfo->nRowOut = (double)1;
  102737. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  102738. Table *pTab; /* Table to open */
  102739. int iDb; /* Index of database containing table/index */
  102740. struct SrcList_item *pTabItem;
  102741. pTabItem = &pTabList->a[pLevel->iFrom];
  102742. pTab = pTabItem->pTab;
  102743. pWInfo->nRowOut *= pLevel->plan.nRow;
  102744. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102745. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  102746. /* Do nothing */
  102747. }else
  102748. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102749. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  102750. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  102751. int iCur = pTabItem->iCursor;
  102752. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  102753. }else if( IsVirtual(pTab) ){
  102754. /* noop */
  102755. }else
  102756. #endif
  102757. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  102758. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  102759. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  102760. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  102761. testcase( pTab->nCol==BMS-1 );
  102762. testcase( pTab->nCol==BMS );
  102763. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  102764. Bitmask b = pTabItem->colUsed;
  102765. int n = 0;
  102766. for(; b; b=b>>1, n++){}
  102767. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  102768. SQLITE_INT_TO_PTR(n), P4_INT32);
  102769. assert( n<=pTab->nCol );
  102770. }
  102771. }else{
  102772. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  102773. }
  102774. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  102775. if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
  102776. constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
  102777. }else
  102778. #endif
  102779. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  102780. Index *pIx = pLevel->plan.u.pIdx;
  102781. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  102782. int iIndexCur = pLevel->iIdxCur;
  102783. assert( pIx->pSchema==pTab->pSchema );
  102784. assert( iIndexCur>=0 );
  102785. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  102786. (char*)pKey, P4_KEYINFO_HANDOFF);
  102787. VdbeComment((v, "%s", pIx->zName));
  102788. }
  102789. sqlite3CodeVerifySchema(pParse, iDb);
  102790. notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
  102791. }
  102792. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  102793. if( db->mallocFailed ) goto whereBeginError;
  102794. /* Generate the code to do the search. Each iteration of the for
  102795. ** loop below generates code for a single nested loop of the VM
  102796. ** program.
  102797. */
  102798. notReady = ~(Bitmask)0;
  102799. for(ii=0; ii<nTabList; ii++){
  102800. pLevel = &pWInfo->a[ii];
  102801. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  102802. notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
  102803. pWInfo->iContinue = pLevel->addrCont;
  102804. }
  102805. #ifdef SQLITE_TEST /* For testing and debugging use only */
  102806. /* Record in the query plan information about the current table
  102807. ** and the index used to access it (if any). If the table itself
  102808. ** is not used, its name is just '{}'. If no index is used
  102809. ** the index is listed as "{}". If the primary key is used the
  102810. ** index name is '*'.
  102811. */
  102812. for(ii=0; ii<nTabList; ii++){
  102813. char *z;
  102814. int n;
  102815. int w;
  102816. struct SrcList_item *pTabItem;
  102817. pLevel = &pWInfo->a[ii];
  102818. w = pLevel->plan.wsFlags;
  102819. pTabItem = &pTabList->a[pLevel->iFrom];
  102820. z = pTabItem->zAlias;
  102821. if( z==0 ) z = pTabItem->pTab->zName;
  102822. n = sqlite3Strlen30(z);
  102823. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  102824. if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
  102825. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  102826. nQPlan += 2;
  102827. }else{
  102828. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  102829. nQPlan += n;
  102830. }
  102831. sqlite3_query_plan[nQPlan++] = ' ';
  102832. }
  102833. testcase( w & WHERE_ROWID_EQ );
  102834. testcase( w & WHERE_ROWID_RANGE );
  102835. if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  102836. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  102837. nQPlan += 2;
  102838. }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
  102839. n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
  102840. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  102841. memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
  102842. nQPlan += n;
  102843. sqlite3_query_plan[nQPlan++] = ' ';
  102844. }
  102845. }else{
  102846. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  102847. nQPlan += 3;
  102848. }
  102849. }
  102850. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  102851. sqlite3_query_plan[--nQPlan] = 0;
  102852. }
  102853. sqlite3_query_plan[nQPlan] = 0;
  102854. nQPlan = 0;
  102855. #endif /* SQLITE_TEST // Testing and debugging use only */
  102856. /* Record the continuation address in the WhereInfo structure. Then
  102857. ** clean up and return.
  102858. */
  102859. return pWInfo;
  102860. /* Jump here if malloc fails */
  102861. whereBeginError:
  102862. if( pWInfo ){
  102863. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  102864. whereInfoFree(db, pWInfo);
  102865. }
  102866. return 0;
  102867. }
  102868. /*
  102869. ** Generate the end of the WHERE loop. See comments on
  102870. ** sqlite3WhereBegin() for additional information.
  102871. */
  102872. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  102873. Parse *pParse = pWInfo->pParse;
  102874. Vdbe *v = pParse->pVdbe;
  102875. int i;
  102876. WhereLevel *pLevel;
  102877. SrcList *pTabList = pWInfo->pTabList;
  102878. sqlite3 *db = pParse->db;
  102879. /* Generate loop termination code.
  102880. */
  102881. sqlite3ExprCacheClear(pParse);
  102882. for(i=pWInfo->nLevel-1; i>=0; i--){
  102883. pLevel = &pWInfo->a[i];
  102884. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  102885. if( pLevel->op!=OP_Noop ){
  102886. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  102887. sqlite3VdbeChangeP5(v, pLevel->p5);
  102888. }
  102889. if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  102890. struct InLoop *pIn;
  102891. int j;
  102892. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  102893. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  102894. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  102895. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  102896. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  102897. }
  102898. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  102899. }
  102900. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  102901. if( pLevel->iLeftJoin ){
  102902. int addr;
  102903. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  102904. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  102905. || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
  102906. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
  102907. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  102908. }
  102909. if( pLevel->iIdxCur>=0 ){
  102910. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  102911. }
  102912. if( pLevel->op==OP_Return ){
  102913. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  102914. }else{
  102915. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  102916. }
  102917. sqlite3VdbeJumpHere(v, addr);
  102918. }
  102919. }
  102920. /* The "break" point is here, just past the end of the outer loop.
  102921. ** Set it.
  102922. */
  102923. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  102924. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  102925. */
  102926. assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
  102927. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  102928. Index *pIdx = 0;
  102929. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  102930. Table *pTab = pTabItem->pTab;
  102931. assert( pTab!=0 );
  102932. if( (pTab->tabFlags & TF_Ephemeral)==0
  102933. && pTab->pSelect==0
  102934. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  102935. ){
  102936. int ws = pLevel->plan.wsFlags;
  102937. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  102938. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  102939. }
  102940. if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
  102941. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  102942. }
  102943. }
  102944. /* If this scan uses an index, make code substitutions to read data
  102945. ** from the index in preference to the table. Sometimes, this means
  102946. ** the table need never be read from. This is a performance boost,
  102947. ** as the vdbe level waits until the table is read before actually
  102948. ** seeking the table cursor to the record corresponding to the current
  102949. ** position in the index.
  102950. **
  102951. ** Calls to the code generator in between sqlite3WhereBegin and
  102952. ** sqlite3WhereEnd will have created code that references the table
  102953. ** directly. This loop scans all that code looking for opcodes
  102954. ** that reference the table and converts them into opcodes that
  102955. ** reference the index.
  102956. */
  102957. if( pLevel->plan.wsFlags & WHERE_INDEXED ){
  102958. pIdx = pLevel->plan.u.pIdx;
  102959. }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  102960. pIdx = pLevel->u.pCovidx;
  102961. }
  102962. if( pIdx && !db->mallocFailed){
  102963. int k, j, last;
  102964. VdbeOp *pOp;
  102965. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  102966. last = sqlite3VdbeCurrentAddr(v);
  102967. for(k=pWInfo->iTop; k<last; k++, pOp++){
  102968. if( pOp->p1!=pLevel->iTabCur ) continue;
  102969. if( pOp->opcode==OP_Column ){
  102970. for(j=0; j<pIdx->nColumn; j++){
  102971. if( pOp->p2==pIdx->aiColumn[j] ){
  102972. pOp->p2 = j;
  102973. pOp->p1 = pLevel->iIdxCur;
  102974. break;
  102975. }
  102976. }
  102977. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  102978. || j<pIdx->nColumn );
  102979. }else if( pOp->opcode==OP_Rowid ){
  102980. pOp->p1 = pLevel->iIdxCur;
  102981. pOp->opcode = OP_IdxRowid;
  102982. }
  102983. }
  102984. }
  102985. }
  102986. /* Final cleanup
  102987. */
  102988. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  102989. whereInfoFree(db, pWInfo);
  102990. return;
  102991. }
  102992. /************** End of where.c ***********************************************/
  102993. /************** Begin file parse.c *******************************************/
  102994. /* Driver template for the LEMON parser generator.
  102995. ** The author disclaims copyright to this source code.
  102996. **
  102997. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  102998. ** The only modifications are the addition of a couple of NEVER()
  102999. ** macros to disable tests that are needed in the case of a general
  103000. ** LALR(1) grammar but which are always false in the
  103001. ** specific grammar used by SQLite.
  103002. */
  103003. /* First off, code is included that follows the "include" declaration
  103004. ** in the input grammar file. */
  103005. /* #include <stdio.h> */
  103006. /*
  103007. ** Disable all error recovery processing in the parser push-down
  103008. ** automaton.
  103009. */
  103010. #define YYNOERRORRECOVERY 1
  103011. /*
  103012. ** Make yytestcase() the same as testcase()
  103013. */
  103014. #define yytestcase(X) testcase(X)
  103015. /*
  103016. ** An instance of this structure holds information about the
  103017. ** LIMIT clause of a SELECT statement.
  103018. */
  103019. struct LimitVal {
  103020. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  103021. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  103022. };
  103023. /*
  103024. ** An instance of this structure is used to store the LIKE,
  103025. ** GLOB, NOT LIKE, and NOT GLOB operators.
  103026. */
  103027. struct LikeOp {
  103028. Token eOperator; /* "like" or "glob" or "regexp" */
  103029. int bNot; /* True if the NOT keyword is present */
  103030. };
  103031. /*
  103032. ** An instance of the following structure describes the event of a
  103033. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  103034. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  103035. **
  103036. ** UPDATE ON (a,b,c)
  103037. **
  103038. ** Then the "b" IdList records the list "a,b,c".
  103039. */
  103040. struct TrigEvent { int a; IdList * b; };
  103041. /*
  103042. ** An instance of this structure holds the ATTACH key and the key type.
  103043. */
  103044. struct AttachKey { int type; Token key; };
  103045. /*
  103046. ** One or more VALUES claues
  103047. */
  103048. struct ValueList {
  103049. ExprList *pList;
  103050. Select *pSelect;
  103051. };
  103052. /* This is a utility routine used to set the ExprSpan.zStart and
  103053. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  103054. ** range of text beginning with pStart and going to the end of pEnd.
  103055. */
  103056. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  103057. pOut->zStart = pStart->z;
  103058. pOut->zEnd = &pEnd->z[pEnd->n];
  103059. }
  103060. /* Construct a new Expr object from a single identifier. Use the
  103061. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  103062. ** that created the expression.
  103063. */
  103064. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  103065. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  103066. pOut->zStart = pValue->z;
  103067. pOut->zEnd = &pValue->z[pValue->n];
  103068. }
  103069. /* This routine constructs a binary expression node out of two ExprSpan
  103070. ** objects and uses the result to populate a new ExprSpan object.
  103071. */
  103072. static void spanBinaryExpr(
  103073. ExprSpan *pOut, /* Write the result here */
  103074. Parse *pParse, /* The parsing context. Errors accumulate here */
  103075. int op, /* The binary operation */
  103076. ExprSpan *pLeft, /* The left operand */
  103077. ExprSpan *pRight /* The right operand */
  103078. ){
  103079. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  103080. pOut->zStart = pLeft->zStart;
  103081. pOut->zEnd = pRight->zEnd;
  103082. }
  103083. /* Construct an expression node for a unary postfix operator
  103084. */
  103085. static void spanUnaryPostfix(
  103086. ExprSpan *pOut, /* Write the new expression node here */
  103087. Parse *pParse, /* Parsing context to record errors */
  103088. int op, /* The operator */
  103089. ExprSpan *pOperand, /* The operand */
  103090. Token *pPostOp /* The operand token for setting the span */
  103091. ){
  103092. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  103093. pOut->zStart = pOperand->zStart;
  103094. pOut->zEnd = &pPostOp->z[pPostOp->n];
  103095. }
  103096. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  103097. ** unary TK_ISNULL or TK_NOTNULL expression. */
  103098. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  103099. sqlite3 *db = pParse->db;
  103100. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  103101. pA->op = (u8)op;
  103102. sqlite3ExprDelete(db, pA->pRight);
  103103. pA->pRight = 0;
  103104. }
  103105. }
  103106. /* Construct an expression node for a unary prefix operator
  103107. */
  103108. static void spanUnaryPrefix(
  103109. ExprSpan *pOut, /* Write the new expression node here */
  103110. Parse *pParse, /* Parsing context to record errors */
  103111. int op, /* The operator */
  103112. ExprSpan *pOperand, /* The operand */
  103113. Token *pPreOp /* The operand token for setting the span */
  103114. ){
  103115. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  103116. pOut->zStart = pPreOp->z;
  103117. pOut->zEnd = pOperand->zEnd;
  103118. }
  103119. /* Next is all token values, in a form suitable for use by makeheaders.
  103120. ** This section will be null unless lemon is run with the -m switch.
  103121. */
  103122. /*
  103123. ** These constants (all generated automatically by the parser generator)
  103124. ** specify the various kinds of tokens (terminals) that the parser
  103125. ** understands.
  103126. **
  103127. ** Each symbol here is a terminal symbol in the grammar.
  103128. */
  103129. /* Make sure the INTERFACE macro is defined.
  103130. */
  103131. #ifndef INTERFACE
  103132. # define INTERFACE 1
  103133. #endif
  103134. /* The next thing included is series of defines which control
  103135. ** various aspects of the generated parser.
  103136. ** YYCODETYPE is the data type used for storing terminal
  103137. ** and nonterminal numbers. "unsigned char" is
  103138. ** used if there are fewer than 250 terminals
  103139. ** and nonterminals. "int" is used otherwise.
  103140. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  103141. ** to no legal terminal or nonterminal number. This
  103142. ** number is used to fill in empty slots of the hash
  103143. ** table.
  103144. ** YYFALLBACK If defined, this indicates that one or more tokens
  103145. ** have fall-back values which should be used if the
  103146. ** original value of the token will not parse.
  103147. ** YYACTIONTYPE is the data type used for storing terminal
  103148. ** and nonterminal numbers. "unsigned char" is
  103149. ** used if there are fewer than 250 rules and
  103150. ** states combined. "int" is used otherwise.
  103151. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  103152. ** directly to the parser from the tokenizer.
  103153. ** YYMINORTYPE is the data type used for all minor tokens.
  103154. ** This is typically a union of many types, one of
  103155. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  103156. ** for base tokens is called "yy0".
  103157. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  103158. ** zero the stack is dynamically sized using realloc()
  103159. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  103160. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  103161. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  103162. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  103163. ** YYNSTATE the combined number of states.
  103164. ** YYNRULE the number of rules in the grammar
  103165. ** YYERRORSYMBOL is the code number of the error symbol. If not
  103166. ** defined, then do no error processing.
  103167. */
  103168. #define YYCODETYPE unsigned char
  103169. #define YYNOCODE 251
  103170. #define YYACTIONTYPE unsigned short int
  103171. #define YYWILDCARD 67
  103172. #define sqlite3ParserTOKENTYPE Token
  103173. typedef union {
  103174. int yyinit;
  103175. sqlite3ParserTOKENTYPE yy0;
  103176. struct LimitVal yy64;
  103177. Expr* yy122;
  103178. Select* yy159;
  103179. IdList* yy180;
  103180. struct {int value; int mask;} yy207;
  103181. u8 yy258;
  103182. u16 yy305;
  103183. struct LikeOp yy318;
  103184. TriggerStep* yy327;
  103185. ExprSpan yy342;
  103186. SrcList* yy347;
  103187. int yy392;
  103188. struct TrigEvent yy410;
  103189. ExprList* yy442;
  103190. struct ValueList yy487;
  103191. } YYMINORTYPE;
  103192. #ifndef YYSTACKDEPTH
  103193. #define YYSTACKDEPTH 100
  103194. #endif
  103195. #define sqlite3ParserARG_SDECL Parse *pParse;
  103196. #define sqlite3ParserARG_PDECL ,Parse *pParse
  103197. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  103198. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  103199. #define YYNSTATE 627
  103200. #define YYNRULE 327
  103201. #define YYFALLBACK 1
  103202. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  103203. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  103204. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  103205. /* The yyzerominor constant is used to initialize instances of
  103206. ** YYMINORTYPE objects to zero. */
  103207. static const YYMINORTYPE yyzerominor = { 0 };
  103208. /* Define the yytestcase() macro to be a no-op if is not already defined
  103209. ** otherwise.
  103210. **
  103211. ** Applications can choose to define yytestcase() in the %include section
  103212. ** to a macro that can assist in verifying code coverage. For production
  103213. ** code the yytestcase() macro should be turned off. But it is useful
  103214. ** for testing.
  103215. */
  103216. #ifndef yytestcase
  103217. # define yytestcase(X)
  103218. #endif
  103219. /* Next are the tables used to determine what action to take based on the
  103220. ** current state and lookahead token. These tables are used to implement
  103221. ** functions that take a state number and lookahead value and return an
  103222. ** action integer.
  103223. **
  103224. ** Suppose the action integer is N. Then the action is determined as
  103225. ** follows
  103226. **
  103227. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  103228. ** token onto the stack and goto state N.
  103229. **
  103230. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  103231. **
  103232. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  103233. **
  103234. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  103235. **
  103236. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  103237. ** slots in the yy_action[] table.
  103238. **
  103239. ** The action table is constructed as a single large table named yy_action[].
  103240. ** Given state S and lookahead X, the action is computed as
  103241. **
  103242. ** yy_action[ yy_shift_ofst[S] + X ]
  103243. **
  103244. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  103245. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  103246. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  103247. ** and that yy_default[S] should be used instead.
  103248. **
  103249. ** The formula above is for computing the action when the lookahead is
  103250. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  103251. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  103252. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  103253. ** YY_SHIFT_USE_DFLT.
  103254. **
  103255. ** The following are the tables generated in this section:
  103256. **
  103257. ** yy_action[] A single table containing all actions.
  103258. ** yy_lookahead[] A table containing the lookahead for each entry in
  103259. ** yy_action. Used to detect hash collisions.
  103260. ** yy_shift_ofst[] For each state, the offset into yy_action for
  103261. ** shifting terminals.
  103262. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  103263. ** shifting non-terminals after a reduce.
  103264. ** yy_default[] Default action for each state.
  103265. */
  103266. #define YY_ACTTAB_COUNT (1564)
  103267. static const YYACTIONTYPE yy_action[] = {
  103268. /* 0 */ 309, 955, 184, 417, 2, 171, 624, 594, 56, 56,
  103269. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  103270. /* 20 */ 52, 52, 51, 233, 620, 619, 298, 620, 619, 234,
  103271. /* 30 */ 587, 581, 56, 56, 56, 56, 19, 54, 54, 54,
  103272. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 605, 57,
  103273. /* 50 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  103274. /* 60 */ 56, 56, 541, 54, 54, 54, 54, 53, 53, 52,
  103275. /* 70 */ 52, 52, 51, 233, 309, 594, 325, 196, 195, 194,
  103276. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  103277. /* 90 */ 51, 233, 617, 616, 165, 617, 616, 380, 377, 376,
  103278. /* 100 */ 407, 532, 576, 576, 587, 581, 303, 422, 375, 59,
  103279. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  103280. /* 120 */ 574, 545, 65, 57, 58, 48, 579, 578, 580, 580,
  103281. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  103282. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 223,
  103283. /* 150 */ 539, 420, 170, 176, 138, 280, 383, 275, 382, 168,
  103284. /* 160 */ 489, 551, 409, 668, 620, 619, 271, 438, 409, 438,
  103285. /* 170 */ 550, 604, 67, 482, 507, 618, 599, 412, 587, 581,
  103286. /* 180 */ 600, 483, 618, 412, 618, 598, 91, 439, 440, 439,
  103287. /* 190 */ 335, 598, 73, 669, 222, 266, 480, 57, 58, 48,
  103288. /* 200 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  103289. /* 210 */ 670, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  103290. /* 220 */ 51, 233, 309, 279, 232, 231, 1, 132, 200, 385,
  103291. /* 230 */ 620, 619, 617, 616, 278, 435, 289, 563, 175, 262,
  103292. /* 240 */ 409, 264, 437, 497, 436, 166, 441, 568, 336, 568,
  103293. /* 250 */ 201, 537, 587, 581, 599, 412, 165, 594, 600, 380,
  103294. /* 260 */ 377, 376, 597, 598, 92, 523, 618, 569, 569, 592,
  103295. /* 270 */ 375, 57, 58, 48, 579, 578, 580, 580, 55, 55,
  103296. /* 280 */ 56, 56, 56, 56, 597, 54, 54, 54, 54, 53,
  103297. /* 290 */ 53, 52, 52, 52, 51, 233, 309, 463, 617, 616,
  103298. /* 300 */ 590, 590, 590, 174, 272, 396, 409, 272, 409, 548,
  103299. /* 310 */ 397, 620, 619, 68, 326, 620, 619, 620, 619, 618,
  103300. /* 320 */ 546, 412, 618, 412, 471, 594, 587, 581, 472, 598,
  103301. /* 330 */ 92, 598, 92, 52, 52, 52, 51, 233, 513, 512,
  103302. /* 340 */ 206, 322, 363, 464, 221, 57, 58, 48, 579, 578,
  103303. /* 350 */ 580, 580, 55, 55, 56, 56, 56, 56, 529, 54,
  103304. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  103305. /* 370 */ 309, 396, 409, 396, 597, 372, 386, 530, 347, 617,
  103306. /* 380 */ 616, 575, 202, 617, 616, 617, 616, 412, 620, 619,
  103307. /* 390 */ 145, 255, 346, 254, 577, 598, 74, 351, 45, 489,
  103308. /* 400 */ 587, 581, 235, 189, 464, 544, 167, 296, 187, 469,
  103309. /* 410 */ 479, 67, 62, 39, 618, 546, 597, 345, 573, 57,
  103310. /* 420 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  103311. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  103312. /* 440 */ 52, 52, 51, 233, 309, 562, 558, 407, 528, 576,
  103313. /* 450 */ 576, 344, 255, 346, 254, 182, 617, 616, 503, 504,
  103314. /* 460 */ 314, 409, 557, 235, 166, 271, 409, 352, 564, 181,
  103315. /* 470 */ 407, 546, 576, 576, 587, 581, 412, 537, 556, 561,
  103316. /* 480 */ 517, 412, 618, 249, 598, 16, 7, 36, 467, 598,
  103317. /* 490 */ 92, 516, 618, 57, 58, 48, 579, 578, 580, 580,
  103318. /* 500 */ 55, 55, 56, 56, 56, 56, 541, 54, 54, 54,
  103319. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 327,
  103320. /* 520 */ 572, 571, 525, 558, 560, 394, 871, 246, 409, 248,
  103321. /* 530 */ 171, 392, 594, 219, 407, 409, 576, 576, 502, 557,
  103322. /* 540 */ 364, 145, 510, 412, 407, 229, 576, 576, 587, 581,
  103323. /* 550 */ 412, 598, 92, 381, 269, 556, 166, 400, 598, 69,
  103324. /* 560 */ 501, 419, 945, 199, 945, 198, 546, 57, 58, 48,
  103325. /* 570 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  103326. /* 580 */ 568, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  103327. /* 590 */ 51, 233, 309, 317, 419, 944, 508, 944, 308, 597,
  103328. /* 600 */ 594, 565, 490, 212, 173, 247, 423, 615, 614, 613,
  103329. /* 610 */ 323, 197, 143, 405, 572, 571, 489, 66, 50, 47,
  103330. /* 620 */ 146, 594, 587, 581, 232, 231, 559, 427, 67, 555,
  103331. /* 630 */ 15, 618, 186, 543, 303, 421, 35, 206, 432, 423,
  103332. /* 640 */ 552, 57, 58, 48, 579, 578, 580, 580, 55, 55,
  103333. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  103334. /* 660 */ 53, 52, 52, 52, 51, 233, 309, 569, 569, 260,
  103335. /* 670 */ 268, 597, 12, 373, 568, 166, 409, 313, 409, 420,
  103336. /* 680 */ 409, 473, 473, 365, 618, 50, 47, 146, 597, 594,
  103337. /* 690 */ 468, 412, 166, 412, 351, 412, 587, 581, 32, 598,
  103338. /* 700 */ 94, 598, 97, 598, 95, 627, 625, 329, 142, 50,
  103339. /* 710 */ 47, 146, 333, 349, 358, 57, 58, 48, 579, 578,
  103340. /* 720 */ 580, 580, 55, 55, 56, 56, 56, 56, 409, 54,
  103341. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  103342. /* 740 */ 309, 409, 388, 412, 409, 22, 565, 404, 212, 362,
  103343. /* 750 */ 389, 598, 104, 359, 409, 156, 412, 409, 603, 412,
  103344. /* 760 */ 537, 331, 569, 569, 598, 103, 493, 598, 105, 412,
  103345. /* 770 */ 587, 581, 412, 260, 549, 618, 11, 598, 106, 521,
  103346. /* 780 */ 598, 133, 169, 457, 456, 170, 35, 601, 618, 57,
  103347. /* 790 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  103348. /* 800 */ 56, 56, 409, 54, 54, 54, 54, 53, 53, 52,
  103349. /* 810 */ 52, 52, 51, 233, 309, 409, 259, 412, 409, 50,
  103350. /* 820 */ 47, 146, 357, 318, 355, 598, 134, 527, 352, 337,
  103351. /* 830 */ 412, 409, 356, 412, 357, 409, 357, 618, 598, 98,
  103352. /* 840 */ 129, 598, 102, 618, 587, 581, 412, 21, 235, 618,
  103353. /* 850 */ 412, 618, 211, 143, 598, 101, 30, 167, 598, 93,
  103354. /* 860 */ 350, 535, 203, 57, 58, 48, 579, 578, 580, 580,
  103355. /* 870 */ 55, 55, 56, 56, 56, 56, 409, 54, 54, 54,
  103356. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 409,
  103357. /* 890 */ 526, 412, 409, 425, 215, 305, 597, 551, 141, 598,
  103358. /* 900 */ 100, 40, 409, 38, 412, 409, 550, 412, 409, 228,
  103359. /* 910 */ 220, 314, 598, 77, 500, 598, 96, 412, 587, 581,
  103360. /* 920 */ 412, 338, 253, 412, 218, 598, 137, 379, 598, 136,
  103361. /* 930 */ 28, 598, 135, 270, 715, 210, 481, 57, 58, 48,
  103362. /* 940 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  103363. /* 950 */ 409, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  103364. /* 960 */ 51, 233, 309, 409, 272, 412, 409, 315, 147, 597,
  103365. /* 970 */ 272, 626, 2, 598, 76, 209, 409, 127, 412, 618,
  103366. /* 980 */ 126, 412, 409, 621, 235, 618, 598, 90, 374, 598,
  103367. /* 990 */ 89, 412, 587, 581, 27, 260, 350, 412, 618, 598,
  103368. /* 1000 */ 75, 321, 541, 541, 125, 598, 88, 320, 278, 597,
  103369. /* 1010 */ 618, 57, 46, 48, 579, 578, 580, 580, 55, 55,
  103370. /* 1020 */ 56, 56, 56, 56, 409, 54, 54, 54, 54, 53,
  103371. /* 1030 */ 53, 52, 52, 52, 51, 233, 309, 409, 450, 412,
  103372. /* 1040 */ 164, 284, 282, 272, 609, 424, 304, 598, 87, 370,
  103373. /* 1050 */ 409, 477, 412, 409, 608, 409, 607, 602, 618, 618,
  103374. /* 1060 */ 598, 99, 586, 585, 122, 412, 587, 581, 412, 618,
  103375. /* 1070 */ 412, 618, 618, 598, 86, 366, 598, 17, 598, 85,
  103376. /* 1080 */ 319, 185, 519, 518, 583, 582, 58, 48, 579, 578,
  103377. /* 1090 */ 580, 580, 55, 55, 56, 56, 56, 56, 409, 54,
  103378. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  103379. /* 1110 */ 309, 584, 409, 412, 409, 260, 260, 260, 408, 591,
  103380. /* 1120 */ 474, 598, 84, 170, 409, 466, 518, 412, 121, 412,
  103381. /* 1130 */ 618, 618, 618, 618, 618, 598, 83, 598, 72, 412,
  103382. /* 1140 */ 587, 581, 51, 233, 625, 329, 470, 598, 71, 257,
  103383. /* 1150 */ 159, 120, 14, 462, 157, 158, 117, 260, 448, 447,
  103384. /* 1160 */ 446, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  103385. /* 1170 */ 56, 56, 618, 54, 54, 54, 54, 53, 53, 52,
  103386. /* 1180 */ 52, 52, 51, 233, 44, 403, 260, 3, 409, 459,
  103387. /* 1190 */ 260, 413, 619, 118, 398, 10, 25, 24, 554, 348,
  103388. /* 1200 */ 217, 618, 406, 412, 409, 618, 4, 44, 403, 618,
  103389. /* 1210 */ 3, 598, 82, 618, 413, 619, 455, 542, 115, 412,
  103390. /* 1220 */ 538, 401, 536, 274, 506, 406, 251, 598, 81, 216,
  103391. /* 1230 */ 273, 563, 618, 243, 453, 618, 154, 618, 618, 618,
  103392. /* 1240 */ 449, 416, 623, 110, 401, 618, 409, 236, 64, 123,
  103393. /* 1250 */ 487, 41, 42, 531, 563, 204, 409, 267, 43, 411,
  103394. /* 1260 */ 410, 412, 265, 592, 108, 618, 107, 434, 332, 598,
  103395. /* 1270 */ 80, 412, 618, 263, 41, 42, 443, 618, 409, 598,
  103396. /* 1280 */ 70, 43, 411, 410, 433, 261, 592, 149, 618, 597,
  103397. /* 1290 */ 256, 237, 188, 412, 590, 590, 590, 589, 588, 13,
  103398. /* 1300 */ 618, 598, 18, 328, 235, 618, 44, 403, 360, 3,
  103399. /* 1310 */ 418, 461, 339, 413, 619, 227, 124, 590, 590, 590,
  103400. /* 1320 */ 589, 588, 13, 618, 406, 409, 618, 409, 139, 34,
  103401. /* 1330 */ 403, 387, 3, 148, 622, 312, 413, 619, 311, 330,
  103402. /* 1340 */ 412, 460, 412, 401, 180, 353, 412, 406, 598, 79,
  103403. /* 1350 */ 598, 78, 250, 563, 598, 9, 618, 612, 611, 610,
  103404. /* 1360 */ 618, 8, 452, 442, 242, 415, 401, 618, 239, 235,
  103405. /* 1370 */ 179, 238, 428, 41, 42, 288, 563, 618, 618, 618,
  103406. /* 1380 */ 43, 411, 410, 618, 144, 592, 618, 618, 177, 61,
  103407. /* 1390 */ 618, 596, 391, 620, 619, 287, 41, 42, 414, 618,
  103408. /* 1400 */ 293, 30, 393, 43, 411, 410, 292, 618, 592, 31,
  103409. /* 1410 */ 618, 395, 291, 60, 230, 37, 590, 590, 590, 589,
  103410. /* 1420 */ 588, 13, 214, 553, 183, 290, 172, 301, 300, 299,
  103411. /* 1430 */ 178, 297, 595, 563, 451, 29, 285, 390, 540, 590,
  103412. /* 1440 */ 590, 590, 589, 588, 13, 283, 520, 534, 150, 533,
  103413. /* 1450 */ 241, 281, 384, 192, 191, 324, 515, 514, 276, 240,
  103414. /* 1460 */ 510, 523, 307, 511, 128, 592, 509, 225, 226, 486,
  103415. /* 1470 */ 485, 224, 152, 491, 464, 306, 484, 163, 153, 371,
  103416. /* 1480 */ 478, 151, 162, 258, 369, 161, 367, 208, 475, 476,
  103417. /* 1490 */ 26, 160, 465, 140, 361, 131, 590, 590, 590, 116,
  103418. /* 1500 */ 119, 454, 343, 155, 114, 342, 113, 112, 445, 111,
  103419. /* 1510 */ 130, 109, 431, 316, 426, 430, 23, 429, 20, 606,
  103420. /* 1520 */ 190, 507, 255, 341, 244, 63, 294, 593, 310, 570,
  103421. /* 1530 */ 277, 402, 354, 235, 567, 496, 495, 492, 494, 302,
  103422. /* 1540 */ 458, 378, 286, 245, 566, 5, 252, 547, 193, 444,
  103423. /* 1550 */ 233, 340, 207, 524, 368, 505, 334, 522, 499, 399,
  103424. /* 1560 */ 295, 498, 956, 488,
  103425. };
  103426. static const YYCODETYPE yy_lookahead[] = {
  103427. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  103428. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  103429. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  103430. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  103431. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  103432. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  103433. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  103434. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  103435. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  103436. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  103437. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  103438. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  103439. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  103440. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  103441. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  103442. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  103443. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  103444. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  103445. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  103446. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  103447. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  103448. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  103449. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  103450. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  103451. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  103452. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  103453. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  103454. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  103455. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  103456. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  103457. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  103458. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  103459. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  103460. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  103461. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  103462. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  103463. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  103464. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  103465. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  103466. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  103467. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  103468. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  103469. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  103470. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  103471. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  103472. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  103473. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  103474. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  103475. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  103476. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  103477. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  103478. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  103479. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  103480. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  103481. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  103482. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  103483. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  103484. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  103485. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  103486. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  103487. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  103488. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  103489. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  103490. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  103491. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  103492. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  103493. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  103494. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  103495. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  103496. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  103497. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  103498. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  103499. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  103500. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  103501. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  103502. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  103503. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  103504. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  103505. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  103506. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  103507. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  103508. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  103509. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  103510. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  103511. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  103512. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  103513. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  103514. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  103515. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  103516. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  103517. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  103518. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  103519. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  103520. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  103521. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  103522. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  103523. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  103524. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  103525. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  103526. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  103527. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  103528. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  103529. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  103530. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  103531. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  103532. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  103533. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  103534. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  103535. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  103536. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  103537. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  103538. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  103539. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  103540. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  103541. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  103542. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  103543. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  103544. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  103545. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  103546. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  103547. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  103548. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  103549. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  103550. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  103551. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  103552. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  103553. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  103554. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  103555. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  103556. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  103557. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  103558. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  103559. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  103560. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  103561. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  103562. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  103563. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  103564. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  103565. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  103566. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  103567. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  103568. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  103569. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  103570. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  103571. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  103572. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  103573. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  103574. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  103575. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  103576. /* 1490 */ 135, 156, 189, 68, 157, 218, 129, 130, 131, 22,
  103577. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  103578. /* 1510 */ 218, 189, 40, 157, 38, 157, 240, 157, 240, 153,
  103579. /* 1520 */ 196, 181, 105, 106, 107, 243, 198, 166, 111, 230,
  103580. /* 1530 */ 176, 226, 239, 116, 230, 176, 166, 166, 176, 148,
  103581. /* 1540 */ 199, 177, 209, 209, 166, 196, 239, 208, 185, 199,
  103582. /* 1550 */ 92, 209, 233, 173, 234, 182, 139, 173, 182, 191,
  103583. /* 1560 */ 195, 182, 250, 186,
  103584. };
  103585. #define YY_SHIFT_USE_DFLT (-70)
  103586. #define YY_SHIFT_COUNT (416)
  103587. #define YY_SHIFT_MIN (-69)
  103588. #define YY_SHIFT_MAX (1487)
  103589. static const short yy_shift_ofst[] = {
  103590. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  103591. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  103592. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  103593. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  103594. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  103595. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  103596. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  103597. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  103598. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  103599. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  103600. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  103601. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  103602. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  103603. /* 130 */ 732, 868, 231, 1051, 1458, -70, -70, -70, 1367, 57,
  103604. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  103605. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  103606. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  103607. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  103608. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  103609. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  103610. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  103611. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  103612. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  103613. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1476, 1308, 1308,
  103614. /* 240 */ 1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
  103615. /* 250 */ 1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
  103616. /* 260 */ 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
  103617. /* 270 */ 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
  103618. /* 280 */ 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
  103619. /* 290 */ 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
  103620. /* 300 */ 1338, 1338, 1338, -70, -70, -70, -70, -70, -70, 1013,
  103621. /* 310 */ 467, 612, 84, 179, -28, 870, 410, 761, 760, 667,
  103622. /* 320 */ 650, 531, 220, 361, 331, 125, 127, 97, 1306, 1300,
  103623. /* 330 */ 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
  103624. /* 340 */ 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
  103625. /* 350 */ 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
  103626. /* 360 */ 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960, 1057,
  103627. /* 370 */ 1031, 1030, 899, 938, 982, 936, 972, 958, 910, 955,
  103628. /* 380 */ 875, 885, 908, 857, 859, 867, 804, 590, 834, 747,
  103629. /* 390 */ 818, 513, 611, 741, 673, 637, 611, 606, 603, 579,
  103630. /* 400 */ 501, 541, 468, 386, 445, 395, 376, 281, 185, 120,
  103631. /* 410 */ 92, 75, 45, 114, 25, 11, 5,
  103632. };
  103633. #define YY_REDUCE_USE_DFLT (-169)
  103634. #define YY_REDUCE_COUNT (308)
  103635. #define YY_REDUCE_MIN (-168)
  103636. #define YY_REDUCE_MAX (1391)
  103637. static const short yy_reduce_ofst[] = {
  103638. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  103639. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  103640. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  103641. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  103642. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  103643. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  103644. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  103645. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  103646. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  103647. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  103648. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  103649. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  103650. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  103651. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  103652. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  103653. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  103654. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  103655. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  103656. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  103657. /* 190 */ -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
  103658. /* 200 */ 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
  103659. /* 210 */ 1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
  103660. /* 220 */ 1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
  103661. /* 230 */ 1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
  103662. /* 240 */ 1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
  103663. /* 250 */ 1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
  103664. /* 260 */ 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
  103665. /* 270 */ 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
  103666. /* 280 */ 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
  103667. /* 290 */ 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
  103668. /* 300 */ 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  103669. };
  103670. static const YYACTIONTYPE yy_default[] = {
  103671. /* 0 */ 632, 866, 954, 954, 866, 866, 954, 954, 954, 756,
  103672. /* 10 */ 954, 954, 954, 864, 954, 954, 784, 784, 928, 954,
  103673. /* 20 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103674. /* 30 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103675. /* 40 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103676. /* 50 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103677. /* 60 */ 954, 954, 954, 954, 954, 954, 954, 671, 760, 790,
  103678. /* 70 */ 954, 954, 954, 954, 954, 954, 954, 954, 927, 929,
  103679. /* 80 */ 798, 797, 907, 771, 795, 788, 792, 867, 860, 861,
  103680. /* 90 */ 859, 863, 868, 954, 791, 827, 844, 826, 838, 843,
  103681. /* 100 */ 850, 842, 839, 829, 828, 830, 831, 954, 954, 954,
  103682. /* 110 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103683. /* 120 */ 954, 954, 954, 658, 725, 954, 954, 954, 954, 954,
  103684. /* 130 */ 954, 954, 954, 832, 833, 847, 846, 845, 954, 663,
  103685. /* 140 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103686. /* 150 */ 934, 932, 954, 879, 954, 954, 954, 954, 954, 954,
  103687. /* 160 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103688. /* 170 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103689. /* 180 */ 638, 756, 756, 756, 632, 954, 954, 954, 946, 760,
  103690. /* 190 */ 750, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103691. /* 200 */ 954, 954, 954, 800, 739, 917, 919, 954, 900, 737,
  103692. /* 210 */ 660, 758, 673, 748, 640, 794, 773, 773, 912, 794,
  103693. /* 220 */ 912, 696, 719, 954, 784, 954, 784, 693, 784, 773,
  103694. /* 230 */ 862, 954, 954, 954, 757, 748, 954, 939, 764, 764,
  103695. /* 240 */ 931, 931, 764, 806, 729, 794, 736, 736, 736, 736,
  103696. /* 250 */ 764, 655, 794, 806, 729, 729, 764, 655, 906, 904,
  103697. /* 260 */ 764, 764, 655, 764, 655, 764, 655, 872, 727, 727,
  103698. /* 270 */ 727, 711, 876, 876, 872, 727, 696, 727, 711, 727,
  103699. /* 280 */ 727, 777, 772, 777, 772, 777, 772, 764, 764, 954,
  103700. /* 290 */ 789, 778, 787, 785, 794, 954, 714, 648, 648, 637,
  103701. /* 300 */ 637, 637, 637, 951, 951, 946, 698, 698, 681, 954,
  103702. /* 310 */ 954, 954, 954, 954, 954, 954, 881, 954, 954, 954,
  103703. /* 320 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 633,
  103704. /* 330 */ 941, 954, 954, 938, 954, 954, 954, 954, 799, 954,
  103705. /* 340 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 916,
  103706. /* 350 */ 954, 954, 954, 954, 954, 954, 954, 910, 954, 954,
  103707. /* 360 */ 954, 954, 954, 954, 903, 902, 954, 954, 954, 954,
  103708. /* 370 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103709. /* 380 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  103710. /* 390 */ 954, 954, 786, 954, 779, 954, 865, 954, 954, 954,
  103711. /* 400 */ 954, 954, 954, 954, 954, 954, 954, 742, 815, 954,
  103712. /* 410 */ 814, 818, 813, 665, 954, 646, 954, 629, 634, 950,
  103713. /* 420 */ 953, 952, 949, 948, 947, 942, 940, 937, 936, 935,
  103714. /* 430 */ 933, 930, 926, 885, 883, 890, 889, 888, 887, 886,
  103715. /* 440 */ 884, 882, 880, 801, 796, 793, 925, 878, 738, 735,
  103716. /* 450 */ 734, 654, 943, 909, 918, 805, 804, 807, 915, 914,
  103717. /* 460 */ 913, 911, 908, 895, 803, 802, 730, 870, 869, 657,
  103718. /* 470 */ 899, 898, 897, 901, 905, 896, 766, 656, 653, 662,
  103719. /* 480 */ 717, 718, 726, 724, 723, 722, 721, 720, 716, 664,
  103720. /* 490 */ 672, 710, 695, 694, 875, 877, 874, 873, 703, 702,
  103721. /* 500 */ 708, 707, 706, 705, 704, 701, 700, 699, 692, 691,
  103722. /* 510 */ 697, 690, 713, 712, 709, 689, 733, 732, 731, 728,
  103723. /* 520 */ 688, 687, 686, 818, 685, 684, 824, 823, 811, 854,
  103724. /* 530 */ 753, 752, 751, 763, 762, 775, 774, 809, 808, 776,
  103725. /* 540 */ 761, 755, 754, 770, 769, 768, 767, 759, 749, 781,
  103726. /* 550 */ 783, 782, 780, 856, 765, 853, 924, 923, 922, 921,
  103727. /* 560 */ 920, 858, 857, 825, 822, 676, 677, 893, 892, 894,
  103728. /* 570 */ 891, 679, 678, 675, 674, 855, 744, 743, 851, 848,
  103729. /* 580 */ 840, 836, 852, 849, 841, 837, 835, 834, 820, 819,
  103730. /* 590 */ 817, 816, 812, 821, 667, 745, 741, 740, 810, 747,
  103731. /* 600 */ 746, 683, 682, 680, 661, 659, 652, 650, 649, 651,
  103732. /* 610 */ 647, 645, 644, 643, 642, 641, 670, 669, 668, 666,
  103733. /* 620 */ 665, 639, 636, 635, 631, 630, 628,
  103734. };
  103735. /* The next table maps tokens into fallback tokens. If a construct
  103736. ** like the following:
  103737. **
  103738. ** %fallback ID X Y Z.
  103739. **
  103740. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  103741. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  103742. ** but it does not parse, the type of the token is changed to ID and
  103743. ** the parse is retried before an error is thrown.
  103744. */
  103745. #ifdef YYFALLBACK
  103746. static const YYCODETYPE yyFallback[] = {
  103747. 0, /* $ => nothing */
  103748. 0, /* SEMI => nothing */
  103749. 26, /* EXPLAIN => ID */
  103750. 26, /* QUERY => ID */
  103751. 26, /* PLAN => ID */
  103752. 26, /* BEGIN => ID */
  103753. 0, /* TRANSACTION => nothing */
  103754. 26, /* DEFERRED => ID */
  103755. 26, /* IMMEDIATE => ID */
  103756. 26, /* EXCLUSIVE => ID */
  103757. 0, /* COMMIT => nothing */
  103758. 26, /* END => ID */
  103759. 26, /* ROLLBACK => ID */
  103760. 26, /* SAVEPOINT => ID */
  103761. 26, /* RELEASE => ID */
  103762. 0, /* TO => nothing */
  103763. 0, /* TABLE => nothing */
  103764. 0, /* CREATE => nothing */
  103765. 26, /* IF => ID */
  103766. 0, /* NOT => nothing */
  103767. 0, /* EXISTS => nothing */
  103768. 26, /* TEMP => ID */
  103769. 0, /* LP => nothing */
  103770. 0, /* RP => nothing */
  103771. 0, /* AS => nothing */
  103772. 0, /* COMMA => nothing */
  103773. 0, /* ID => nothing */
  103774. 0, /* INDEXED => nothing */
  103775. 26, /* ABORT => ID */
  103776. 26, /* ACTION => ID */
  103777. 26, /* AFTER => ID */
  103778. 26, /* ANALYZE => ID */
  103779. 26, /* ASC => ID */
  103780. 26, /* ATTACH => ID */
  103781. 26, /* BEFORE => ID */
  103782. 26, /* BY => ID */
  103783. 26, /* CASCADE => ID */
  103784. 26, /* CAST => ID */
  103785. 26, /* COLUMNKW => ID */
  103786. 26, /* CONFLICT => ID */
  103787. 26, /* DATABASE => ID */
  103788. 26, /* DESC => ID */
  103789. 26, /* DETACH => ID */
  103790. 26, /* EACH => ID */
  103791. 26, /* FAIL => ID */
  103792. 26, /* FOR => ID */
  103793. 26, /* IGNORE => ID */
  103794. 26, /* INITIALLY => ID */
  103795. 26, /* INSTEAD => ID */
  103796. 26, /* LIKE_KW => ID */
  103797. 26, /* MATCH => ID */
  103798. 26, /* NO => ID */
  103799. 26, /* KEY => ID */
  103800. 26, /* OF => ID */
  103801. 26, /* OFFSET => ID */
  103802. 26, /* PRAGMA => ID */
  103803. 26, /* RAISE => ID */
  103804. 26, /* REPLACE => ID */
  103805. 26, /* RESTRICT => ID */
  103806. 26, /* ROW => ID */
  103807. 26, /* TRIGGER => ID */
  103808. 26, /* VACUUM => ID */
  103809. 26, /* VIEW => ID */
  103810. 26, /* VIRTUAL => ID */
  103811. 26, /* REINDEX => ID */
  103812. 26, /* RENAME => ID */
  103813. 26, /* CTIME_KW => ID */
  103814. };
  103815. #endif /* YYFALLBACK */
  103816. /* The following structure represents a single element of the
  103817. ** parser's stack. Information stored includes:
  103818. **
  103819. ** + The state number for the parser at this level of the stack.
  103820. **
  103821. ** + The value of the token stored at this level of the stack.
  103822. ** (In other words, the "major" token.)
  103823. **
  103824. ** + The semantic value stored at this level of the stack. This is
  103825. ** the information used by the action routines in the grammar.
  103826. ** It is sometimes called the "minor" token.
  103827. */
  103828. struct yyStackEntry {
  103829. YYACTIONTYPE stateno; /* The state-number */
  103830. YYCODETYPE major; /* The major token value. This is the code
  103831. ** number for the token at this stack level */
  103832. YYMINORTYPE minor; /* The user-supplied minor token value. This
  103833. ** is the value of the token */
  103834. };
  103835. typedef struct yyStackEntry yyStackEntry;
  103836. /* The state of the parser is completely contained in an instance of
  103837. ** the following structure */
  103838. struct yyParser {
  103839. int yyidx; /* Index of top element in stack */
  103840. #ifdef YYTRACKMAXSTACKDEPTH
  103841. int yyidxMax; /* Maximum value of yyidx */
  103842. #endif
  103843. int yyerrcnt; /* Shifts left before out of the error */
  103844. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  103845. #if YYSTACKDEPTH<=0
  103846. int yystksz; /* Current side of the stack */
  103847. yyStackEntry *yystack; /* The parser's stack */
  103848. #else
  103849. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  103850. #endif
  103851. };
  103852. typedef struct yyParser yyParser;
  103853. #ifndef NDEBUG
  103854. /* #include <stdio.h> */
  103855. static FILE *yyTraceFILE = 0;
  103856. static char *yyTracePrompt = 0;
  103857. #endif /* NDEBUG */
  103858. #ifndef NDEBUG
  103859. /*
  103860. ** Turn parser tracing on by giving a stream to which to write the trace
  103861. ** and a prompt to preface each trace message. Tracing is turned off
  103862. ** by making either argument NULL
  103863. **
  103864. ** Inputs:
  103865. ** <ul>
  103866. ** <li> A FILE* to which trace output should be written.
  103867. ** If NULL, then tracing is turned off.
  103868. ** <li> A prefix string written at the beginning of every
  103869. ** line of trace output. If NULL, then tracing is
  103870. ** turned off.
  103871. ** </ul>
  103872. **
  103873. ** Outputs:
  103874. ** None.
  103875. */
  103876. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  103877. yyTraceFILE = TraceFILE;
  103878. yyTracePrompt = zTracePrompt;
  103879. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  103880. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  103881. }
  103882. #endif /* NDEBUG */
  103883. #ifndef NDEBUG
  103884. /* For tracing shifts, the names of all terminals and nonterminals
  103885. ** are required. The following table supplies these names */
  103886. static const char *const yyTokenName[] = {
  103887. "$", "SEMI", "EXPLAIN", "QUERY",
  103888. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  103889. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  103890. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  103891. "TABLE", "CREATE", "IF", "NOT",
  103892. "EXISTS", "TEMP", "LP", "RP",
  103893. "AS", "COMMA", "ID", "INDEXED",
  103894. "ABORT", "ACTION", "AFTER", "ANALYZE",
  103895. "ASC", "ATTACH", "BEFORE", "BY",
  103896. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  103897. "DATABASE", "DESC", "DETACH", "EACH",
  103898. "FAIL", "FOR", "IGNORE", "INITIALLY",
  103899. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  103900. "KEY", "OF", "OFFSET", "PRAGMA",
  103901. "RAISE", "REPLACE", "RESTRICT", "ROW",
  103902. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  103903. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  103904. "OR", "AND", "IS", "BETWEEN",
  103905. "IN", "ISNULL", "NOTNULL", "NE",
  103906. "EQ", "GT", "LE", "LT",
  103907. "GE", "ESCAPE", "BITAND", "BITOR",
  103908. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  103909. "STAR", "SLASH", "REM", "CONCAT",
  103910. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  103911. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  103912. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  103913. "ON", "INSERT", "DELETE", "UPDATE",
  103914. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  103915. "UNION", "ALL", "EXCEPT", "INTERSECT",
  103916. "SELECT", "DISTINCT", "DOT", "FROM",
  103917. "JOIN", "USING", "ORDER", "GROUP",
  103918. "HAVING", "LIMIT", "WHERE", "INTO",
  103919. "VALUES", "INTEGER", "FLOAT", "BLOB",
  103920. "REGISTER", "VARIABLE", "CASE", "WHEN",
  103921. "THEN", "ELSE", "INDEX", "ALTER",
  103922. "ADD", "error", "input", "cmdlist",
  103923. "ecmd", "explain", "cmdx", "cmd",
  103924. "transtype", "trans_opt", "nm", "savepoint_opt",
  103925. "create_table", "create_table_args", "createkw", "temp",
  103926. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  103927. "select", "column", "columnid", "type",
  103928. "carglist", "id", "ids", "typetoken",
  103929. "typename", "signed", "plus_num", "minus_num",
  103930. "ccons", "term", "expr", "onconf",
  103931. "sortorder", "autoinc", "idxlist_opt", "refargs",
  103932. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  103933. "conslist", "tconscomma", "tcons", "idxlist",
  103934. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  103935. "ifexists", "fullname", "oneselect", "multiselect_op",
  103936. "distinct", "selcollist", "from", "where_opt",
  103937. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  103938. "sclp", "as", "seltablist", "stl_prefix",
  103939. "joinop", "indexed_opt", "on_opt", "using_opt",
  103940. "joinop2", "inscollist", "sortlist", "nexprlist",
  103941. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  103942. "exprlist", "likeop", "between_op", "in_op",
  103943. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  103944. "collate", "nmnum", "number", "trigger_decl",
  103945. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  103946. "when_clause", "trigger_cmd", "trnm", "tridxby",
  103947. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  103948. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  103949. "lp", "anylist",
  103950. };
  103951. #endif /* NDEBUG */
  103952. #ifndef NDEBUG
  103953. /* For tracing reduce actions, the names of all rules are required.
  103954. */
  103955. static const char *const yyRuleName[] = {
  103956. /* 0 */ "input ::= cmdlist",
  103957. /* 1 */ "cmdlist ::= cmdlist ecmd",
  103958. /* 2 */ "cmdlist ::= ecmd",
  103959. /* 3 */ "ecmd ::= SEMI",
  103960. /* 4 */ "ecmd ::= explain cmdx SEMI",
  103961. /* 5 */ "explain ::=",
  103962. /* 6 */ "explain ::= EXPLAIN",
  103963. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  103964. /* 8 */ "cmdx ::= cmd",
  103965. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  103966. /* 10 */ "trans_opt ::=",
  103967. /* 11 */ "trans_opt ::= TRANSACTION",
  103968. /* 12 */ "trans_opt ::= TRANSACTION nm",
  103969. /* 13 */ "transtype ::=",
  103970. /* 14 */ "transtype ::= DEFERRED",
  103971. /* 15 */ "transtype ::= IMMEDIATE",
  103972. /* 16 */ "transtype ::= EXCLUSIVE",
  103973. /* 17 */ "cmd ::= COMMIT trans_opt",
  103974. /* 18 */ "cmd ::= END trans_opt",
  103975. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  103976. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  103977. /* 21 */ "savepoint_opt ::=",
  103978. /* 22 */ "cmd ::= SAVEPOINT nm",
  103979. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  103980. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  103981. /* 25 */ "cmd ::= create_table create_table_args",
  103982. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  103983. /* 27 */ "createkw ::= CREATE",
  103984. /* 28 */ "ifnotexists ::=",
  103985. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  103986. /* 30 */ "temp ::= TEMP",
  103987. /* 31 */ "temp ::=",
  103988. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  103989. /* 33 */ "create_table_args ::= AS select",
  103990. /* 34 */ "columnlist ::= columnlist COMMA column",
  103991. /* 35 */ "columnlist ::= column",
  103992. /* 36 */ "column ::= columnid type carglist",
  103993. /* 37 */ "columnid ::= nm",
  103994. /* 38 */ "id ::= ID",
  103995. /* 39 */ "id ::= INDEXED",
  103996. /* 40 */ "ids ::= ID|STRING",
  103997. /* 41 */ "nm ::= id",
  103998. /* 42 */ "nm ::= STRING",
  103999. /* 43 */ "nm ::= JOIN_KW",
  104000. /* 44 */ "type ::=",
  104001. /* 45 */ "type ::= typetoken",
  104002. /* 46 */ "typetoken ::= typename",
  104003. /* 47 */ "typetoken ::= typename LP signed RP",
  104004. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  104005. /* 49 */ "typename ::= ids",
  104006. /* 50 */ "typename ::= typename ids",
  104007. /* 51 */ "signed ::= plus_num",
  104008. /* 52 */ "signed ::= minus_num",
  104009. /* 53 */ "carglist ::= carglist ccons",
  104010. /* 54 */ "carglist ::=",
  104011. /* 55 */ "ccons ::= CONSTRAINT nm",
  104012. /* 56 */ "ccons ::= DEFAULT term",
  104013. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  104014. /* 58 */ "ccons ::= DEFAULT PLUS term",
  104015. /* 59 */ "ccons ::= DEFAULT MINUS term",
  104016. /* 60 */ "ccons ::= DEFAULT id",
  104017. /* 61 */ "ccons ::= NULL onconf",
  104018. /* 62 */ "ccons ::= NOT NULL onconf",
  104019. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  104020. /* 64 */ "ccons ::= UNIQUE onconf",
  104021. /* 65 */ "ccons ::= CHECK LP expr RP",
  104022. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  104023. /* 67 */ "ccons ::= defer_subclause",
  104024. /* 68 */ "ccons ::= COLLATE ids",
  104025. /* 69 */ "autoinc ::=",
  104026. /* 70 */ "autoinc ::= AUTOINCR",
  104027. /* 71 */ "refargs ::=",
  104028. /* 72 */ "refargs ::= refargs refarg",
  104029. /* 73 */ "refarg ::= MATCH nm",
  104030. /* 74 */ "refarg ::= ON INSERT refact",
  104031. /* 75 */ "refarg ::= ON DELETE refact",
  104032. /* 76 */ "refarg ::= ON UPDATE refact",
  104033. /* 77 */ "refact ::= SET NULL",
  104034. /* 78 */ "refact ::= SET DEFAULT",
  104035. /* 79 */ "refact ::= CASCADE",
  104036. /* 80 */ "refact ::= RESTRICT",
  104037. /* 81 */ "refact ::= NO ACTION",
  104038. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  104039. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  104040. /* 84 */ "init_deferred_pred_opt ::=",
  104041. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  104042. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  104043. /* 87 */ "conslist_opt ::=",
  104044. /* 88 */ "conslist_opt ::= COMMA conslist",
  104045. /* 89 */ "conslist ::= conslist tconscomma tcons",
  104046. /* 90 */ "conslist ::= tcons",
  104047. /* 91 */ "tconscomma ::= COMMA",
  104048. /* 92 */ "tconscomma ::=",
  104049. /* 93 */ "tcons ::= CONSTRAINT nm",
  104050. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  104051. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  104052. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  104053. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  104054. /* 98 */ "defer_subclause_opt ::=",
  104055. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  104056. /* 100 */ "onconf ::=",
  104057. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  104058. /* 102 */ "orconf ::=",
  104059. /* 103 */ "orconf ::= OR resolvetype",
  104060. /* 104 */ "resolvetype ::= raisetype",
  104061. /* 105 */ "resolvetype ::= IGNORE",
  104062. /* 106 */ "resolvetype ::= REPLACE",
  104063. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  104064. /* 108 */ "ifexists ::= IF EXISTS",
  104065. /* 109 */ "ifexists ::=",
  104066. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  104067. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  104068. /* 112 */ "cmd ::= select",
  104069. /* 113 */ "select ::= oneselect",
  104070. /* 114 */ "select ::= select multiselect_op oneselect",
  104071. /* 115 */ "multiselect_op ::= UNION",
  104072. /* 116 */ "multiselect_op ::= UNION ALL",
  104073. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  104074. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  104075. /* 119 */ "distinct ::= DISTINCT",
  104076. /* 120 */ "distinct ::= ALL",
  104077. /* 121 */ "distinct ::=",
  104078. /* 122 */ "sclp ::= selcollist COMMA",
  104079. /* 123 */ "sclp ::=",
  104080. /* 124 */ "selcollist ::= sclp expr as",
  104081. /* 125 */ "selcollist ::= sclp STAR",
  104082. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  104083. /* 127 */ "as ::= AS nm",
  104084. /* 128 */ "as ::= ids",
  104085. /* 129 */ "as ::=",
  104086. /* 130 */ "from ::=",
  104087. /* 131 */ "from ::= FROM seltablist",
  104088. /* 132 */ "stl_prefix ::= seltablist joinop",
  104089. /* 133 */ "stl_prefix ::=",
  104090. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  104091. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  104092. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  104093. /* 137 */ "dbnm ::=",
  104094. /* 138 */ "dbnm ::= DOT nm",
  104095. /* 139 */ "fullname ::= nm dbnm",
  104096. /* 140 */ "joinop ::= COMMA|JOIN",
  104097. /* 141 */ "joinop ::= JOIN_KW JOIN",
  104098. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  104099. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  104100. /* 144 */ "on_opt ::= ON expr",
  104101. /* 145 */ "on_opt ::=",
  104102. /* 146 */ "indexed_opt ::=",
  104103. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  104104. /* 148 */ "indexed_opt ::= NOT INDEXED",
  104105. /* 149 */ "using_opt ::= USING LP inscollist RP",
  104106. /* 150 */ "using_opt ::=",
  104107. /* 151 */ "orderby_opt ::=",
  104108. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  104109. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  104110. /* 154 */ "sortlist ::= expr sortorder",
  104111. /* 155 */ "sortorder ::= ASC",
  104112. /* 156 */ "sortorder ::= DESC",
  104113. /* 157 */ "sortorder ::=",
  104114. /* 158 */ "groupby_opt ::=",
  104115. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  104116. /* 160 */ "having_opt ::=",
  104117. /* 161 */ "having_opt ::= HAVING expr",
  104118. /* 162 */ "limit_opt ::=",
  104119. /* 163 */ "limit_opt ::= LIMIT expr",
  104120. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  104121. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  104122. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  104123. /* 167 */ "where_opt ::=",
  104124. /* 168 */ "where_opt ::= WHERE expr",
  104125. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  104126. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  104127. /* 171 */ "setlist ::= nm EQ expr",
  104128. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  104129. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  104130. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  104131. /* 175 */ "insert_cmd ::= INSERT orconf",
  104132. /* 176 */ "insert_cmd ::= REPLACE",
  104133. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  104134. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  104135. /* 179 */ "inscollist_opt ::=",
  104136. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  104137. /* 181 */ "inscollist ::= inscollist COMMA nm",
  104138. /* 182 */ "inscollist ::= nm",
  104139. /* 183 */ "expr ::= term",
  104140. /* 184 */ "expr ::= LP expr RP",
  104141. /* 185 */ "term ::= NULL",
  104142. /* 186 */ "expr ::= id",
  104143. /* 187 */ "expr ::= JOIN_KW",
  104144. /* 188 */ "expr ::= nm DOT nm",
  104145. /* 189 */ "expr ::= nm DOT nm DOT nm",
  104146. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  104147. /* 191 */ "term ::= STRING",
  104148. /* 192 */ "expr ::= REGISTER",
  104149. /* 193 */ "expr ::= VARIABLE",
  104150. /* 194 */ "expr ::= expr COLLATE ids",
  104151. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  104152. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  104153. /* 197 */ "expr ::= ID LP STAR RP",
  104154. /* 198 */ "term ::= CTIME_KW",
  104155. /* 199 */ "expr ::= expr AND expr",
  104156. /* 200 */ "expr ::= expr OR expr",
  104157. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  104158. /* 202 */ "expr ::= expr EQ|NE expr",
  104159. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  104160. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  104161. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  104162. /* 206 */ "expr ::= expr CONCAT expr",
  104163. /* 207 */ "likeop ::= LIKE_KW",
  104164. /* 208 */ "likeop ::= NOT LIKE_KW",
  104165. /* 209 */ "likeop ::= MATCH",
  104166. /* 210 */ "likeop ::= NOT MATCH",
  104167. /* 211 */ "expr ::= expr likeop expr",
  104168. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  104169. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  104170. /* 214 */ "expr ::= expr NOT NULL",
  104171. /* 215 */ "expr ::= expr IS expr",
  104172. /* 216 */ "expr ::= expr IS NOT expr",
  104173. /* 217 */ "expr ::= NOT expr",
  104174. /* 218 */ "expr ::= BITNOT expr",
  104175. /* 219 */ "expr ::= MINUS expr",
  104176. /* 220 */ "expr ::= PLUS expr",
  104177. /* 221 */ "between_op ::= BETWEEN",
  104178. /* 222 */ "between_op ::= NOT BETWEEN",
  104179. /* 223 */ "expr ::= expr between_op expr AND expr",
  104180. /* 224 */ "in_op ::= IN",
  104181. /* 225 */ "in_op ::= NOT IN",
  104182. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  104183. /* 227 */ "expr ::= LP select RP",
  104184. /* 228 */ "expr ::= expr in_op LP select RP",
  104185. /* 229 */ "expr ::= expr in_op nm dbnm",
  104186. /* 230 */ "expr ::= EXISTS LP select RP",
  104187. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  104188. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  104189. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  104190. /* 234 */ "case_else ::= ELSE expr",
  104191. /* 235 */ "case_else ::=",
  104192. /* 236 */ "case_operand ::= expr",
  104193. /* 237 */ "case_operand ::=",
  104194. /* 238 */ "exprlist ::= nexprlist",
  104195. /* 239 */ "exprlist ::=",
  104196. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  104197. /* 241 */ "nexprlist ::= expr",
  104198. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
  104199. /* 243 */ "uniqueflag ::= UNIQUE",
  104200. /* 244 */ "uniqueflag ::=",
  104201. /* 245 */ "idxlist_opt ::=",
  104202. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  104203. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  104204. /* 248 */ "idxlist ::= nm collate sortorder",
  104205. /* 249 */ "collate ::=",
  104206. /* 250 */ "collate ::= COLLATE ids",
  104207. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  104208. /* 252 */ "cmd ::= VACUUM",
  104209. /* 253 */ "cmd ::= VACUUM nm",
  104210. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  104211. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  104212. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  104213. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  104214. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  104215. /* 259 */ "nmnum ::= plus_num",
  104216. /* 260 */ "nmnum ::= nm",
  104217. /* 261 */ "nmnum ::= ON",
  104218. /* 262 */ "nmnum ::= DELETE",
  104219. /* 263 */ "nmnum ::= DEFAULT",
  104220. /* 264 */ "plus_num ::= PLUS number",
  104221. /* 265 */ "plus_num ::= number",
  104222. /* 266 */ "minus_num ::= MINUS number",
  104223. /* 267 */ "number ::= INTEGER|FLOAT",
  104224. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  104225. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  104226. /* 270 */ "trigger_time ::= BEFORE",
  104227. /* 271 */ "trigger_time ::= AFTER",
  104228. /* 272 */ "trigger_time ::= INSTEAD OF",
  104229. /* 273 */ "trigger_time ::=",
  104230. /* 274 */ "trigger_event ::= DELETE|INSERT",
  104231. /* 275 */ "trigger_event ::= UPDATE",
  104232. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  104233. /* 277 */ "foreach_clause ::=",
  104234. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  104235. /* 279 */ "when_clause ::=",
  104236. /* 280 */ "when_clause ::= WHEN expr",
  104237. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  104238. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  104239. /* 283 */ "trnm ::= nm",
  104240. /* 284 */ "trnm ::= nm DOT nm",
  104241. /* 285 */ "tridxby ::=",
  104242. /* 286 */ "tridxby ::= INDEXED BY nm",
  104243. /* 287 */ "tridxby ::= NOT INDEXED",
  104244. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  104245. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  104246. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  104247. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  104248. /* 292 */ "trigger_cmd ::= select",
  104249. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  104250. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  104251. /* 295 */ "raisetype ::= ROLLBACK",
  104252. /* 296 */ "raisetype ::= ABORT",
  104253. /* 297 */ "raisetype ::= FAIL",
  104254. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  104255. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  104256. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  104257. /* 301 */ "key_opt ::=",
  104258. /* 302 */ "key_opt ::= KEY expr",
  104259. /* 303 */ "database_kw_opt ::= DATABASE",
  104260. /* 304 */ "database_kw_opt ::=",
  104261. /* 305 */ "cmd ::= REINDEX",
  104262. /* 306 */ "cmd ::= REINDEX nm dbnm",
  104263. /* 307 */ "cmd ::= ANALYZE",
  104264. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  104265. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  104266. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  104267. /* 311 */ "add_column_fullname ::= fullname",
  104268. /* 312 */ "kwcolumn_opt ::=",
  104269. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  104270. /* 314 */ "cmd ::= create_vtab",
  104271. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  104272. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  104273. /* 317 */ "vtabarglist ::= vtabarg",
  104274. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  104275. /* 319 */ "vtabarg ::=",
  104276. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  104277. /* 321 */ "vtabargtoken ::= ANY",
  104278. /* 322 */ "vtabargtoken ::= lp anylist RP",
  104279. /* 323 */ "lp ::= LP",
  104280. /* 324 */ "anylist ::=",
  104281. /* 325 */ "anylist ::= anylist LP anylist RP",
  104282. /* 326 */ "anylist ::= anylist ANY",
  104283. };
  104284. #endif /* NDEBUG */
  104285. #if YYSTACKDEPTH<=0
  104286. /*
  104287. ** Try to increase the size of the parser stack.
  104288. */
  104289. static void yyGrowStack(yyParser *p){
  104290. int newSize;
  104291. yyStackEntry *pNew;
  104292. newSize = p->yystksz*2 + 100;
  104293. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  104294. if( pNew ){
  104295. p->yystack = pNew;
  104296. p->yystksz = newSize;
  104297. #ifndef NDEBUG
  104298. if( yyTraceFILE ){
  104299. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  104300. yyTracePrompt, p->yystksz);
  104301. }
  104302. #endif
  104303. }
  104304. }
  104305. #endif
  104306. /*
  104307. ** This function allocates a new parser.
  104308. ** The only argument is a pointer to a function which works like
  104309. ** malloc.
  104310. **
  104311. ** Inputs:
  104312. ** A pointer to the function used to allocate memory.
  104313. **
  104314. ** Outputs:
  104315. ** A pointer to a parser. This pointer is used in subsequent calls
  104316. ** to sqlite3Parser and sqlite3ParserFree.
  104317. */
  104318. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  104319. yyParser *pParser;
  104320. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  104321. if( pParser ){
  104322. pParser->yyidx = -1;
  104323. #ifdef YYTRACKMAXSTACKDEPTH
  104324. pParser->yyidxMax = 0;
  104325. #endif
  104326. #if YYSTACKDEPTH<=0
  104327. pParser->yystack = NULL;
  104328. pParser->yystksz = 0;
  104329. yyGrowStack(pParser);
  104330. #endif
  104331. }
  104332. return pParser;
  104333. }
  104334. /* The following function deletes the value associated with a
  104335. ** symbol. The symbol can be either a terminal or nonterminal.
  104336. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  104337. ** the value.
  104338. */
  104339. static void yy_destructor(
  104340. yyParser *yypParser, /* The parser */
  104341. YYCODETYPE yymajor, /* Type code for object to destroy */
  104342. YYMINORTYPE *yypminor /* The object to be destroyed */
  104343. ){
  104344. sqlite3ParserARG_FETCH;
  104345. switch( yymajor ){
  104346. /* Here is inserted the actions which take place when a
  104347. ** terminal or non-terminal is destroyed. This can happen
  104348. ** when the symbol is popped from the stack during a
  104349. ** reduce or during error processing or when a parser is
  104350. ** being destroyed before it is finished parsing.
  104351. **
  104352. ** Note: during a reduce, the only symbols destroyed are those
  104353. ** which appear on the RHS of the rule, but which are not used
  104354. ** inside the C code.
  104355. */
  104356. case 160: /* select */
  104357. case 194: /* oneselect */
  104358. {
  104359. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  104360. }
  104361. break;
  104362. case 173: /* term */
  104363. case 174: /* expr */
  104364. {
  104365. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  104366. }
  104367. break;
  104368. case 178: /* idxlist_opt */
  104369. case 187: /* idxlist */
  104370. case 197: /* selcollist */
  104371. case 200: /* groupby_opt */
  104372. case 202: /* orderby_opt */
  104373. case 204: /* sclp */
  104374. case 214: /* sortlist */
  104375. case 215: /* nexprlist */
  104376. case 216: /* setlist */
  104377. case 220: /* exprlist */
  104378. case 225: /* case_exprlist */
  104379. {
  104380. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  104381. }
  104382. break;
  104383. case 193: /* fullname */
  104384. case 198: /* from */
  104385. case 206: /* seltablist */
  104386. case 207: /* stl_prefix */
  104387. {
  104388. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  104389. }
  104390. break;
  104391. case 199: /* where_opt */
  104392. case 201: /* having_opt */
  104393. case 210: /* on_opt */
  104394. case 224: /* case_operand */
  104395. case 226: /* case_else */
  104396. case 236: /* when_clause */
  104397. case 241: /* key_opt */
  104398. {
  104399. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  104400. }
  104401. break;
  104402. case 211: /* using_opt */
  104403. case 213: /* inscollist */
  104404. case 218: /* inscollist_opt */
  104405. {
  104406. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  104407. }
  104408. break;
  104409. case 219: /* valuelist */
  104410. {
  104411. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  104412. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  104413. }
  104414. break;
  104415. case 232: /* trigger_cmd_list */
  104416. case 237: /* trigger_cmd */
  104417. {
  104418. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  104419. }
  104420. break;
  104421. case 234: /* trigger_event */
  104422. {
  104423. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  104424. }
  104425. break;
  104426. default: break; /* If no destructor action specified: do nothing */
  104427. }
  104428. }
  104429. /*
  104430. ** Pop the parser's stack once.
  104431. **
  104432. ** If there is a destructor routine associated with the token which
  104433. ** is popped from the stack, then call it.
  104434. **
  104435. ** Return the major token number for the symbol popped.
  104436. */
  104437. static int yy_pop_parser_stack(yyParser *pParser){
  104438. YYCODETYPE yymajor;
  104439. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  104440. /* There is no mechanism by which the parser stack can be popped below
  104441. ** empty in SQLite. */
  104442. if( NEVER(pParser->yyidx<0) ) return 0;
  104443. #ifndef NDEBUG
  104444. if( yyTraceFILE && pParser->yyidx>=0 ){
  104445. fprintf(yyTraceFILE,"%sPopping %s\n",
  104446. yyTracePrompt,
  104447. yyTokenName[yytos->major]);
  104448. }
  104449. #endif
  104450. yymajor = yytos->major;
  104451. yy_destructor(pParser, yymajor, &yytos->minor);
  104452. pParser->yyidx--;
  104453. return yymajor;
  104454. }
  104455. /*
  104456. ** Deallocate and destroy a parser. Destructors are all called for
  104457. ** all stack elements before shutting the parser down.
  104458. **
  104459. ** Inputs:
  104460. ** <ul>
  104461. ** <li> A pointer to the parser. This should be a pointer
  104462. ** obtained from sqlite3ParserAlloc.
  104463. ** <li> A pointer to a function used to reclaim memory obtained
  104464. ** from malloc.
  104465. ** </ul>
  104466. */
  104467. SQLITE_PRIVATE void sqlite3ParserFree(
  104468. void *p, /* The parser to be deleted */
  104469. void (*freeProc)(void*) /* Function used to reclaim memory */
  104470. ){
  104471. yyParser *pParser = (yyParser*)p;
  104472. /* In SQLite, we never try to destroy a parser that was not successfully
  104473. ** created in the first place. */
  104474. if( NEVER(pParser==0) ) return;
  104475. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  104476. #if YYSTACKDEPTH<=0
  104477. free(pParser->yystack);
  104478. #endif
  104479. (*freeProc)((void*)pParser);
  104480. }
  104481. /*
  104482. ** Return the peak depth of the stack for a parser.
  104483. */
  104484. #ifdef YYTRACKMAXSTACKDEPTH
  104485. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  104486. yyParser *pParser = (yyParser*)p;
  104487. return pParser->yyidxMax;
  104488. }
  104489. #endif
  104490. /*
  104491. ** Find the appropriate action for a parser given the terminal
  104492. ** look-ahead token iLookAhead.
  104493. **
  104494. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  104495. ** independent of the look-ahead. If it is, return the action, otherwise
  104496. ** return YY_NO_ACTION.
  104497. */
  104498. static int yy_find_shift_action(
  104499. yyParser *pParser, /* The parser */
  104500. YYCODETYPE iLookAhead /* The look-ahead token */
  104501. ){
  104502. int i;
  104503. int stateno = pParser->yystack[pParser->yyidx].stateno;
  104504. if( stateno>YY_SHIFT_COUNT
  104505. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  104506. return yy_default[stateno];
  104507. }
  104508. assert( iLookAhead!=YYNOCODE );
  104509. i += iLookAhead;
  104510. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  104511. if( iLookAhead>0 ){
  104512. #ifdef YYFALLBACK
  104513. YYCODETYPE iFallback; /* Fallback token */
  104514. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  104515. && (iFallback = yyFallback[iLookAhead])!=0 ){
  104516. #ifndef NDEBUG
  104517. if( yyTraceFILE ){
  104518. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  104519. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  104520. }
  104521. #endif
  104522. return yy_find_shift_action(pParser, iFallback);
  104523. }
  104524. #endif
  104525. #ifdef YYWILDCARD
  104526. {
  104527. int j = i - iLookAhead + YYWILDCARD;
  104528. if(
  104529. #if YY_SHIFT_MIN+YYWILDCARD<0
  104530. j>=0 &&
  104531. #endif
  104532. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  104533. j<YY_ACTTAB_COUNT &&
  104534. #endif
  104535. yy_lookahead[j]==YYWILDCARD
  104536. ){
  104537. #ifndef NDEBUG
  104538. if( yyTraceFILE ){
  104539. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  104540. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  104541. }
  104542. #endif /* NDEBUG */
  104543. return yy_action[j];
  104544. }
  104545. }
  104546. #endif /* YYWILDCARD */
  104547. }
  104548. return yy_default[stateno];
  104549. }else{
  104550. return yy_action[i];
  104551. }
  104552. }
  104553. /*
  104554. ** Find the appropriate action for a parser given the non-terminal
  104555. ** look-ahead token iLookAhead.
  104556. **
  104557. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  104558. ** independent of the look-ahead. If it is, return the action, otherwise
  104559. ** return YY_NO_ACTION.
  104560. */
  104561. static int yy_find_reduce_action(
  104562. int stateno, /* Current state number */
  104563. YYCODETYPE iLookAhead /* The look-ahead token */
  104564. ){
  104565. int i;
  104566. #ifdef YYERRORSYMBOL
  104567. if( stateno>YY_REDUCE_COUNT ){
  104568. return yy_default[stateno];
  104569. }
  104570. #else
  104571. assert( stateno<=YY_REDUCE_COUNT );
  104572. #endif
  104573. i = yy_reduce_ofst[stateno];
  104574. assert( i!=YY_REDUCE_USE_DFLT );
  104575. assert( iLookAhead!=YYNOCODE );
  104576. i += iLookAhead;
  104577. #ifdef YYERRORSYMBOL
  104578. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  104579. return yy_default[stateno];
  104580. }
  104581. #else
  104582. assert( i>=0 && i<YY_ACTTAB_COUNT );
  104583. assert( yy_lookahead[i]==iLookAhead );
  104584. #endif
  104585. return yy_action[i];
  104586. }
  104587. /*
  104588. ** The following routine is called if the stack overflows.
  104589. */
  104590. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  104591. sqlite3ParserARG_FETCH;
  104592. yypParser->yyidx--;
  104593. #ifndef NDEBUG
  104594. if( yyTraceFILE ){
  104595. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  104596. }
  104597. #endif
  104598. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  104599. /* Here code is inserted which will execute if the parser
  104600. ** stack every overflows */
  104601. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  104602. sqlite3ErrorMsg(pParse, "parser stack overflow");
  104603. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  104604. }
  104605. /*
  104606. ** Perform a shift action.
  104607. */
  104608. static void yy_shift(
  104609. yyParser *yypParser, /* The parser to be shifted */
  104610. int yyNewState, /* The new state to shift in */
  104611. int yyMajor, /* The major token to shift in */
  104612. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  104613. ){
  104614. yyStackEntry *yytos;
  104615. yypParser->yyidx++;
  104616. #ifdef YYTRACKMAXSTACKDEPTH
  104617. if( yypParser->yyidx>yypParser->yyidxMax ){
  104618. yypParser->yyidxMax = yypParser->yyidx;
  104619. }
  104620. #endif
  104621. #if YYSTACKDEPTH>0
  104622. if( yypParser->yyidx>=YYSTACKDEPTH ){
  104623. yyStackOverflow(yypParser, yypMinor);
  104624. return;
  104625. }
  104626. #else
  104627. if( yypParser->yyidx>=yypParser->yystksz ){
  104628. yyGrowStack(yypParser);
  104629. if( yypParser->yyidx>=yypParser->yystksz ){
  104630. yyStackOverflow(yypParser, yypMinor);
  104631. return;
  104632. }
  104633. }
  104634. #endif
  104635. yytos = &yypParser->yystack[yypParser->yyidx];
  104636. yytos->stateno = (YYACTIONTYPE)yyNewState;
  104637. yytos->major = (YYCODETYPE)yyMajor;
  104638. yytos->minor = *yypMinor;
  104639. #ifndef NDEBUG
  104640. if( yyTraceFILE && yypParser->yyidx>0 ){
  104641. int i;
  104642. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  104643. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  104644. for(i=1; i<=yypParser->yyidx; i++)
  104645. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  104646. fprintf(yyTraceFILE,"\n");
  104647. }
  104648. #endif
  104649. }
  104650. /* The following table contains information about every rule that
  104651. ** is used during the reduce.
  104652. */
  104653. static const struct {
  104654. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  104655. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  104656. } yyRuleInfo[] = {
  104657. { 142, 1 },
  104658. { 143, 2 },
  104659. { 143, 1 },
  104660. { 144, 1 },
  104661. { 144, 3 },
  104662. { 145, 0 },
  104663. { 145, 1 },
  104664. { 145, 3 },
  104665. { 146, 1 },
  104666. { 147, 3 },
  104667. { 149, 0 },
  104668. { 149, 1 },
  104669. { 149, 2 },
  104670. { 148, 0 },
  104671. { 148, 1 },
  104672. { 148, 1 },
  104673. { 148, 1 },
  104674. { 147, 2 },
  104675. { 147, 2 },
  104676. { 147, 2 },
  104677. { 151, 1 },
  104678. { 151, 0 },
  104679. { 147, 2 },
  104680. { 147, 3 },
  104681. { 147, 5 },
  104682. { 147, 2 },
  104683. { 152, 6 },
  104684. { 154, 1 },
  104685. { 156, 0 },
  104686. { 156, 3 },
  104687. { 155, 1 },
  104688. { 155, 0 },
  104689. { 153, 4 },
  104690. { 153, 2 },
  104691. { 158, 3 },
  104692. { 158, 1 },
  104693. { 161, 3 },
  104694. { 162, 1 },
  104695. { 165, 1 },
  104696. { 165, 1 },
  104697. { 166, 1 },
  104698. { 150, 1 },
  104699. { 150, 1 },
  104700. { 150, 1 },
  104701. { 163, 0 },
  104702. { 163, 1 },
  104703. { 167, 1 },
  104704. { 167, 4 },
  104705. { 167, 6 },
  104706. { 168, 1 },
  104707. { 168, 2 },
  104708. { 169, 1 },
  104709. { 169, 1 },
  104710. { 164, 2 },
  104711. { 164, 0 },
  104712. { 172, 2 },
  104713. { 172, 2 },
  104714. { 172, 4 },
  104715. { 172, 3 },
  104716. { 172, 3 },
  104717. { 172, 2 },
  104718. { 172, 2 },
  104719. { 172, 3 },
  104720. { 172, 5 },
  104721. { 172, 2 },
  104722. { 172, 4 },
  104723. { 172, 4 },
  104724. { 172, 1 },
  104725. { 172, 2 },
  104726. { 177, 0 },
  104727. { 177, 1 },
  104728. { 179, 0 },
  104729. { 179, 2 },
  104730. { 181, 2 },
  104731. { 181, 3 },
  104732. { 181, 3 },
  104733. { 181, 3 },
  104734. { 182, 2 },
  104735. { 182, 2 },
  104736. { 182, 1 },
  104737. { 182, 1 },
  104738. { 182, 2 },
  104739. { 180, 3 },
  104740. { 180, 2 },
  104741. { 183, 0 },
  104742. { 183, 2 },
  104743. { 183, 2 },
  104744. { 159, 0 },
  104745. { 159, 2 },
  104746. { 184, 3 },
  104747. { 184, 1 },
  104748. { 185, 1 },
  104749. { 185, 0 },
  104750. { 186, 2 },
  104751. { 186, 7 },
  104752. { 186, 5 },
  104753. { 186, 5 },
  104754. { 186, 10 },
  104755. { 188, 0 },
  104756. { 188, 1 },
  104757. { 175, 0 },
  104758. { 175, 3 },
  104759. { 189, 0 },
  104760. { 189, 2 },
  104761. { 190, 1 },
  104762. { 190, 1 },
  104763. { 190, 1 },
  104764. { 147, 4 },
  104765. { 192, 2 },
  104766. { 192, 0 },
  104767. { 147, 8 },
  104768. { 147, 4 },
  104769. { 147, 1 },
  104770. { 160, 1 },
  104771. { 160, 3 },
  104772. { 195, 1 },
  104773. { 195, 2 },
  104774. { 195, 1 },
  104775. { 194, 9 },
  104776. { 196, 1 },
  104777. { 196, 1 },
  104778. { 196, 0 },
  104779. { 204, 2 },
  104780. { 204, 0 },
  104781. { 197, 3 },
  104782. { 197, 2 },
  104783. { 197, 4 },
  104784. { 205, 2 },
  104785. { 205, 1 },
  104786. { 205, 0 },
  104787. { 198, 0 },
  104788. { 198, 2 },
  104789. { 207, 2 },
  104790. { 207, 0 },
  104791. { 206, 7 },
  104792. { 206, 7 },
  104793. { 206, 7 },
  104794. { 157, 0 },
  104795. { 157, 2 },
  104796. { 193, 2 },
  104797. { 208, 1 },
  104798. { 208, 2 },
  104799. { 208, 3 },
  104800. { 208, 4 },
  104801. { 210, 2 },
  104802. { 210, 0 },
  104803. { 209, 0 },
  104804. { 209, 3 },
  104805. { 209, 2 },
  104806. { 211, 4 },
  104807. { 211, 0 },
  104808. { 202, 0 },
  104809. { 202, 3 },
  104810. { 214, 4 },
  104811. { 214, 2 },
  104812. { 176, 1 },
  104813. { 176, 1 },
  104814. { 176, 0 },
  104815. { 200, 0 },
  104816. { 200, 3 },
  104817. { 201, 0 },
  104818. { 201, 2 },
  104819. { 203, 0 },
  104820. { 203, 2 },
  104821. { 203, 4 },
  104822. { 203, 4 },
  104823. { 147, 5 },
  104824. { 199, 0 },
  104825. { 199, 2 },
  104826. { 147, 7 },
  104827. { 216, 5 },
  104828. { 216, 3 },
  104829. { 147, 5 },
  104830. { 147, 5 },
  104831. { 147, 6 },
  104832. { 217, 2 },
  104833. { 217, 1 },
  104834. { 219, 4 },
  104835. { 219, 5 },
  104836. { 218, 0 },
  104837. { 218, 3 },
  104838. { 213, 3 },
  104839. { 213, 1 },
  104840. { 174, 1 },
  104841. { 174, 3 },
  104842. { 173, 1 },
  104843. { 174, 1 },
  104844. { 174, 1 },
  104845. { 174, 3 },
  104846. { 174, 5 },
  104847. { 173, 1 },
  104848. { 173, 1 },
  104849. { 174, 1 },
  104850. { 174, 1 },
  104851. { 174, 3 },
  104852. { 174, 6 },
  104853. { 174, 5 },
  104854. { 174, 4 },
  104855. { 173, 1 },
  104856. { 174, 3 },
  104857. { 174, 3 },
  104858. { 174, 3 },
  104859. { 174, 3 },
  104860. { 174, 3 },
  104861. { 174, 3 },
  104862. { 174, 3 },
  104863. { 174, 3 },
  104864. { 221, 1 },
  104865. { 221, 2 },
  104866. { 221, 1 },
  104867. { 221, 2 },
  104868. { 174, 3 },
  104869. { 174, 5 },
  104870. { 174, 2 },
  104871. { 174, 3 },
  104872. { 174, 3 },
  104873. { 174, 4 },
  104874. { 174, 2 },
  104875. { 174, 2 },
  104876. { 174, 2 },
  104877. { 174, 2 },
  104878. { 222, 1 },
  104879. { 222, 2 },
  104880. { 174, 5 },
  104881. { 223, 1 },
  104882. { 223, 2 },
  104883. { 174, 5 },
  104884. { 174, 3 },
  104885. { 174, 5 },
  104886. { 174, 4 },
  104887. { 174, 4 },
  104888. { 174, 5 },
  104889. { 225, 5 },
  104890. { 225, 4 },
  104891. { 226, 2 },
  104892. { 226, 0 },
  104893. { 224, 1 },
  104894. { 224, 0 },
  104895. { 220, 1 },
  104896. { 220, 0 },
  104897. { 215, 3 },
  104898. { 215, 1 },
  104899. { 147, 11 },
  104900. { 227, 1 },
  104901. { 227, 0 },
  104902. { 178, 0 },
  104903. { 178, 3 },
  104904. { 187, 5 },
  104905. { 187, 3 },
  104906. { 228, 0 },
  104907. { 228, 2 },
  104908. { 147, 4 },
  104909. { 147, 1 },
  104910. { 147, 2 },
  104911. { 147, 3 },
  104912. { 147, 5 },
  104913. { 147, 6 },
  104914. { 147, 5 },
  104915. { 147, 6 },
  104916. { 229, 1 },
  104917. { 229, 1 },
  104918. { 229, 1 },
  104919. { 229, 1 },
  104920. { 229, 1 },
  104921. { 170, 2 },
  104922. { 170, 1 },
  104923. { 171, 2 },
  104924. { 230, 1 },
  104925. { 147, 5 },
  104926. { 231, 11 },
  104927. { 233, 1 },
  104928. { 233, 1 },
  104929. { 233, 2 },
  104930. { 233, 0 },
  104931. { 234, 1 },
  104932. { 234, 1 },
  104933. { 234, 3 },
  104934. { 235, 0 },
  104935. { 235, 3 },
  104936. { 236, 0 },
  104937. { 236, 2 },
  104938. { 232, 3 },
  104939. { 232, 2 },
  104940. { 238, 1 },
  104941. { 238, 3 },
  104942. { 239, 0 },
  104943. { 239, 3 },
  104944. { 239, 2 },
  104945. { 237, 7 },
  104946. { 237, 5 },
  104947. { 237, 5 },
  104948. { 237, 5 },
  104949. { 237, 1 },
  104950. { 174, 4 },
  104951. { 174, 6 },
  104952. { 191, 1 },
  104953. { 191, 1 },
  104954. { 191, 1 },
  104955. { 147, 4 },
  104956. { 147, 6 },
  104957. { 147, 3 },
  104958. { 241, 0 },
  104959. { 241, 2 },
  104960. { 240, 1 },
  104961. { 240, 0 },
  104962. { 147, 1 },
  104963. { 147, 3 },
  104964. { 147, 1 },
  104965. { 147, 3 },
  104966. { 147, 6 },
  104967. { 147, 6 },
  104968. { 242, 1 },
  104969. { 243, 0 },
  104970. { 243, 1 },
  104971. { 147, 1 },
  104972. { 147, 4 },
  104973. { 244, 8 },
  104974. { 245, 1 },
  104975. { 245, 3 },
  104976. { 246, 0 },
  104977. { 246, 2 },
  104978. { 247, 1 },
  104979. { 247, 3 },
  104980. { 248, 1 },
  104981. { 249, 0 },
  104982. { 249, 4 },
  104983. { 249, 2 },
  104984. };
  104985. static void yy_accept(yyParser*); /* Forward Declaration */
  104986. /*
  104987. ** Perform a reduce action and the shift that must immediately
  104988. ** follow the reduce.
  104989. */
  104990. static void yy_reduce(
  104991. yyParser *yypParser, /* The parser */
  104992. int yyruleno /* Number of the rule by which to reduce */
  104993. ){
  104994. int yygoto; /* The next state */
  104995. int yyact; /* The next action */
  104996. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  104997. yyStackEntry *yymsp; /* The top of the parser's stack */
  104998. int yysize; /* Amount to pop the stack */
  104999. sqlite3ParserARG_FETCH;
  105000. yymsp = &yypParser->yystack[yypParser->yyidx];
  105001. #ifndef NDEBUG
  105002. if( yyTraceFILE && yyruleno>=0
  105003. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  105004. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  105005. yyRuleName[yyruleno]);
  105006. }
  105007. #endif /* NDEBUG */
  105008. /* Silence complaints from purify about yygotominor being uninitialized
  105009. ** in some cases when it is copied into the stack after the following
  105010. ** switch. yygotominor is uninitialized when a rule reduces that does
  105011. ** not set the value of its left-hand side nonterminal. Leaving the
  105012. ** value of the nonterminal uninitialized is utterly harmless as long
  105013. ** as the value is never used. So really the only thing this code
  105014. ** accomplishes is to quieten purify.
  105015. **
  105016. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  105017. ** without this code, their parser segfaults. I'm not sure what there
  105018. ** parser is doing to make this happen. This is the second bug report
  105019. ** from wireshark this week. Clearly they are stressing Lemon in ways
  105020. ** that it has not been previously stressed... (SQLite ticket #2172)
  105021. */
  105022. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  105023. yygotominor = yyzerominor;
  105024. switch( yyruleno ){
  105025. /* Beginning here are the reduction cases. A typical example
  105026. ** follows:
  105027. ** case 0:
  105028. ** #line <lineno> <grammarfile>
  105029. ** { ... } // User supplied code
  105030. ** #line <lineno> <thisfile>
  105031. ** break;
  105032. */
  105033. case 5: /* explain ::= */
  105034. { sqlite3BeginParse(pParse, 0); }
  105035. break;
  105036. case 6: /* explain ::= EXPLAIN */
  105037. { sqlite3BeginParse(pParse, 1); }
  105038. break;
  105039. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  105040. { sqlite3BeginParse(pParse, 2); }
  105041. break;
  105042. case 8: /* cmdx ::= cmd */
  105043. { sqlite3FinishCoding(pParse); }
  105044. break;
  105045. case 9: /* cmd ::= BEGIN transtype trans_opt */
  105046. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  105047. break;
  105048. case 13: /* transtype ::= */
  105049. {yygotominor.yy392 = TK_DEFERRED;}
  105050. break;
  105051. case 14: /* transtype ::= DEFERRED */
  105052. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  105053. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  105054. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  105055. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  105056. {yygotominor.yy392 = yymsp[0].major;}
  105057. break;
  105058. case 17: /* cmd ::= COMMIT trans_opt */
  105059. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  105060. {sqlite3CommitTransaction(pParse);}
  105061. break;
  105062. case 19: /* cmd ::= ROLLBACK trans_opt */
  105063. {sqlite3RollbackTransaction(pParse);}
  105064. break;
  105065. case 22: /* cmd ::= SAVEPOINT nm */
  105066. {
  105067. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  105068. }
  105069. break;
  105070. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  105071. {
  105072. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  105073. }
  105074. break;
  105075. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  105076. {
  105077. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  105078. }
  105079. break;
  105080. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  105081. {
  105082. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  105083. }
  105084. break;
  105085. case 27: /* createkw ::= CREATE */
  105086. {
  105087. pParse->db->lookaside.bEnabled = 0;
  105088. yygotominor.yy0 = yymsp[0].minor.yy0;
  105089. }
  105090. break;
  105091. case 28: /* ifnotexists ::= */
  105092. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  105093. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  105094. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  105095. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  105096. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  105097. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  105098. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  105099. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  105100. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  105101. {yygotominor.yy392 = 0;}
  105102. break;
  105103. case 29: /* ifnotexists ::= IF NOT EXISTS */
  105104. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  105105. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  105106. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  105107. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  105108. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  105109. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  105110. {yygotominor.yy392 = 1;}
  105111. break;
  105112. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  105113. {
  105114. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  105115. }
  105116. break;
  105117. case 33: /* create_table_args ::= AS select */
  105118. {
  105119. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  105120. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  105121. }
  105122. break;
  105123. case 36: /* column ::= columnid type carglist */
  105124. {
  105125. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  105126. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  105127. }
  105128. break;
  105129. case 37: /* columnid ::= nm */
  105130. {
  105131. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  105132. yygotominor.yy0 = yymsp[0].minor.yy0;
  105133. pParse->constraintName.n = 0;
  105134. }
  105135. break;
  105136. case 38: /* id ::= ID */
  105137. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  105138. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  105139. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  105140. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  105141. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  105142. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  105143. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  105144. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  105145. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  105146. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  105147. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  105148. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  105149. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  105150. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  105151. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  105152. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  105153. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  105154. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  105155. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  105156. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  105157. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  105158. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  105159. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  105160. break;
  105161. case 45: /* type ::= typetoken */
  105162. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  105163. break;
  105164. case 47: /* typetoken ::= typename LP signed RP */
  105165. {
  105166. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  105167. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  105168. }
  105169. break;
  105170. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  105171. {
  105172. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  105173. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  105174. }
  105175. break;
  105176. case 50: /* typename ::= typename ids */
  105177. {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);}
  105178. break;
  105179. case 55: /* ccons ::= CONSTRAINT nm */
  105180. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  105181. {pParse->constraintName = yymsp[0].minor.yy0;}
  105182. break;
  105183. case 56: /* ccons ::= DEFAULT term */
  105184. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  105185. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  105186. break;
  105187. case 57: /* ccons ::= DEFAULT LP expr RP */
  105188. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  105189. break;
  105190. case 59: /* ccons ::= DEFAULT MINUS term */
  105191. {
  105192. ExprSpan v;
  105193. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  105194. v.zStart = yymsp[-1].minor.yy0.z;
  105195. v.zEnd = yymsp[0].minor.yy342.zEnd;
  105196. sqlite3AddDefaultValue(pParse,&v);
  105197. }
  105198. break;
  105199. case 60: /* ccons ::= DEFAULT id */
  105200. {
  105201. ExprSpan v;
  105202. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  105203. sqlite3AddDefaultValue(pParse,&v);
  105204. }
  105205. break;
  105206. case 62: /* ccons ::= NOT NULL onconf */
  105207. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  105208. break;
  105209. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  105210. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  105211. break;
  105212. case 64: /* ccons ::= UNIQUE onconf */
  105213. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  105214. break;
  105215. case 65: /* ccons ::= CHECK LP expr RP */
  105216. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  105217. break;
  105218. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  105219. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  105220. break;
  105221. case 67: /* ccons ::= defer_subclause */
  105222. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  105223. break;
  105224. case 68: /* ccons ::= COLLATE ids */
  105225. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  105226. break;
  105227. case 71: /* refargs ::= */
  105228. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  105229. break;
  105230. case 72: /* refargs ::= refargs refarg */
  105231. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  105232. break;
  105233. case 73: /* refarg ::= MATCH nm */
  105234. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  105235. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  105236. break;
  105237. case 75: /* refarg ::= ON DELETE refact */
  105238. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  105239. break;
  105240. case 76: /* refarg ::= ON UPDATE refact */
  105241. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  105242. break;
  105243. case 77: /* refact ::= SET NULL */
  105244. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  105245. break;
  105246. case 78: /* refact ::= SET DEFAULT */
  105247. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  105248. break;
  105249. case 79: /* refact ::= CASCADE */
  105250. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  105251. break;
  105252. case 80: /* refact ::= RESTRICT */
  105253. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  105254. break;
  105255. case 81: /* refact ::= NO ACTION */
  105256. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  105257. break;
  105258. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  105259. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  105260. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  105261. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  105262. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  105263. break;
  105264. case 87: /* conslist_opt ::= */
  105265. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  105266. break;
  105267. case 88: /* conslist_opt ::= COMMA conslist */
  105268. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  105269. break;
  105270. case 91: /* tconscomma ::= COMMA */
  105271. {pParse->constraintName.n = 0;}
  105272. break;
  105273. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  105274. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  105275. break;
  105276. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  105277. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  105278. break;
  105279. case 96: /* tcons ::= CHECK LP expr RP onconf */
  105280. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  105281. break;
  105282. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  105283. {
  105284. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  105285. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  105286. }
  105287. break;
  105288. case 100: /* onconf ::= */
  105289. {yygotominor.yy392 = OE_Default;}
  105290. break;
  105291. case 102: /* orconf ::= */
  105292. {yygotominor.yy258 = OE_Default;}
  105293. break;
  105294. case 103: /* orconf ::= OR resolvetype */
  105295. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  105296. break;
  105297. case 105: /* resolvetype ::= IGNORE */
  105298. {yygotominor.yy392 = OE_Ignore;}
  105299. break;
  105300. case 106: /* resolvetype ::= REPLACE */
  105301. {yygotominor.yy392 = OE_Replace;}
  105302. break;
  105303. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  105304. {
  105305. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  105306. }
  105307. break;
  105308. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  105309. {
  105310. 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);
  105311. }
  105312. break;
  105313. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  105314. {
  105315. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  105316. }
  105317. break;
  105318. case 112: /* cmd ::= select */
  105319. {
  105320. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  105321. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  105322. sqlite3ExplainBegin(pParse->pVdbe);
  105323. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  105324. sqlite3ExplainFinish(pParse->pVdbe);
  105325. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  105326. }
  105327. break;
  105328. case 113: /* select ::= oneselect */
  105329. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  105330. break;
  105331. case 114: /* select ::= select multiselect_op oneselect */
  105332. {
  105333. if( yymsp[0].minor.yy159 ){
  105334. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  105335. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  105336. }else{
  105337. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  105338. }
  105339. yygotominor.yy159 = yymsp[0].minor.yy159;
  105340. }
  105341. break;
  105342. case 116: /* multiselect_op ::= UNION ALL */
  105343. {yygotominor.yy392 = TK_ALL;}
  105344. break;
  105345. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  105346. {
  105347. 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);
  105348. }
  105349. break;
  105350. case 119: /* distinct ::= DISTINCT */
  105351. {yygotominor.yy305 = SF_Distinct;}
  105352. break;
  105353. case 120: /* distinct ::= ALL */
  105354. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  105355. {yygotominor.yy305 = 0;}
  105356. break;
  105357. case 122: /* sclp ::= selcollist COMMA */
  105358. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  105359. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  105360. break;
  105361. case 123: /* sclp ::= */
  105362. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  105363. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  105364. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  105365. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  105366. {yygotominor.yy442 = 0;}
  105367. break;
  105368. case 124: /* selcollist ::= sclp expr as */
  105369. {
  105370. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  105371. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  105372. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  105373. }
  105374. break;
  105375. case 125: /* selcollist ::= sclp STAR */
  105376. {
  105377. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  105378. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  105379. }
  105380. break;
  105381. case 126: /* selcollist ::= sclp nm DOT STAR */
  105382. {
  105383. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  105384. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  105385. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  105386. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  105387. }
  105388. break;
  105389. case 129: /* as ::= */
  105390. {yygotominor.yy0.n = 0;}
  105391. break;
  105392. case 130: /* from ::= */
  105393. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  105394. break;
  105395. case 131: /* from ::= FROM seltablist */
  105396. {
  105397. yygotominor.yy347 = yymsp[0].minor.yy347;
  105398. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  105399. }
  105400. break;
  105401. case 132: /* stl_prefix ::= seltablist joinop */
  105402. {
  105403. yygotominor.yy347 = yymsp[-1].minor.yy347;
  105404. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  105405. }
  105406. break;
  105407. case 133: /* stl_prefix ::= */
  105408. {yygotominor.yy347 = 0;}
  105409. break;
  105410. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  105411. {
  105412. 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);
  105413. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  105414. }
  105415. break;
  105416. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  105417. {
  105418. 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);
  105419. }
  105420. break;
  105421. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  105422. {
  105423. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  105424. yygotominor.yy347 = yymsp[-4].minor.yy347;
  105425. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  105426. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  105427. if( yygotominor.yy347 ){
  105428. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  105429. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  105430. pNew->zName = pOld->zName;
  105431. pNew->zDatabase = pOld->zDatabase;
  105432. pNew->pSelect = pOld->pSelect;
  105433. pOld->zName = pOld->zDatabase = 0;
  105434. pOld->pSelect = 0;
  105435. }
  105436. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  105437. }else{
  105438. Select *pSubquery;
  105439. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  105440. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  105441. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  105442. }
  105443. }
  105444. break;
  105445. case 137: /* dbnm ::= */
  105446. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  105447. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  105448. break;
  105449. case 139: /* fullname ::= nm dbnm */
  105450. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  105451. break;
  105452. case 140: /* joinop ::= COMMA|JOIN */
  105453. { yygotominor.yy392 = JT_INNER; }
  105454. break;
  105455. case 141: /* joinop ::= JOIN_KW JOIN */
  105456. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  105457. break;
  105458. case 142: /* joinop ::= JOIN_KW nm JOIN */
  105459. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  105460. break;
  105461. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  105462. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  105463. break;
  105464. case 144: /* on_opt ::= ON expr */
  105465. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  105466. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  105467. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  105468. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  105469. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  105470. break;
  105471. case 145: /* on_opt ::= */
  105472. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  105473. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  105474. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  105475. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  105476. {yygotominor.yy122 = 0;}
  105477. break;
  105478. case 148: /* indexed_opt ::= NOT INDEXED */
  105479. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  105480. break;
  105481. case 149: /* using_opt ::= USING LP inscollist RP */
  105482. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  105483. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  105484. break;
  105485. case 150: /* using_opt ::= */
  105486. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  105487. {yygotominor.yy180 = 0;}
  105488. break;
  105489. case 152: /* orderby_opt ::= ORDER BY sortlist */
  105490. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  105491. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  105492. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  105493. break;
  105494. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  105495. {
  105496. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  105497. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  105498. }
  105499. break;
  105500. case 154: /* sortlist ::= expr sortorder */
  105501. {
  105502. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  105503. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  105504. }
  105505. break;
  105506. case 155: /* sortorder ::= ASC */
  105507. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  105508. {yygotominor.yy392 = SQLITE_SO_ASC;}
  105509. break;
  105510. case 156: /* sortorder ::= DESC */
  105511. {yygotominor.yy392 = SQLITE_SO_DESC;}
  105512. break;
  105513. case 162: /* limit_opt ::= */
  105514. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  105515. break;
  105516. case 163: /* limit_opt ::= LIMIT expr */
  105517. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  105518. break;
  105519. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  105520. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  105521. break;
  105522. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  105523. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  105524. break;
  105525. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  105526. {
  105527. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  105528. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  105529. }
  105530. break;
  105531. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  105532. {
  105533. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  105534. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  105535. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  105536. }
  105537. break;
  105538. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  105539. {
  105540. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  105541. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  105542. }
  105543. break;
  105544. case 171: /* setlist ::= nm EQ expr */
  105545. {
  105546. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  105547. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  105548. }
  105549. break;
  105550. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  105551. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  105552. break;
  105553. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  105554. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  105555. break;
  105556. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  105557. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  105558. break;
  105559. case 175: /* insert_cmd ::= INSERT orconf */
  105560. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  105561. break;
  105562. case 176: /* insert_cmd ::= REPLACE */
  105563. {yygotominor.yy258 = OE_Replace;}
  105564. break;
  105565. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  105566. {
  105567. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  105568. yygotominor.yy487.pSelect = 0;
  105569. }
  105570. break;
  105571. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  105572. {
  105573. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  105574. if( yymsp[-4].minor.yy487.pList ){
  105575. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  105576. yymsp[-4].minor.yy487.pList = 0;
  105577. }
  105578. yygotominor.yy487.pList = 0;
  105579. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  105580. sqlite3SelectDelete(pParse->db, pRight);
  105581. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  105582. yygotominor.yy487.pSelect = 0;
  105583. }else{
  105584. pRight->op = TK_ALL;
  105585. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  105586. pRight->selFlags |= SF_Values;
  105587. pRight->pPrior->selFlags |= SF_Values;
  105588. yygotominor.yy487.pSelect = pRight;
  105589. }
  105590. }
  105591. break;
  105592. case 181: /* inscollist ::= inscollist COMMA nm */
  105593. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  105594. break;
  105595. case 182: /* inscollist ::= nm */
  105596. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  105597. break;
  105598. case 183: /* expr ::= term */
  105599. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  105600. break;
  105601. case 184: /* expr ::= LP expr RP */
  105602. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  105603. break;
  105604. case 185: /* term ::= NULL */
  105605. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  105606. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  105607. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  105608. break;
  105609. case 186: /* expr ::= id */
  105610. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  105611. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  105612. break;
  105613. case 188: /* expr ::= nm DOT nm */
  105614. {
  105615. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  105616. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  105617. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  105618. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  105619. }
  105620. break;
  105621. case 189: /* expr ::= nm DOT nm DOT nm */
  105622. {
  105623. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  105624. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  105625. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  105626. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  105627. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  105628. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  105629. }
  105630. break;
  105631. case 192: /* expr ::= REGISTER */
  105632. {
  105633. /* When doing a nested parse, one can include terms in an expression
  105634. ** that look like this: #1 #2 ... These terms refer to registers
  105635. ** in the virtual machine. #N is the N-th register. */
  105636. if( pParse->nested==0 ){
  105637. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  105638. yygotominor.yy342.pExpr = 0;
  105639. }else{
  105640. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  105641. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  105642. }
  105643. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  105644. }
  105645. break;
  105646. case 193: /* expr ::= VARIABLE */
  105647. {
  105648. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  105649. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  105650. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  105651. }
  105652. break;
  105653. case 194: /* expr ::= expr COLLATE ids */
  105654. {
  105655. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  105656. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  105657. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105658. }
  105659. break;
  105660. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  105661. {
  105662. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  105663. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  105664. }
  105665. break;
  105666. case 196: /* expr ::= ID LP distinct exprlist RP */
  105667. {
  105668. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  105669. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  105670. }
  105671. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  105672. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  105673. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  105674. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  105675. }
  105676. }
  105677. break;
  105678. case 197: /* expr ::= ID LP STAR RP */
  105679. {
  105680. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  105681. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  105682. }
  105683. break;
  105684. case 198: /* term ::= CTIME_KW */
  105685. {
  105686. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  105687. ** treated as functions that return constants */
  105688. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  105689. if( yygotominor.yy342.pExpr ){
  105690. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  105691. }
  105692. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  105693. }
  105694. break;
  105695. case 199: /* expr ::= expr AND expr */
  105696. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  105697. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  105698. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  105699. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  105700. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  105701. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  105702. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  105703. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  105704. break;
  105705. case 207: /* likeop ::= LIKE_KW */
  105706. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  105707. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  105708. break;
  105709. case 208: /* likeop ::= NOT LIKE_KW */
  105710. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  105711. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  105712. break;
  105713. case 211: /* expr ::= expr likeop expr */
  105714. {
  105715. ExprList *pList;
  105716. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  105717. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  105718. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  105719. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105720. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  105721. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  105722. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  105723. }
  105724. break;
  105725. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  105726. {
  105727. ExprList *pList;
  105728. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  105729. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  105730. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  105731. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  105732. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105733. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  105734. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  105735. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  105736. }
  105737. break;
  105738. case 213: /* expr ::= expr ISNULL|NOTNULL */
  105739. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  105740. break;
  105741. case 214: /* expr ::= expr NOT NULL */
  105742. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  105743. break;
  105744. case 215: /* expr ::= expr IS expr */
  105745. {
  105746. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  105747. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  105748. }
  105749. break;
  105750. case 216: /* expr ::= expr IS NOT expr */
  105751. {
  105752. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  105753. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  105754. }
  105755. break;
  105756. case 217: /* expr ::= NOT expr */
  105757. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  105758. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  105759. break;
  105760. case 219: /* expr ::= MINUS expr */
  105761. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  105762. break;
  105763. case 220: /* expr ::= PLUS expr */
  105764. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  105765. break;
  105766. case 223: /* expr ::= expr between_op expr AND expr */
  105767. {
  105768. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  105769. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  105770. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  105771. if( yygotominor.yy342.pExpr ){
  105772. yygotominor.yy342.pExpr->x.pList = pList;
  105773. }else{
  105774. sqlite3ExprListDelete(pParse->db, pList);
  105775. }
  105776. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105777. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  105778. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  105779. }
  105780. break;
  105781. case 226: /* expr ::= expr in_op LP exprlist RP */
  105782. {
  105783. if( yymsp[-1].minor.yy442==0 ){
  105784. /* Expressions of the form
  105785. **
  105786. ** expr1 IN ()
  105787. ** expr1 NOT IN ()
  105788. **
  105789. ** simplify to constants 0 (false) and 1 (true), respectively,
  105790. ** regardless of the value of expr1.
  105791. */
  105792. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  105793. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  105794. }else{
  105795. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  105796. if( yygotominor.yy342.pExpr ){
  105797. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  105798. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  105799. }else{
  105800. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  105801. }
  105802. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105803. }
  105804. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  105805. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105806. }
  105807. break;
  105808. case 227: /* expr ::= LP select RP */
  105809. {
  105810. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  105811. if( yygotominor.yy342.pExpr ){
  105812. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  105813. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  105814. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  105815. }else{
  105816. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  105817. }
  105818. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  105819. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105820. }
  105821. break;
  105822. case 228: /* expr ::= expr in_op LP select RP */
  105823. {
  105824. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  105825. if( yygotominor.yy342.pExpr ){
  105826. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  105827. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  105828. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  105829. }else{
  105830. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  105831. }
  105832. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105833. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  105834. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105835. }
  105836. break;
  105837. case 229: /* expr ::= expr in_op nm dbnm */
  105838. {
  105839. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  105840. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  105841. if( yygotominor.yy342.pExpr ){
  105842. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  105843. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  105844. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  105845. }else{
  105846. sqlite3SrcListDelete(pParse->db, pSrc);
  105847. }
  105848. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  105849. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  105850. 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];
  105851. }
  105852. break;
  105853. case 230: /* expr ::= EXISTS LP select RP */
  105854. {
  105855. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  105856. if( p ){
  105857. p->x.pSelect = yymsp[-1].minor.yy159;
  105858. ExprSetProperty(p, EP_xIsSelect);
  105859. sqlite3ExprSetHeight(pParse, p);
  105860. }else{
  105861. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  105862. }
  105863. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  105864. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105865. }
  105866. break;
  105867. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  105868. {
  105869. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
  105870. if( yygotominor.yy342.pExpr ){
  105871. yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
  105872. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  105873. }else{
  105874. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  105875. }
  105876. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  105877. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  105878. }
  105879. break;
  105880. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  105881. {
  105882. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  105883. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  105884. }
  105885. break;
  105886. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  105887. {
  105888. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  105889. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  105890. }
  105891. break;
  105892. case 240: /* nexprlist ::= nexprlist COMMA expr */
  105893. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  105894. break;
  105895. case 241: /* nexprlist ::= expr */
  105896. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  105897. break;
  105898. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
  105899. {
  105900. sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
  105901. sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
  105902. &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
  105903. }
  105904. break;
  105905. case 243: /* uniqueflag ::= UNIQUE */
  105906. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  105907. {yygotominor.yy392 = OE_Abort;}
  105908. break;
  105909. case 244: /* uniqueflag ::= */
  105910. {yygotominor.yy392 = OE_None;}
  105911. break;
  105912. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  105913. {
  105914. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  105915. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  105916. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  105917. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  105918. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  105919. }
  105920. break;
  105921. case 248: /* idxlist ::= nm collate sortorder */
  105922. {
  105923. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  105924. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  105925. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  105926. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  105927. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  105928. }
  105929. break;
  105930. case 249: /* collate ::= */
  105931. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  105932. break;
  105933. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  105934. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  105935. break;
  105936. case 252: /* cmd ::= VACUUM */
  105937. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  105938. {sqlite3Vacuum(pParse);}
  105939. break;
  105940. case 254: /* cmd ::= PRAGMA nm dbnm */
  105941. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  105942. break;
  105943. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  105944. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  105945. break;
  105946. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  105947. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  105948. break;
  105949. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  105950. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  105951. break;
  105952. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  105953. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  105954. break;
  105955. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  105956. {
  105957. Token all;
  105958. all.z = yymsp[-3].minor.yy0.z;
  105959. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  105960. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  105961. }
  105962. break;
  105963. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  105964. {
  105965. 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);
  105966. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  105967. }
  105968. break;
  105969. case 270: /* trigger_time ::= BEFORE */
  105970. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  105971. { yygotominor.yy392 = TK_BEFORE; }
  105972. break;
  105973. case 271: /* trigger_time ::= AFTER */
  105974. { yygotominor.yy392 = TK_AFTER; }
  105975. break;
  105976. case 272: /* trigger_time ::= INSTEAD OF */
  105977. { yygotominor.yy392 = TK_INSTEAD;}
  105978. break;
  105979. case 274: /* trigger_event ::= DELETE|INSERT */
  105980. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  105981. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  105982. break;
  105983. case 276: /* trigger_event ::= UPDATE OF inscollist */
  105984. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  105985. break;
  105986. case 279: /* when_clause ::= */
  105987. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  105988. { yygotominor.yy122 = 0; }
  105989. break;
  105990. case 280: /* when_clause ::= WHEN expr */
  105991. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  105992. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  105993. break;
  105994. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  105995. {
  105996. assert( yymsp[-2].minor.yy327!=0 );
  105997. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  105998. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  105999. yygotominor.yy327 = yymsp[-2].minor.yy327;
  106000. }
  106001. break;
  106002. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  106003. {
  106004. assert( yymsp[-1].minor.yy327!=0 );
  106005. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  106006. yygotominor.yy327 = yymsp[-1].minor.yy327;
  106007. }
  106008. break;
  106009. case 284: /* trnm ::= nm DOT nm */
  106010. {
  106011. yygotominor.yy0 = yymsp[0].minor.yy0;
  106012. sqlite3ErrorMsg(pParse,
  106013. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  106014. "statements within triggers");
  106015. }
  106016. break;
  106017. case 286: /* tridxby ::= INDEXED BY nm */
  106018. {
  106019. sqlite3ErrorMsg(pParse,
  106020. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  106021. "within triggers");
  106022. }
  106023. break;
  106024. case 287: /* tridxby ::= NOT INDEXED */
  106025. {
  106026. sqlite3ErrorMsg(pParse,
  106027. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  106028. "within triggers");
  106029. }
  106030. break;
  106031. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  106032. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  106033. break;
  106034. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  106035. {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);}
  106036. break;
  106037. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  106038. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  106039. break;
  106040. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  106041. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  106042. break;
  106043. case 292: /* trigger_cmd ::= select */
  106044. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  106045. break;
  106046. case 293: /* expr ::= RAISE LP IGNORE RP */
  106047. {
  106048. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  106049. if( yygotominor.yy342.pExpr ){
  106050. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  106051. }
  106052. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  106053. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  106054. }
  106055. break;
  106056. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  106057. {
  106058. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  106059. if( yygotominor.yy342.pExpr ) {
  106060. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  106061. }
  106062. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  106063. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  106064. }
  106065. break;
  106066. case 295: /* raisetype ::= ROLLBACK */
  106067. {yygotominor.yy392 = OE_Rollback;}
  106068. break;
  106069. case 297: /* raisetype ::= FAIL */
  106070. {yygotominor.yy392 = OE_Fail;}
  106071. break;
  106072. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  106073. {
  106074. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  106075. }
  106076. break;
  106077. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  106078. {
  106079. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  106080. }
  106081. break;
  106082. case 300: /* cmd ::= DETACH database_kw_opt expr */
  106083. {
  106084. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  106085. }
  106086. break;
  106087. case 305: /* cmd ::= REINDEX */
  106088. {sqlite3Reindex(pParse, 0, 0);}
  106089. break;
  106090. case 306: /* cmd ::= REINDEX nm dbnm */
  106091. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  106092. break;
  106093. case 307: /* cmd ::= ANALYZE */
  106094. {sqlite3Analyze(pParse, 0, 0);}
  106095. break;
  106096. case 308: /* cmd ::= ANALYZE nm dbnm */
  106097. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  106098. break;
  106099. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  106100. {
  106101. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  106102. }
  106103. break;
  106104. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  106105. {
  106106. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  106107. }
  106108. break;
  106109. case 311: /* add_column_fullname ::= fullname */
  106110. {
  106111. pParse->db->lookaside.bEnabled = 0;
  106112. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  106113. }
  106114. break;
  106115. case 314: /* cmd ::= create_vtab */
  106116. {sqlite3VtabFinishParse(pParse,0);}
  106117. break;
  106118. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  106119. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  106120. break;
  106121. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  106122. {
  106123. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  106124. }
  106125. break;
  106126. case 319: /* vtabarg ::= */
  106127. {sqlite3VtabArgInit(pParse);}
  106128. break;
  106129. case 321: /* vtabargtoken ::= ANY */
  106130. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  106131. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  106132. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  106133. break;
  106134. default:
  106135. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  106136. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  106137. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  106138. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  106139. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  106140. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  106141. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  106142. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  106143. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  106144. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  106145. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  106146. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  106147. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  106148. /* (44) type ::= */ yytestcase(yyruleno==44);
  106149. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  106150. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  106151. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  106152. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  106153. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  106154. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  106155. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  106156. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  106157. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  106158. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  106159. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  106160. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  106161. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  106162. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  106163. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  106164. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  106165. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  106166. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  106167. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  106168. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  106169. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  106170. break;
  106171. };
  106172. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  106173. yygoto = yyRuleInfo[yyruleno].lhs;
  106174. yysize = yyRuleInfo[yyruleno].nrhs;
  106175. yypParser->yyidx -= yysize;
  106176. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  106177. if( yyact < YYNSTATE ){
  106178. #ifdef NDEBUG
  106179. /* If we are not debugging and the reduce action popped at least
  106180. ** one element off the stack, then we can push the new element back
  106181. ** onto the stack here, and skip the stack overflow test in yy_shift().
  106182. ** That gives a significant speed improvement. */
  106183. if( yysize ){
  106184. yypParser->yyidx++;
  106185. yymsp -= yysize-1;
  106186. yymsp->stateno = (YYACTIONTYPE)yyact;
  106187. yymsp->major = (YYCODETYPE)yygoto;
  106188. yymsp->minor = yygotominor;
  106189. }else
  106190. #endif
  106191. {
  106192. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  106193. }
  106194. }else{
  106195. assert( yyact == YYNSTATE + YYNRULE + 1 );
  106196. yy_accept(yypParser);
  106197. }
  106198. }
  106199. /*
  106200. ** The following code executes when the parse fails
  106201. */
  106202. #ifndef YYNOERRORRECOVERY
  106203. static void yy_parse_failed(
  106204. yyParser *yypParser /* The parser */
  106205. ){
  106206. sqlite3ParserARG_FETCH;
  106207. #ifndef NDEBUG
  106208. if( yyTraceFILE ){
  106209. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  106210. }
  106211. #endif
  106212. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  106213. /* Here code is inserted which will be executed whenever the
  106214. ** parser fails */
  106215. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  106216. }
  106217. #endif /* YYNOERRORRECOVERY */
  106218. /*
  106219. ** The following code executes when a syntax error first occurs.
  106220. */
  106221. static void yy_syntax_error(
  106222. yyParser *yypParser, /* The parser */
  106223. int yymajor, /* The major type of the error token */
  106224. YYMINORTYPE yyminor /* The minor type of the error token */
  106225. ){
  106226. sqlite3ParserARG_FETCH;
  106227. #define TOKEN (yyminor.yy0)
  106228. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  106229. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  106230. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  106231. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  106232. }
  106233. /*
  106234. ** The following is executed when the parser accepts
  106235. */
  106236. static void yy_accept(
  106237. yyParser *yypParser /* The parser */
  106238. ){
  106239. sqlite3ParserARG_FETCH;
  106240. #ifndef NDEBUG
  106241. if( yyTraceFILE ){
  106242. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  106243. }
  106244. #endif
  106245. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  106246. /* Here code is inserted which will be executed whenever the
  106247. ** parser accepts */
  106248. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  106249. }
  106250. /* The main parser program.
  106251. ** The first argument is a pointer to a structure obtained from
  106252. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  106253. ** The second argument is the major token number. The third is
  106254. ** the minor token. The fourth optional argument is whatever the
  106255. ** user wants (and specified in the grammar) and is available for
  106256. ** use by the action routines.
  106257. **
  106258. ** Inputs:
  106259. ** <ul>
  106260. ** <li> A pointer to the parser (an opaque structure.)
  106261. ** <li> The major token number.
  106262. ** <li> The minor token number.
  106263. ** <li> An option argument of a grammar-specified type.
  106264. ** </ul>
  106265. **
  106266. ** Outputs:
  106267. ** None.
  106268. */
  106269. SQLITE_PRIVATE void sqlite3Parser(
  106270. void *yyp, /* The parser */
  106271. int yymajor, /* The major token code number */
  106272. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  106273. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  106274. ){
  106275. YYMINORTYPE yyminorunion;
  106276. int yyact; /* The parser action. */
  106277. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  106278. int yyendofinput; /* True if we are at the end of input */
  106279. #endif
  106280. #ifdef YYERRORSYMBOL
  106281. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  106282. #endif
  106283. yyParser *yypParser; /* The parser */
  106284. /* (re)initialize the parser, if necessary */
  106285. yypParser = (yyParser*)yyp;
  106286. if( yypParser->yyidx<0 ){
  106287. #if YYSTACKDEPTH<=0
  106288. if( yypParser->yystksz <=0 ){
  106289. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  106290. yyminorunion = yyzerominor;
  106291. yyStackOverflow(yypParser, &yyminorunion);
  106292. return;
  106293. }
  106294. #endif
  106295. yypParser->yyidx = 0;
  106296. yypParser->yyerrcnt = -1;
  106297. yypParser->yystack[0].stateno = 0;
  106298. yypParser->yystack[0].major = 0;
  106299. }
  106300. yyminorunion.yy0 = yyminor;
  106301. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  106302. yyendofinput = (yymajor==0);
  106303. #endif
  106304. sqlite3ParserARG_STORE;
  106305. #ifndef NDEBUG
  106306. if( yyTraceFILE ){
  106307. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  106308. }
  106309. #endif
  106310. do{
  106311. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  106312. if( yyact<YYNSTATE ){
  106313. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  106314. yypParser->yyerrcnt--;
  106315. yymajor = YYNOCODE;
  106316. }else if( yyact < YYNSTATE + YYNRULE ){
  106317. yy_reduce(yypParser,yyact-YYNSTATE);
  106318. }else{
  106319. assert( yyact == YY_ERROR_ACTION );
  106320. #ifdef YYERRORSYMBOL
  106321. int yymx;
  106322. #endif
  106323. #ifndef NDEBUG
  106324. if( yyTraceFILE ){
  106325. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  106326. }
  106327. #endif
  106328. #ifdef YYERRORSYMBOL
  106329. /* A syntax error has occurred.
  106330. ** The response to an error depends upon whether or not the
  106331. ** grammar defines an error token "ERROR".
  106332. **
  106333. ** This is what we do if the grammar does define ERROR:
  106334. **
  106335. ** * Call the %syntax_error function.
  106336. **
  106337. ** * Begin popping the stack until we enter a state where
  106338. ** it is legal to shift the error symbol, then shift
  106339. ** the error symbol.
  106340. **
  106341. ** * Set the error count to three.
  106342. **
  106343. ** * Begin accepting and shifting new tokens. No new error
  106344. ** processing will occur until three tokens have been
  106345. ** shifted successfully.
  106346. **
  106347. */
  106348. if( yypParser->yyerrcnt<0 ){
  106349. yy_syntax_error(yypParser,yymajor,yyminorunion);
  106350. }
  106351. yymx = yypParser->yystack[yypParser->yyidx].major;
  106352. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  106353. #ifndef NDEBUG
  106354. if( yyTraceFILE ){
  106355. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  106356. yyTracePrompt,yyTokenName[yymajor]);
  106357. }
  106358. #endif
  106359. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  106360. yymajor = YYNOCODE;
  106361. }else{
  106362. while(
  106363. yypParser->yyidx >= 0 &&
  106364. yymx != YYERRORSYMBOL &&
  106365. (yyact = yy_find_reduce_action(
  106366. yypParser->yystack[yypParser->yyidx].stateno,
  106367. YYERRORSYMBOL)) >= YYNSTATE
  106368. ){
  106369. yy_pop_parser_stack(yypParser);
  106370. }
  106371. if( yypParser->yyidx < 0 || yymajor==0 ){
  106372. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  106373. yy_parse_failed(yypParser);
  106374. yymajor = YYNOCODE;
  106375. }else if( yymx!=YYERRORSYMBOL ){
  106376. YYMINORTYPE u2;
  106377. u2.YYERRSYMDT = 0;
  106378. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  106379. }
  106380. }
  106381. yypParser->yyerrcnt = 3;
  106382. yyerrorhit = 1;
  106383. #elif defined(YYNOERRORRECOVERY)
  106384. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  106385. ** do any kind of error recovery. Instead, simply invoke the syntax
  106386. ** error routine and continue going as if nothing had happened.
  106387. **
  106388. ** Applications can set this macro (for example inside %include) if
  106389. ** they intend to abandon the parse upon the first syntax error seen.
  106390. */
  106391. yy_syntax_error(yypParser,yymajor,yyminorunion);
  106392. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  106393. yymajor = YYNOCODE;
  106394. #else /* YYERRORSYMBOL is not defined */
  106395. /* This is what we do if the grammar does not define ERROR:
  106396. **
  106397. ** * Report an error message, and throw away the input token.
  106398. **
  106399. ** * If the input token is $, then fail the parse.
  106400. **
  106401. ** As before, subsequent error messages are suppressed until
  106402. ** three input tokens have been successfully shifted.
  106403. */
  106404. if( yypParser->yyerrcnt<=0 ){
  106405. yy_syntax_error(yypParser,yymajor,yyminorunion);
  106406. }
  106407. yypParser->yyerrcnt = 3;
  106408. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  106409. if( yyendofinput ){
  106410. yy_parse_failed(yypParser);
  106411. }
  106412. yymajor = YYNOCODE;
  106413. #endif
  106414. }
  106415. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  106416. return;
  106417. }
  106418. /************** End of parse.c ***********************************************/
  106419. /************** Begin file tokenize.c ****************************************/
  106420. /*
  106421. ** 2001 September 15
  106422. **
  106423. ** The author disclaims copyright to this source code. In place of
  106424. ** a legal notice, here is a blessing:
  106425. **
  106426. ** May you do good and not evil.
  106427. ** May you find forgiveness for yourself and forgive others.
  106428. ** May you share freely, never taking more than you give.
  106429. **
  106430. *************************************************************************
  106431. ** An tokenizer for SQL
  106432. **
  106433. ** This file contains C code that splits an SQL input string up into
  106434. ** individual tokens and sends those tokens one-by-one over to the
  106435. ** parser for analysis.
  106436. */
  106437. /* #include <stdlib.h> */
  106438. /*
  106439. ** The charMap() macro maps alphabetic characters into their
  106440. ** lower-case ASCII equivalent. On ASCII machines, this is just
  106441. ** an upper-to-lower case map. On EBCDIC machines we also need
  106442. ** to adjust the encoding. Only alphabetic characters and underscores
  106443. ** need to be translated.
  106444. */
  106445. #ifdef SQLITE_ASCII
  106446. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  106447. #endif
  106448. #ifdef SQLITE_EBCDIC
  106449. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  106450. const unsigned char ebcdicToAscii[] = {
  106451. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  106452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  106453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  106454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  106455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  106456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  106457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  106458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  106459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  106460. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  106461. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  106462. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  106463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  106464. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  106465. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  106466. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  106467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  106468. };
  106469. #endif
  106470. /*
  106471. ** The sqlite3KeywordCode function looks up an identifier to determine if
  106472. ** it is a keyword. If it is a keyword, the token code of that keyword is
  106473. ** returned. If the input is not a keyword, TK_ID is returned.
  106474. **
  106475. ** The implementation of this routine was generated by a program,
  106476. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  106477. ** The output of the mkkeywordhash.c program is written into a file
  106478. ** named keywordhash.h and then included into this source file by
  106479. ** the #include below.
  106480. */
  106481. /************** Include keywordhash.h in the middle of tokenize.c ************/
  106482. /************** Begin file keywordhash.h *************************************/
  106483. /***** This file contains automatically generated code ******
  106484. **
  106485. ** The code in this file has been automatically generated by
  106486. **
  106487. ** sqlite/tool/mkkeywordhash.c
  106488. **
  106489. ** The code in this file implements a function that determines whether
  106490. ** or not a given identifier is really an SQL keyword. The same thing
  106491. ** might be implemented more directly using a hand-written hash table.
  106492. ** But by using this automatically generated code, the size of the code
  106493. ** is substantially reduced. This is important for embedded applications
  106494. ** on platforms with limited memory.
  106495. */
  106496. /* Hash score: 175 */
  106497. static int keywordCode(const char *z, int n){
  106498. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  106499. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  106500. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  106501. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  106502. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  106503. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  106504. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  106505. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  106506. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  106507. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  106508. /* INITIALLY */
  106509. static const char zText[540] = {
  106510. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  106511. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  106512. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  106513. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  106514. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  106515. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  106516. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  106517. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  106518. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  106519. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  106520. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  106521. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  106522. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  106523. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  106524. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  106525. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  106526. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  106527. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  106528. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  106529. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  106530. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  106531. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  106532. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  106533. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  106534. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  106535. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  106536. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  106537. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  106538. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  106539. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  106540. };
  106541. static const unsigned char aHash[127] = {
  106542. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  106543. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  106544. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  106545. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  106546. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  106547. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  106548. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  106549. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  106550. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  106551. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  106552. };
  106553. static const unsigned char aNext[121] = {
  106554. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  106555. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  106556. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  106557. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  106558. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  106559. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  106560. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  106561. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  106562. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  106563. 35, 64, 0, 0,
  106564. };
  106565. static const unsigned char aLen[121] = {
  106566. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  106567. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  106568. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  106569. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  106570. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  106571. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  106572. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  106573. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  106574. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  106575. 6, 4, 9, 3,
  106576. };
  106577. static const unsigned short int aOffset[121] = {
  106578. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  106579. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  106580. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  106581. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  106582. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  106583. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  106584. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  106585. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  106586. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  106587. 521, 527, 531, 536,
  106588. };
  106589. static const unsigned char aCode[121] = {
  106590. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  106591. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  106592. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  106593. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  106594. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  106595. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  106596. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  106597. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  106598. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  106599. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  106600. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  106601. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  106602. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  106603. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  106604. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  106605. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  106606. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  106607. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  106608. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  106609. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  106610. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  106611. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  106612. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  106613. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  106614. TK_ALL,
  106615. };
  106616. int h, i;
  106617. if( n<2 ) return TK_ID;
  106618. h = ((charMap(z[0])*4) ^
  106619. (charMap(z[n-1])*3) ^
  106620. n) % 127;
  106621. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  106622. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  106623. testcase( i==0 ); /* REINDEX */
  106624. testcase( i==1 ); /* INDEXED */
  106625. testcase( i==2 ); /* INDEX */
  106626. testcase( i==3 ); /* DESC */
  106627. testcase( i==4 ); /* ESCAPE */
  106628. testcase( i==5 ); /* EACH */
  106629. testcase( i==6 ); /* CHECK */
  106630. testcase( i==7 ); /* KEY */
  106631. testcase( i==8 ); /* BEFORE */
  106632. testcase( i==9 ); /* FOREIGN */
  106633. testcase( i==10 ); /* FOR */
  106634. testcase( i==11 ); /* IGNORE */
  106635. testcase( i==12 ); /* REGEXP */
  106636. testcase( i==13 ); /* EXPLAIN */
  106637. testcase( i==14 ); /* INSTEAD */
  106638. testcase( i==15 ); /* ADD */
  106639. testcase( i==16 ); /* DATABASE */
  106640. testcase( i==17 ); /* AS */
  106641. testcase( i==18 ); /* SELECT */
  106642. testcase( i==19 ); /* TABLE */
  106643. testcase( i==20 ); /* LEFT */
  106644. testcase( i==21 ); /* THEN */
  106645. testcase( i==22 ); /* END */
  106646. testcase( i==23 ); /* DEFERRABLE */
  106647. testcase( i==24 ); /* ELSE */
  106648. testcase( i==25 ); /* EXCEPT */
  106649. testcase( i==26 ); /* TRANSACTION */
  106650. testcase( i==27 ); /* ACTION */
  106651. testcase( i==28 ); /* ON */
  106652. testcase( i==29 ); /* NATURAL */
  106653. testcase( i==30 ); /* ALTER */
  106654. testcase( i==31 ); /* RAISE */
  106655. testcase( i==32 ); /* EXCLUSIVE */
  106656. testcase( i==33 ); /* EXISTS */
  106657. testcase( i==34 ); /* SAVEPOINT */
  106658. testcase( i==35 ); /* INTERSECT */
  106659. testcase( i==36 ); /* TRIGGER */
  106660. testcase( i==37 ); /* REFERENCES */
  106661. testcase( i==38 ); /* CONSTRAINT */
  106662. testcase( i==39 ); /* INTO */
  106663. testcase( i==40 ); /* OFFSET */
  106664. testcase( i==41 ); /* OF */
  106665. testcase( i==42 ); /* SET */
  106666. testcase( i==43 ); /* TEMPORARY */
  106667. testcase( i==44 ); /* TEMP */
  106668. testcase( i==45 ); /* OR */
  106669. testcase( i==46 ); /* UNIQUE */
  106670. testcase( i==47 ); /* QUERY */
  106671. testcase( i==48 ); /* ATTACH */
  106672. testcase( i==49 ); /* HAVING */
  106673. testcase( i==50 ); /* GROUP */
  106674. testcase( i==51 ); /* UPDATE */
  106675. testcase( i==52 ); /* BEGIN */
  106676. testcase( i==53 ); /* INNER */
  106677. testcase( i==54 ); /* RELEASE */
  106678. testcase( i==55 ); /* BETWEEN */
  106679. testcase( i==56 ); /* NOTNULL */
  106680. testcase( i==57 ); /* NOT */
  106681. testcase( i==58 ); /* NO */
  106682. testcase( i==59 ); /* NULL */
  106683. testcase( i==60 ); /* LIKE */
  106684. testcase( i==61 ); /* CASCADE */
  106685. testcase( i==62 ); /* ASC */
  106686. testcase( i==63 ); /* DELETE */
  106687. testcase( i==64 ); /* CASE */
  106688. testcase( i==65 ); /* COLLATE */
  106689. testcase( i==66 ); /* CREATE */
  106690. testcase( i==67 ); /* CURRENT_DATE */
  106691. testcase( i==68 ); /* DETACH */
  106692. testcase( i==69 ); /* IMMEDIATE */
  106693. testcase( i==70 ); /* JOIN */
  106694. testcase( i==71 ); /* INSERT */
  106695. testcase( i==72 ); /* MATCH */
  106696. testcase( i==73 ); /* PLAN */
  106697. testcase( i==74 ); /* ANALYZE */
  106698. testcase( i==75 ); /* PRAGMA */
  106699. testcase( i==76 ); /* ABORT */
  106700. testcase( i==77 ); /* VALUES */
  106701. testcase( i==78 ); /* VIRTUAL */
  106702. testcase( i==79 ); /* LIMIT */
  106703. testcase( i==80 ); /* WHEN */
  106704. testcase( i==81 ); /* WHERE */
  106705. testcase( i==82 ); /* RENAME */
  106706. testcase( i==83 ); /* AFTER */
  106707. testcase( i==84 ); /* REPLACE */
  106708. testcase( i==85 ); /* AND */
  106709. testcase( i==86 ); /* DEFAULT */
  106710. testcase( i==87 ); /* AUTOINCREMENT */
  106711. testcase( i==88 ); /* TO */
  106712. testcase( i==89 ); /* IN */
  106713. testcase( i==90 ); /* CAST */
  106714. testcase( i==91 ); /* COLUMN */
  106715. testcase( i==92 ); /* COMMIT */
  106716. testcase( i==93 ); /* CONFLICT */
  106717. testcase( i==94 ); /* CROSS */
  106718. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  106719. testcase( i==96 ); /* CURRENT_TIME */
  106720. testcase( i==97 ); /* PRIMARY */
  106721. testcase( i==98 ); /* DEFERRED */
  106722. testcase( i==99 ); /* DISTINCT */
  106723. testcase( i==100 ); /* IS */
  106724. testcase( i==101 ); /* DROP */
  106725. testcase( i==102 ); /* FAIL */
  106726. testcase( i==103 ); /* FROM */
  106727. testcase( i==104 ); /* FULL */
  106728. testcase( i==105 ); /* GLOB */
  106729. testcase( i==106 ); /* BY */
  106730. testcase( i==107 ); /* IF */
  106731. testcase( i==108 ); /* ISNULL */
  106732. testcase( i==109 ); /* ORDER */
  106733. testcase( i==110 ); /* RESTRICT */
  106734. testcase( i==111 ); /* OUTER */
  106735. testcase( i==112 ); /* RIGHT */
  106736. testcase( i==113 ); /* ROLLBACK */
  106737. testcase( i==114 ); /* ROW */
  106738. testcase( i==115 ); /* UNION */
  106739. testcase( i==116 ); /* USING */
  106740. testcase( i==117 ); /* VACUUM */
  106741. testcase( i==118 ); /* VIEW */
  106742. testcase( i==119 ); /* INITIALLY */
  106743. testcase( i==120 ); /* ALL */
  106744. return aCode[i];
  106745. }
  106746. }
  106747. return TK_ID;
  106748. }
  106749. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  106750. return keywordCode((char*)z, n);
  106751. }
  106752. #define SQLITE_N_KEYWORD 121
  106753. /************** End of keywordhash.h *****************************************/
  106754. /************** Continuing where we left off in tokenize.c *******************/
  106755. /*
  106756. ** If X is a character that can be used in an identifier then
  106757. ** IdChar(X) will be true. Otherwise it is false.
  106758. **
  106759. ** For ASCII, any character with the high-order bit set is
  106760. ** allowed in an identifier. For 7-bit characters,
  106761. ** sqlite3IsIdChar[X] must be 1.
  106762. **
  106763. ** For EBCDIC, the rules are more complex but have the same
  106764. ** end result.
  106765. **
  106766. ** Ticket #1066. the SQL standard does not allow '$' in the
  106767. ** middle of identfiers. But many SQL implementations do.
  106768. ** SQLite will allow '$' in identifiers for compatibility.
  106769. ** But the feature is undocumented.
  106770. */
  106771. #ifdef SQLITE_ASCII
  106772. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  106773. #endif
  106774. #ifdef SQLITE_EBCDIC
  106775. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  106776. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  106777. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  106778. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  106779. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  106780. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  106781. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  106782. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  106783. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  106784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  106785. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  106786. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  106787. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  106788. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  106789. };
  106790. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  106791. #endif
  106792. /*
  106793. ** Return the length of the token that begins at z[0].
  106794. ** Store the token type in *tokenType before returning.
  106795. */
  106796. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  106797. int i, c;
  106798. switch( *z ){
  106799. case ' ': case '\t': case '\n': case '\f': case '\r': {
  106800. testcase( z[0]==' ' );
  106801. testcase( z[0]=='\t' );
  106802. testcase( z[0]=='\n' );
  106803. testcase( z[0]=='\f' );
  106804. testcase( z[0]=='\r' );
  106805. for(i=1; sqlite3Isspace(z[i]); i++){}
  106806. *tokenType = TK_SPACE;
  106807. return i;
  106808. }
  106809. case '-': {
  106810. if( z[1]=='-' ){
  106811. /* IMP: R-50417-27976 -- syntax diagram for comments */
  106812. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  106813. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  106814. return i;
  106815. }
  106816. *tokenType = TK_MINUS;
  106817. return 1;
  106818. }
  106819. case '(': {
  106820. *tokenType = TK_LP;
  106821. return 1;
  106822. }
  106823. case ')': {
  106824. *tokenType = TK_RP;
  106825. return 1;
  106826. }
  106827. case ';': {
  106828. *tokenType = TK_SEMI;
  106829. return 1;
  106830. }
  106831. case '+': {
  106832. *tokenType = TK_PLUS;
  106833. return 1;
  106834. }
  106835. case '*': {
  106836. *tokenType = TK_STAR;
  106837. return 1;
  106838. }
  106839. case '/': {
  106840. if( z[1]!='*' || z[2]==0 ){
  106841. *tokenType = TK_SLASH;
  106842. return 1;
  106843. }
  106844. /* IMP: R-50417-27976 -- syntax diagram for comments */
  106845. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  106846. if( c ) i++;
  106847. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  106848. return i;
  106849. }
  106850. case '%': {
  106851. *tokenType = TK_REM;
  106852. return 1;
  106853. }
  106854. case '=': {
  106855. *tokenType = TK_EQ;
  106856. return 1 + (z[1]=='=');
  106857. }
  106858. case '<': {
  106859. if( (c=z[1])=='=' ){
  106860. *tokenType = TK_LE;
  106861. return 2;
  106862. }else if( c=='>' ){
  106863. *tokenType = TK_NE;
  106864. return 2;
  106865. }else if( c=='<' ){
  106866. *tokenType = TK_LSHIFT;
  106867. return 2;
  106868. }else{
  106869. *tokenType = TK_LT;
  106870. return 1;
  106871. }
  106872. }
  106873. case '>': {
  106874. if( (c=z[1])=='=' ){
  106875. *tokenType = TK_GE;
  106876. return 2;
  106877. }else if( c=='>' ){
  106878. *tokenType = TK_RSHIFT;
  106879. return 2;
  106880. }else{
  106881. *tokenType = TK_GT;
  106882. return 1;
  106883. }
  106884. }
  106885. case '!': {
  106886. if( z[1]!='=' ){
  106887. *tokenType = TK_ILLEGAL;
  106888. return 2;
  106889. }else{
  106890. *tokenType = TK_NE;
  106891. return 2;
  106892. }
  106893. }
  106894. case '|': {
  106895. if( z[1]!='|' ){
  106896. *tokenType = TK_BITOR;
  106897. return 1;
  106898. }else{
  106899. *tokenType = TK_CONCAT;
  106900. return 2;
  106901. }
  106902. }
  106903. case ',': {
  106904. *tokenType = TK_COMMA;
  106905. return 1;
  106906. }
  106907. case '&': {
  106908. *tokenType = TK_BITAND;
  106909. return 1;
  106910. }
  106911. case '~': {
  106912. *tokenType = TK_BITNOT;
  106913. return 1;
  106914. }
  106915. case '`':
  106916. case '\'':
  106917. case '"': {
  106918. int delim = z[0];
  106919. testcase( delim=='`' );
  106920. testcase( delim=='\'' );
  106921. testcase( delim=='"' );
  106922. for(i=1; (c=z[i])!=0; i++){
  106923. if( c==delim ){
  106924. if( z[i+1]==delim ){
  106925. i++;
  106926. }else{
  106927. break;
  106928. }
  106929. }
  106930. }
  106931. if( c=='\'' ){
  106932. *tokenType = TK_STRING;
  106933. return i+1;
  106934. }else if( c!=0 ){
  106935. *tokenType = TK_ID;
  106936. return i+1;
  106937. }else{
  106938. *tokenType = TK_ILLEGAL;
  106939. return i;
  106940. }
  106941. }
  106942. case '.': {
  106943. #ifndef SQLITE_OMIT_FLOATING_POINT
  106944. if( !sqlite3Isdigit(z[1]) )
  106945. #endif
  106946. {
  106947. *tokenType = TK_DOT;
  106948. return 1;
  106949. }
  106950. /* If the next character is a digit, this is a floating point
  106951. ** number that begins with ".". Fall thru into the next case */
  106952. }
  106953. case '0': case '1': case '2': case '3': case '4':
  106954. case '5': case '6': case '7': case '8': case '9': {
  106955. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  106956. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  106957. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  106958. testcase( z[0]=='9' );
  106959. *tokenType = TK_INTEGER;
  106960. for(i=0; sqlite3Isdigit(z[i]); i++){}
  106961. #ifndef SQLITE_OMIT_FLOATING_POINT
  106962. if( z[i]=='.' ){
  106963. i++;
  106964. while( sqlite3Isdigit(z[i]) ){ i++; }
  106965. *tokenType = TK_FLOAT;
  106966. }
  106967. if( (z[i]=='e' || z[i]=='E') &&
  106968. ( sqlite3Isdigit(z[i+1])
  106969. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  106970. )
  106971. ){
  106972. i += 2;
  106973. while( sqlite3Isdigit(z[i]) ){ i++; }
  106974. *tokenType = TK_FLOAT;
  106975. }
  106976. #endif
  106977. while( IdChar(z[i]) ){
  106978. *tokenType = TK_ILLEGAL;
  106979. i++;
  106980. }
  106981. return i;
  106982. }
  106983. case '[': {
  106984. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  106985. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  106986. return i;
  106987. }
  106988. case '?': {
  106989. *tokenType = TK_VARIABLE;
  106990. for(i=1; sqlite3Isdigit(z[i]); i++){}
  106991. return i;
  106992. }
  106993. case '#': {
  106994. for(i=1; sqlite3Isdigit(z[i]); i++){}
  106995. if( i>1 ){
  106996. /* Parameters of the form #NNN (where NNN is a number) are used
  106997. ** internally by sqlite3NestedParse. */
  106998. *tokenType = TK_REGISTER;
  106999. return i;
  107000. }
  107001. /* Fall through into the next case if the '#' is not followed by
  107002. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  107003. }
  107004. #ifndef SQLITE_OMIT_TCL_VARIABLE
  107005. case '$':
  107006. #endif
  107007. case '@': /* For compatibility with MS SQL Server */
  107008. case ':': {
  107009. int n = 0;
  107010. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  107011. *tokenType = TK_VARIABLE;
  107012. for(i=1; (c=z[i])!=0; i++){
  107013. if( IdChar(c) ){
  107014. n++;
  107015. #ifndef SQLITE_OMIT_TCL_VARIABLE
  107016. }else if( c=='(' && n>0 ){
  107017. do{
  107018. i++;
  107019. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  107020. if( c==')' ){
  107021. i++;
  107022. }else{
  107023. *tokenType = TK_ILLEGAL;
  107024. }
  107025. break;
  107026. }else if( c==':' && z[i+1]==':' ){
  107027. i++;
  107028. #endif
  107029. }else{
  107030. break;
  107031. }
  107032. }
  107033. if( n==0 ) *tokenType = TK_ILLEGAL;
  107034. return i;
  107035. }
  107036. #ifndef SQLITE_OMIT_BLOB_LITERAL
  107037. case 'x': case 'X': {
  107038. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  107039. if( z[1]=='\'' ){
  107040. *tokenType = TK_BLOB;
  107041. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  107042. if( z[i]!='\'' || i%2 ){
  107043. *tokenType = TK_ILLEGAL;
  107044. while( z[i] && z[i]!='\'' ){ i++; }
  107045. }
  107046. if( z[i] ) i++;
  107047. return i;
  107048. }
  107049. /* Otherwise fall through to the next case */
  107050. }
  107051. #endif
  107052. default: {
  107053. if( !IdChar(*z) ){
  107054. break;
  107055. }
  107056. for(i=1; IdChar(z[i]); i++){}
  107057. *tokenType = keywordCode((char*)z, i);
  107058. return i;
  107059. }
  107060. }
  107061. *tokenType = TK_ILLEGAL;
  107062. return 1;
  107063. }
  107064. /*
  107065. ** Run the parser on the given SQL string. The parser structure is
  107066. ** passed in. An SQLITE_ status code is returned. If an error occurs
  107067. ** then an and attempt is made to write an error message into
  107068. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  107069. ** error message.
  107070. */
  107071. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  107072. int nErr = 0; /* Number of errors encountered */
  107073. int i; /* Loop counter */
  107074. void *pEngine; /* The LEMON-generated LALR(1) parser */
  107075. int tokenType; /* type of the next token */
  107076. int lastTokenParsed = -1; /* type of the previous token */
  107077. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  107078. sqlite3 *db = pParse->db; /* The database connection */
  107079. int mxSqlLen; /* Max length of an SQL string */
  107080. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  107081. if( db->activeVdbeCnt==0 ){
  107082. db->u1.isInterrupted = 0;
  107083. }
  107084. pParse->rc = SQLITE_OK;
  107085. pParse->zTail = zSql;
  107086. i = 0;
  107087. assert( pzErrMsg!=0 );
  107088. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  107089. if( pEngine==0 ){
  107090. db->mallocFailed = 1;
  107091. return SQLITE_NOMEM;
  107092. }
  107093. assert( pParse->pNewTable==0 );
  107094. assert( pParse->pNewTrigger==0 );
  107095. assert( pParse->nVar==0 );
  107096. assert( pParse->nzVar==0 );
  107097. assert( pParse->azVar==0 );
  107098. enableLookaside = db->lookaside.bEnabled;
  107099. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  107100. while( !db->mallocFailed && zSql[i]!=0 ){
  107101. assert( i>=0 );
  107102. pParse->sLastToken.z = &zSql[i];
  107103. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  107104. i += pParse->sLastToken.n;
  107105. if( i>mxSqlLen ){
  107106. pParse->rc = SQLITE_TOOBIG;
  107107. break;
  107108. }
  107109. switch( tokenType ){
  107110. case TK_SPACE: {
  107111. if( db->u1.isInterrupted ){
  107112. sqlite3ErrorMsg(pParse, "interrupt");
  107113. pParse->rc = SQLITE_INTERRUPT;
  107114. goto abort_parse;
  107115. }
  107116. break;
  107117. }
  107118. case TK_ILLEGAL: {
  107119. sqlite3DbFree(db, *pzErrMsg);
  107120. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  107121. &pParse->sLastToken);
  107122. nErr++;
  107123. goto abort_parse;
  107124. }
  107125. case TK_SEMI: {
  107126. pParse->zTail = &zSql[i];
  107127. /* Fall thru into the default case */
  107128. }
  107129. default: {
  107130. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  107131. lastTokenParsed = tokenType;
  107132. if( pParse->rc!=SQLITE_OK ){
  107133. goto abort_parse;
  107134. }
  107135. break;
  107136. }
  107137. }
  107138. }
  107139. abort_parse:
  107140. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  107141. if( lastTokenParsed!=TK_SEMI ){
  107142. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  107143. pParse->zTail = &zSql[i];
  107144. }
  107145. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  107146. }
  107147. #ifdef YYTRACKMAXSTACKDEPTH
  107148. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  107149. sqlite3ParserStackPeak(pEngine)
  107150. );
  107151. #endif /* YYDEBUG */
  107152. sqlite3ParserFree(pEngine, sqlite3_free);
  107153. db->lookaside.bEnabled = enableLookaside;
  107154. if( db->mallocFailed ){
  107155. pParse->rc = SQLITE_NOMEM;
  107156. }
  107157. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  107158. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  107159. }
  107160. assert( pzErrMsg!=0 );
  107161. if( pParse->zErrMsg ){
  107162. *pzErrMsg = pParse->zErrMsg;
  107163. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  107164. pParse->zErrMsg = 0;
  107165. nErr++;
  107166. }
  107167. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  107168. sqlite3VdbeDelete(pParse->pVdbe);
  107169. pParse->pVdbe = 0;
  107170. }
  107171. #ifndef SQLITE_OMIT_SHARED_CACHE
  107172. if( pParse->nested==0 ){
  107173. sqlite3DbFree(db, pParse->aTableLock);
  107174. pParse->aTableLock = 0;
  107175. pParse->nTableLock = 0;
  107176. }
  107177. #endif
  107178. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107179. sqlite3_free(pParse->apVtabLock);
  107180. #endif
  107181. if( !IN_DECLARE_VTAB ){
  107182. /* If the pParse->declareVtab flag is set, do not delete any table
  107183. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  107184. ** will take responsibility for freeing the Table structure.
  107185. */
  107186. sqlite3DeleteTable(db, pParse->pNewTable);
  107187. }
  107188. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  107189. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  107190. sqlite3DbFree(db, pParse->azVar);
  107191. sqlite3DbFree(db, pParse->aAlias);
  107192. while( pParse->pAinc ){
  107193. AutoincInfo *p = pParse->pAinc;
  107194. pParse->pAinc = p->pNext;
  107195. sqlite3DbFree(db, p);
  107196. }
  107197. while( pParse->pZombieTab ){
  107198. Table *p = pParse->pZombieTab;
  107199. pParse->pZombieTab = p->pNextZombie;
  107200. sqlite3DeleteTable(db, p);
  107201. }
  107202. if( nErr>0 && pParse->rc==SQLITE_OK ){
  107203. pParse->rc = SQLITE_ERROR;
  107204. }
  107205. return nErr;
  107206. }
  107207. /************** End of tokenize.c ********************************************/
  107208. /************** Begin file complete.c ****************************************/
  107209. /*
  107210. ** 2001 September 15
  107211. **
  107212. ** The author disclaims copyright to this source code. In place of
  107213. ** a legal notice, here is a blessing:
  107214. **
  107215. ** May you do good and not evil.
  107216. ** May you find forgiveness for yourself and forgive others.
  107217. ** May you share freely, never taking more than you give.
  107218. **
  107219. *************************************************************************
  107220. ** An tokenizer for SQL
  107221. **
  107222. ** This file contains C code that implements the sqlite3_complete() API.
  107223. ** This code used to be part of the tokenizer.c source file. But by
  107224. ** separating it out, the code will be automatically omitted from
  107225. ** static links that do not use it.
  107226. */
  107227. #ifndef SQLITE_OMIT_COMPLETE
  107228. /*
  107229. ** This is defined in tokenize.c. We just have to import the definition.
  107230. */
  107231. #ifndef SQLITE_AMALGAMATION
  107232. #ifdef SQLITE_ASCII
  107233. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  107234. #endif
  107235. #ifdef SQLITE_EBCDIC
  107236. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  107237. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  107238. #endif
  107239. #endif /* SQLITE_AMALGAMATION */
  107240. /*
  107241. ** Token types used by the sqlite3_complete() routine. See the header
  107242. ** comments on that procedure for additional information.
  107243. */
  107244. #define tkSEMI 0
  107245. #define tkWS 1
  107246. #define tkOTHER 2
  107247. #ifndef SQLITE_OMIT_TRIGGER
  107248. #define tkEXPLAIN 3
  107249. #define tkCREATE 4
  107250. #define tkTEMP 5
  107251. #define tkTRIGGER 6
  107252. #define tkEND 7
  107253. #endif
  107254. /*
  107255. ** Return TRUE if the given SQL string ends in a semicolon.
  107256. **
  107257. ** Special handling is require for CREATE TRIGGER statements.
  107258. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  107259. ** must end with ";END;".
  107260. **
  107261. ** This implementation uses a state machine with 8 states:
  107262. **
  107263. ** (0) INVALID We have not yet seen a non-whitespace character.
  107264. **
  107265. ** (1) START At the beginning or end of an SQL statement. This routine
  107266. ** returns 1 if it ends in the START state and 0 if it ends
  107267. ** in any other state.
  107268. **
  107269. ** (2) NORMAL We are in the middle of statement which ends with a single
  107270. ** semicolon.
  107271. **
  107272. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  107273. ** a statement.
  107274. **
  107275. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  107276. ** statement, possibly preceeded by EXPLAIN and/or followed by
  107277. ** TEMP or TEMPORARY
  107278. **
  107279. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  107280. ** ended by a semicolon, the keyword END, and another semicolon.
  107281. **
  107282. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  107283. ** the end of a trigger definition.
  107284. **
  107285. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  107286. ** of a trigger difinition.
  107287. **
  107288. ** Transitions between states above are determined by tokens extracted
  107289. ** from the input. The following tokens are significant:
  107290. **
  107291. ** (0) tkSEMI A semicolon.
  107292. ** (1) tkWS Whitespace.
  107293. ** (2) tkOTHER Any other SQL token.
  107294. ** (3) tkEXPLAIN The "explain" keyword.
  107295. ** (4) tkCREATE The "create" keyword.
  107296. ** (5) tkTEMP The "temp" or "temporary" keyword.
  107297. ** (6) tkTRIGGER The "trigger" keyword.
  107298. ** (7) tkEND The "end" keyword.
  107299. **
  107300. ** Whitespace never causes a state transition and is always ignored.
  107301. ** This means that a SQL string of all whitespace is invalid.
  107302. **
  107303. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  107304. ** to recognize the end of a trigger can be omitted. All we have to do
  107305. ** is look for a semicolon that is not part of an string or comment.
  107306. */
  107307. SQLITE_API int sqlite3_complete(const char *zSql){
  107308. u8 state = 0; /* Current state, using numbers defined in header comment */
  107309. u8 token; /* Value of the next token */
  107310. #ifndef SQLITE_OMIT_TRIGGER
  107311. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  107312. ** statement. This is the normal case.
  107313. */
  107314. static const u8 trans[8][8] = {
  107315. /* Token: */
  107316. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  107317. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  107318. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  107319. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  107320. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  107321. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  107322. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  107323. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  107324. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  107325. };
  107326. #else
  107327. /* If triggers are not supported by this compile then the statement machine
  107328. ** used to detect the end of a statement is much simplier
  107329. */
  107330. static const u8 trans[3][3] = {
  107331. /* Token: */
  107332. /* State: ** SEMI WS OTHER */
  107333. /* 0 INVALID: */ { 1, 0, 2, },
  107334. /* 1 START: */ { 1, 1, 2, },
  107335. /* 2 NORMAL: */ { 1, 2, 2, },
  107336. };
  107337. #endif /* SQLITE_OMIT_TRIGGER */
  107338. while( *zSql ){
  107339. switch( *zSql ){
  107340. case ';': { /* A semicolon */
  107341. token = tkSEMI;
  107342. break;
  107343. }
  107344. case ' ':
  107345. case '\r':
  107346. case '\t':
  107347. case '\n':
  107348. case '\f': { /* White space is ignored */
  107349. token = tkWS;
  107350. break;
  107351. }
  107352. case '/': { /* C-style comments */
  107353. if( zSql[1]!='*' ){
  107354. token = tkOTHER;
  107355. break;
  107356. }
  107357. zSql += 2;
  107358. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  107359. if( zSql[0]==0 ) return 0;
  107360. zSql++;
  107361. token = tkWS;
  107362. break;
  107363. }
  107364. case '-': { /* SQL-style comments from "--" to end of line */
  107365. if( zSql[1]!='-' ){
  107366. token = tkOTHER;
  107367. break;
  107368. }
  107369. while( *zSql && *zSql!='\n' ){ zSql++; }
  107370. if( *zSql==0 ) return state==1;
  107371. token = tkWS;
  107372. break;
  107373. }
  107374. case '[': { /* Microsoft-style identifiers in [...] */
  107375. zSql++;
  107376. while( *zSql && *zSql!=']' ){ zSql++; }
  107377. if( *zSql==0 ) return 0;
  107378. token = tkOTHER;
  107379. break;
  107380. }
  107381. case '`': /* Grave-accent quoted symbols used by MySQL */
  107382. case '"': /* single- and double-quoted strings */
  107383. case '\'': {
  107384. int c = *zSql;
  107385. zSql++;
  107386. while( *zSql && *zSql!=c ){ zSql++; }
  107387. if( *zSql==0 ) return 0;
  107388. token = tkOTHER;
  107389. break;
  107390. }
  107391. default: {
  107392. #ifdef SQLITE_EBCDIC
  107393. unsigned char c;
  107394. #endif
  107395. if( IdChar((u8)*zSql) ){
  107396. /* Keywords and unquoted identifiers */
  107397. int nId;
  107398. for(nId=1; IdChar(zSql[nId]); nId++){}
  107399. #ifdef SQLITE_OMIT_TRIGGER
  107400. token = tkOTHER;
  107401. #else
  107402. switch( *zSql ){
  107403. case 'c': case 'C': {
  107404. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  107405. token = tkCREATE;
  107406. }else{
  107407. token = tkOTHER;
  107408. }
  107409. break;
  107410. }
  107411. case 't': case 'T': {
  107412. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  107413. token = tkTRIGGER;
  107414. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  107415. token = tkTEMP;
  107416. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  107417. token = tkTEMP;
  107418. }else{
  107419. token = tkOTHER;
  107420. }
  107421. break;
  107422. }
  107423. case 'e': case 'E': {
  107424. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  107425. token = tkEND;
  107426. }else
  107427. #ifndef SQLITE_OMIT_EXPLAIN
  107428. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  107429. token = tkEXPLAIN;
  107430. }else
  107431. #endif
  107432. {
  107433. token = tkOTHER;
  107434. }
  107435. break;
  107436. }
  107437. default: {
  107438. token = tkOTHER;
  107439. break;
  107440. }
  107441. }
  107442. #endif /* SQLITE_OMIT_TRIGGER */
  107443. zSql += nId-1;
  107444. }else{
  107445. /* Operators and special symbols */
  107446. token = tkOTHER;
  107447. }
  107448. break;
  107449. }
  107450. }
  107451. state = trans[state][token];
  107452. zSql++;
  107453. }
  107454. return state==1;
  107455. }
  107456. #ifndef SQLITE_OMIT_UTF16
  107457. /*
  107458. ** This routine is the same as the sqlite3_complete() routine described
  107459. ** above, except that the parameter is required to be UTF-16 encoded, not
  107460. ** UTF-8.
  107461. */
  107462. SQLITE_API int sqlite3_complete16(const void *zSql){
  107463. sqlite3_value *pVal;
  107464. char const *zSql8;
  107465. int rc = SQLITE_NOMEM;
  107466. #ifndef SQLITE_OMIT_AUTOINIT
  107467. rc = sqlite3_initialize();
  107468. if( rc ) return rc;
  107469. #endif
  107470. pVal = sqlite3ValueNew(0);
  107471. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  107472. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  107473. if( zSql8 ){
  107474. rc = sqlite3_complete(zSql8);
  107475. }else{
  107476. rc = SQLITE_NOMEM;
  107477. }
  107478. sqlite3ValueFree(pVal);
  107479. return sqlite3ApiExit(0, rc);
  107480. }
  107481. #endif /* SQLITE_OMIT_UTF16 */
  107482. #endif /* SQLITE_OMIT_COMPLETE */
  107483. /************** End of complete.c ********************************************/
  107484. /************** Begin file main.c ********************************************/
  107485. /*
  107486. ** 2001 September 15
  107487. **
  107488. ** The author disclaims copyright to this source code. In place of
  107489. ** a legal notice, here is a blessing:
  107490. **
  107491. ** May you do good and not evil.
  107492. ** May you find forgiveness for yourself and forgive others.
  107493. ** May you share freely, never taking more than you give.
  107494. **
  107495. *************************************************************************
  107496. ** Main file for the SQLite library. The routines in this file
  107497. ** implement the programmer interface to the library. Routines in
  107498. ** other files are for internal use by SQLite and should not be
  107499. ** accessed by users of the library.
  107500. */
  107501. #ifdef SQLITE_ENABLE_FTS3
  107502. /************** Include fts3.h in the middle of main.c ***********************/
  107503. /************** Begin file fts3.h ********************************************/
  107504. /*
  107505. ** 2006 Oct 10
  107506. **
  107507. ** The author disclaims copyright to this source code. In place of
  107508. ** a legal notice, here is a blessing:
  107509. **
  107510. ** May you do good and not evil.
  107511. ** May you find forgiveness for yourself and forgive others.
  107512. ** May you share freely, never taking more than you give.
  107513. **
  107514. ******************************************************************************
  107515. **
  107516. ** This header file is used by programs that want to link against the
  107517. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  107518. */
  107519. #if 0
  107520. extern "C" {
  107521. #endif /* __cplusplus */
  107522. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  107523. #if 0
  107524. } /* extern "C" */
  107525. #endif /* __cplusplus */
  107526. /************** End of fts3.h ************************************************/
  107527. /************** Continuing where we left off in main.c ***********************/
  107528. #endif
  107529. #ifdef SQLITE_ENABLE_RTREE
  107530. /************** Include rtree.h in the middle of main.c **********************/
  107531. /************** Begin file rtree.h *******************************************/
  107532. /*
  107533. ** 2008 May 26
  107534. **
  107535. ** The author disclaims copyright to this source code. In place of
  107536. ** a legal notice, here is a blessing:
  107537. **
  107538. ** May you do good and not evil.
  107539. ** May you find forgiveness for yourself and forgive others.
  107540. ** May you share freely, never taking more than you give.
  107541. **
  107542. ******************************************************************************
  107543. **
  107544. ** This header file is used by programs that want to link against the
  107545. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  107546. */
  107547. #if 0
  107548. extern "C" {
  107549. #endif /* __cplusplus */
  107550. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  107551. #if 0
  107552. } /* extern "C" */
  107553. #endif /* __cplusplus */
  107554. /************** End of rtree.h ***********************************************/
  107555. /************** Continuing where we left off in main.c ***********************/
  107556. #endif
  107557. #ifdef SQLITE_ENABLE_ICU
  107558. /************** Include sqliteicu.h in the middle of main.c ******************/
  107559. /************** Begin file sqliteicu.h ***************************************/
  107560. /*
  107561. ** 2008 May 26
  107562. **
  107563. ** The author disclaims copyright to this source code. In place of
  107564. ** a legal notice, here is a blessing:
  107565. **
  107566. ** May you do good and not evil.
  107567. ** May you find forgiveness for yourself and forgive others.
  107568. ** May you share freely, never taking more than you give.
  107569. **
  107570. ******************************************************************************
  107571. **
  107572. ** This header file is used by programs that want to link against the
  107573. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  107574. */
  107575. #if 0
  107576. extern "C" {
  107577. #endif /* __cplusplus */
  107578. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  107579. #if 0
  107580. } /* extern "C" */
  107581. #endif /* __cplusplus */
  107582. /************** End of sqliteicu.h *******************************************/
  107583. /************** Continuing where we left off in main.c ***********************/
  107584. #endif
  107585. #ifndef SQLITE_AMALGAMATION
  107586. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  107587. ** contains the text of SQLITE_VERSION macro.
  107588. */
  107589. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  107590. #endif
  107591. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  107592. ** a pointer to the to the sqlite3_version[] string constant.
  107593. */
  107594. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  107595. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  107596. ** pointer to a string constant whose value is the same as the
  107597. ** SQLITE_SOURCE_ID C preprocessor macro.
  107598. */
  107599. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  107600. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  107601. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  107602. */
  107603. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  107604. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  107605. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  107606. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  107607. */
  107608. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  107609. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  107610. /*
  107611. ** If the following function pointer is not NULL and if
  107612. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  107613. ** I/O active are written using this function. These messages
  107614. ** are intended for debugging activity only.
  107615. */
  107616. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  107617. #endif
  107618. /*
  107619. ** If the following global variable points to a string which is the
  107620. ** name of a directory, then that directory will be used to store
  107621. ** temporary files.
  107622. **
  107623. ** See also the "PRAGMA temp_store_directory" SQL command.
  107624. */
  107625. SQLITE_API char *sqlite3_temp_directory = 0;
  107626. /*
  107627. ** If the following global variable points to a string which is the
  107628. ** name of a directory, then that directory will be used to store
  107629. ** all database files specified with a relative pathname.
  107630. **
  107631. ** See also the "PRAGMA data_store_directory" SQL command.
  107632. */
  107633. SQLITE_API char *sqlite3_data_directory = 0;
  107634. /*
  107635. ** Initialize SQLite.
  107636. **
  107637. ** This routine must be called to initialize the memory allocation,
  107638. ** VFS, and mutex subsystems prior to doing any serious work with
  107639. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  107640. ** this routine will be called automatically by key routines such as
  107641. ** sqlite3_open().
  107642. **
  107643. ** This routine is a no-op except on its very first call for the process,
  107644. ** or for the first call after a call to sqlite3_shutdown.
  107645. **
  107646. ** The first thread to call this routine runs the initialization to
  107647. ** completion. If subsequent threads call this routine before the first
  107648. ** thread has finished the initialization process, then the subsequent
  107649. ** threads must block until the first thread finishes with the initialization.
  107650. **
  107651. ** The first thread might call this routine recursively. Recursive
  107652. ** calls to this routine should not block, of course. Otherwise the
  107653. ** initialization process would never complete.
  107654. **
  107655. ** Let X be the first thread to enter this routine. Let Y be some other
  107656. ** thread. Then while the initial invocation of this routine by X is
  107657. ** incomplete, it is required that:
  107658. **
  107659. ** * Calls to this routine from Y must block until the outer-most
  107660. ** call by X completes.
  107661. **
  107662. ** * Recursive calls to this routine from thread X return immediately
  107663. ** without blocking.
  107664. */
  107665. SQLITE_API int sqlite3_initialize(void){
  107666. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  107667. int rc; /* Result code */
  107668. #ifdef SQLITE_OMIT_WSD
  107669. rc = sqlite3_wsd_init(4096, 24);
  107670. if( rc!=SQLITE_OK ){
  107671. return rc;
  107672. }
  107673. #endif
  107674. /* If SQLite is already completely initialized, then this call
  107675. ** to sqlite3_initialize() should be a no-op. But the initialization
  107676. ** must be complete. So isInit must not be set until the very end
  107677. ** of this routine.
  107678. */
  107679. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  107680. #ifdef SQLITE_ENABLE_SQLLOG
  107681. {
  107682. extern void sqlite3_init_sqllog(void);
  107683. sqlite3_init_sqllog();
  107684. }
  107685. #endif
  107686. /* Make sure the mutex subsystem is initialized. If unable to
  107687. ** initialize the mutex subsystem, return early with the error.
  107688. ** If the system is so sick that we are unable to allocate a mutex,
  107689. ** there is not much SQLite is going to be able to do.
  107690. **
  107691. ** The mutex subsystem must take care of serializing its own
  107692. ** initialization.
  107693. */
  107694. rc = sqlite3MutexInit();
  107695. if( rc ) return rc;
  107696. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  107697. ** This operation is protected by the STATIC_MASTER mutex. Note that
  107698. ** MutexAlloc() is called for a static mutex prior to initializing the
  107699. ** malloc subsystem - this implies that the allocation of a static
  107700. ** mutex must not require support from the malloc subsystem.
  107701. */
  107702. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  107703. sqlite3_mutex_enter(pMaster);
  107704. sqlite3GlobalConfig.isMutexInit = 1;
  107705. if( !sqlite3GlobalConfig.isMallocInit ){
  107706. rc = sqlite3MallocInit();
  107707. }
  107708. if( rc==SQLITE_OK ){
  107709. sqlite3GlobalConfig.isMallocInit = 1;
  107710. if( !sqlite3GlobalConfig.pInitMutex ){
  107711. sqlite3GlobalConfig.pInitMutex =
  107712. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  107713. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  107714. rc = SQLITE_NOMEM;
  107715. }
  107716. }
  107717. }
  107718. if( rc==SQLITE_OK ){
  107719. sqlite3GlobalConfig.nRefInitMutex++;
  107720. }
  107721. sqlite3_mutex_leave(pMaster);
  107722. /* If rc is not SQLITE_OK at this point, then either the malloc
  107723. ** subsystem could not be initialized or the system failed to allocate
  107724. ** the pInitMutex mutex. Return an error in either case. */
  107725. if( rc!=SQLITE_OK ){
  107726. return rc;
  107727. }
  107728. /* Do the rest of the initialization under the recursive mutex so
  107729. ** that we will be able to handle recursive calls into
  107730. ** sqlite3_initialize(). The recursive calls normally come through
  107731. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  107732. ** recursive calls might also be possible.
  107733. **
  107734. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  107735. ** to the xInit method, so the xInit method need not be threadsafe.
  107736. **
  107737. ** The following mutex is what serializes access to the appdef pcache xInit
  107738. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  107739. ** call to sqlite3PcacheInitialize().
  107740. */
  107741. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  107742. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  107743. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  107744. sqlite3GlobalConfig.inProgress = 1;
  107745. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  107746. sqlite3RegisterGlobalFunctions();
  107747. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  107748. rc = sqlite3PcacheInitialize();
  107749. }
  107750. if( rc==SQLITE_OK ){
  107751. sqlite3GlobalConfig.isPCacheInit = 1;
  107752. rc = sqlite3OsInit();
  107753. }
  107754. if( rc==SQLITE_OK ){
  107755. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  107756. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  107757. sqlite3GlobalConfig.isInit = 1;
  107758. }
  107759. sqlite3GlobalConfig.inProgress = 0;
  107760. }
  107761. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  107762. /* Go back under the static mutex and clean up the recursive
  107763. ** mutex to prevent a resource leak.
  107764. */
  107765. sqlite3_mutex_enter(pMaster);
  107766. sqlite3GlobalConfig.nRefInitMutex--;
  107767. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  107768. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  107769. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  107770. sqlite3GlobalConfig.pInitMutex = 0;
  107771. }
  107772. sqlite3_mutex_leave(pMaster);
  107773. /* The following is just a sanity check to make sure SQLite has
  107774. ** been compiled correctly. It is important to run this code, but
  107775. ** we don't want to run it too often and soak up CPU cycles for no
  107776. ** reason. So we run it once during initialization.
  107777. */
  107778. #ifndef NDEBUG
  107779. #ifndef SQLITE_OMIT_FLOATING_POINT
  107780. /* This section of code's only "output" is via assert() statements. */
  107781. if ( rc==SQLITE_OK ){
  107782. u64 x = (((u64)1)<<63)-1;
  107783. double y;
  107784. assert(sizeof(x)==8);
  107785. assert(sizeof(x)==sizeof(y));
  107786. memcpy(&y, &x, 8);
  107787. assert( sqlite3IsNaN(y) );
  107788. }
  107789. #endif
  107790. #endif
  107791. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  107792. ** compile-time option.
  107793. */
  107794. #ifdef SQLITE_EXTRA_INIT
  107795. if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
  107796. int SQLITE_EXTRA_INIT(const char*);
  107797. rc = SQLITE_EXTRA_INIT(0);
  107798. }
  107799. #endif
  107800. return rc;
  107801. }
  107802. /*
  107803. ** Undo the effects of sqlite3_initialize(). Must not be called while
  107804. ** there are outstanding database connections or memory allocations or
  107805. ** while any part of SQLite is otherwise in use in any thread. This
  107806. ** routine is not threadsafe. But it is safe to invoke this routine
  107807. ** on when SQLite is already shut down. If SQLite is already shut down
  107808. ** when this routine is invoked, then this routine is a harmless no-op.
  107809. */
  107810. SQLITE_API int sqlite3_shutdown(void){
  107811. if( sqlite3GlobalConfig.isInit ){
  107812. #ifdef SQLITE_EXTRA_SHUTDOWN
  107813. void SQLITE_EXTRA_SHUTDOWN(void);
  107814. SQLITE_EXTRA_SHUTDOWN();
  107815. #endif
  107816. sqlite3_os_end();
  107817. sqlite3_reset_auto_extension();
  107818. sqlite3GlobalConfig.isInit = 0;
  107819. }
  107820. if( sqlite3GlobalConfig.isPCacheInit ){
  107821. sqlite3PcacheShutdown();
  107822. sqlite3GlobalConfig.isPCacheInit = 0;
  107823. }
  107824. if( sqlite3GlobalConfig.isMallocInit ){
  107825. sqlite3MallocEnd();
  107826. sqlite3GlobalConfig.isMallocInit = 0;
  107827. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  107828. /* The heap subsystem has now been shutdown and these values are supposed
  107829. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  107830. ** which would rely on that heap subsystem; therefore, make sure these
  107831. ** values cannot refer to heap memory that was just invalidated when the
  107832. ** heap subsystem was shutdown. This is only done if the current call to
  107833. ** this function resulted in the heap subsystem actually being shutdown.
  107834. */
  107835. sqlite3_data_directory = 0;
  107836. sqlite3_temp_directory = 0;
  107837. #endif
  107838. }
  107839. if( sqlite3GlobalConfig.isMutexInit ){
  107840. sqlite3MutexEnd();
  107841. sqlite3GlobalConfig.isMutexInit = 0;
  107842. }
  107843. return SQLITE_OK;
  107844. }
  107845. /*
  107846. ** This API allows applications to modify the global configuration of
  107847. ** the SQLite library at run-time.
  107848. **
  107849. ** This routine should only be called when there are no outstanding
  107850. ** database connections or memory allocations. This routine is not
  107851. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  107852. ** behavior.
  107853. */
  107854. SQLITE_API int sqlite3_config(int op, ...){
  107855. va_list ap;
  107856. int rc = SQLITE_OK;
  107857. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  107858. ** the SQLite library is in use. */
  107859. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  107860. va_start(ap, op);
  107861. switch( op ){
  107862. /* Mutex configuration options are only available in a threadsafe
  107863. ** compile.
  107864. */
  107865. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  107866. case SQLITE_CONFIG_SINGLETHREAD: {
  107867. /* Disable all mutexing */
  107868. sqlite3GlobalConfig.bCoreMutex = 0;
  107869. sqlite3GlobalConfig.bFullMutex = 0;
  107870. break;
  107871. }
  107872. case SQLITE_CONFIG_MULTITHREAD: {
  107873. /* Disable mutexing of database connections */
  107874. /* Enable mutexing of core data structures */
  107875. sqlite3GlobalConfig.bCoreMutex = 1;
  107876. sqlite3GlobalConfig.bFullMutex = 0;
  107877. break;
  107878. }
  107879. case SQLITE_CONFIG_SERIALIZED: {
  107880. /* Enable all mutexing */
  107881. sqlite3GlobalConfig.bCoreMutex = 1;
  107882. sqlite3GlobalConfig.bFullMutex = 1;
  107883. break;
  107884. }
  107885. case SQLITE_CONFIG_MUTEX: {
  107886. /* Specify an alternative mutex implementation */
  107887. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  107888. break;
  107889. }
  107890. case SQLITE_CONFIG_GETMUTEX: {
  107891. /* Retrieve the current mutex implementation */
  107892. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  107893. break;
  107894. }
  107895. #endif
  107896. case SQLITE_CONFIG_MALLOC: {
  107897. /* Specify an alternative malloc implementation */
  107898. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  107899. break;
  107900. }
  107901. case SQLITE_CONFIG_GETMALLOC: {
  107902. /* Retrieve the current malloc() implementation */
  107903. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  107904. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  107905. break;
  107906. }
  107907. case SQLITE_CONFIG_MEMSTATUS: {
  107908. /* Enable or disable the malloc status collection */
  107909. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  107910. break;
  107911. }
  107912. case SQLITE_CONFIG_SCRATCH: {
  107913. /* Designate a buffer for scratch memory space */
  107914. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  107915. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  107916. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  107917. break;
  107918. }
  107919. case SQLITE_CONFIG_PAGECACHE: {
  107920. /* Designate a buffer for page cache memory space */
  107921. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  107922. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  107923. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  107924. break;
  107925. }
  107926. case SQLITE_CONFIG_PCACHE: {
  107927. /* no-op */
  107928. break;
  107929. }
  107930. case SQLITE_CONFIG_GETPCACHE: {
  107931. /* now an error */
  107932. rc = SQLITE_ERROR;
  107933. break;
  107934. }
  107935. case SQLITE_CONFIG_PCACHE2: {
  107936. /* Specify an alternative page cache implementation */
  107937. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  107938. break;
  107939. }
  107940. case SQLITE_CONFIG_GETPCACHE2: {
  107941. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  107942. sqlite3PCacheSetDefault();
  107943. }
  107944. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  107945. break;
  107946. }
  107947. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  107948. case SQLITE_CONFIG_HEAP: {
  107949. /* Designate a buffer for heap memory space */
  107950. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  107951. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  107952. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  107953. if( sqlite3GlobalConfig.mnReq<1 ){
  107954. sqlite3GlobalConfig.mnReq = 1;
  107955. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  107956. /* cap min request size at 2^12 */
  107957. sqlite3GlobalConfig.mnReq = (1<<12);
  107958. }
  107959. if( sqlite3GlobalConfig.pHeap==0 ){
  107960. /* If the heap pointer is NULL, then restore the malloc implementation
  107961. ** back to NULL pointers too. This will cause the malloc to go
  107962. ** back to its default implementation when sqlite3_initialize() is
  107963. ** run.
  107964. */
  107965. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  107966. }else{
  107967. /* The heap pointer is not NULL, then install one of the
  107968. ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
  107969. ** ENABLE_MEMSYS5 is defined, return an error.
  107970. */
  107971. #ifdef SQLITE_ENABLE_MEMSYS3
  107972. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  107973. #endif
  107974. #ifdef SQLITE_ENABLE_MEMSYS5
  107975. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  107976. #endif
  107977. }
  107978. break;
  107979. }
  107980. #endif
  107981. case SQLITE_CONFIG_LOOKASIDE: {
  107982. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  107983. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  107984. break;
  107985. }
  107986. /* Record a pointer to the logger funcction and its first argument.
  107987. ** The default is NULL. Logging is disabled if the function pointer is
  107988. ** NULL.
  107989. */
  107990. case SQLITE_CONFIG_LOG: {
  107991. /* MSVC is picky about pulling func ptrs from va lists.
  107992. ** http://support.microsoft.com/kb/47961
  107993. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  107994. */
  107995. typedef void(*LOGFUNC_t)(void*,int,const char*);
  107996. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  107997. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  107998. break;
  107999. }
  108000. case SQLITE_CONFIG_URI: {
  108001. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  108002. break;
  108003. }
  108004. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  108005. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  108006. break;
  108007. }
  108008. #ifdef SQLITE_ENABLE_SQLLOG
  108009. case SQLITE_CONFIG_SQLLOG: {
  108010. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  108011. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  108012. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  108013. break;
  108014. }
  108015. #endif
  108016. case SQLITE_CONFIG_MMAP_SIZE: {
  108017. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  108018. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  108019. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  108020. mxMmap = SQLITE_MAX_MMAP_SIZE;
  108021. }
  108022. sqlite3GlobalConfig.mxMmap = mxMmap;
  108023. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  108024. if( szMmap>mxMmap) szMmap = mxMmap;
  108025. sqlite3GlobalConfig.szMmap = szMmap;
  108026. break;
  108027. }
  108028. default: {
  108029. rc = SQLITE_ERROR;
  108030. break;
  108031. }
  108032. }
  108033. va_end(ap);
  108034. return rc;
  108035. }
  108036. /*
  108037. ** Set up the lookaside buffers for a database connection.
  108038. ** Return SQLITE_OK on success.
  108039. ** If lookaside is already active, return SQLITE_BUSY.
  108040. **
  108041. ** The sz parameter is the number of bytes in each lookaside slot.
  108042. ** The cnt parameter is the number of slots. If pStart is NULL the
  108043. ** space for the lookaside memory is obtained from sqlite3_malloc().
  108044. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  108045. ** the lookaside memory.
  108046. */
  108047. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  108048. void *pStart;
  108049. if( db->lookaside.nOut ){
  108050. return SQLITE_BUSY;
  108051. }
  108052. /* Free any existing lookaside buffer for this handle before
  108053. ** allocating a new one so we don't have to have space for
  108054. ** both at the same time.
  108055. */
  108056. if( db->lookaside.bMalloced ){
  108057. sqlite3_free(db->lookaside.pStart);
  108058. }
  108059. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  108060. ** than a pointer to be useful.
  108061. */
  108062. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  108063. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  108064. if( cnt<0 ) cnt = 0;
  108065. if( sz==0 || cnt==0 ){
  108066. sz = 0;
  108067. pStart = 0;
  108068. }else if( pBuf==0 ){
  108069. sqlite3BeginBenignMalloc();
  108070. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  108071. sqlite3EndBenignMalloc();
  108072. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  108073. }else{
  108074. pStart = pBuf;
  108075. }
  108076. db->lookaside.pStart = pStart;
  108077. db->lookaside.pFree = 0;
  108078. db->lookaside.sz = (u16)sz;
  108079. if( pStart ){
  108080. int i;
  108081. LookasideSlot *p;
  108082. assert( sz > (int)sizeof(LookasideSlot*) );
  108083. p = (LookasideSlot*)pStart;
  108084. for(i=cnt-1; i>=0; i--){
  108085. p->pNext = db->lookaside.pFree;
  108086. db->lookaside.pFree = p;
  108087. p = (LookasideSlot*)&((u8*)p)[sz];
  108088. }
  108089. db->lookaside.pEnd = p;
  108090. db->lookaside.bEnabled = 1;
  108091. db->lookaside.bMalloced = pBuf==0 ?1:0;
  108092. }else{
  108093. db->lookaside.pEnd = 0;
  108094. db->lookaside.bEnabled = 0;
  108095. db->lookaside.bMalloced = 0;
  108096. }
  108097. return SQLITE_OK;
  108098. }
  108099. /*
  108100. ** Return the mutex associated with a database connection.
  108101. */
  108102. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  108103. return db->mutex;
  108104. }
  108105. /*
  108106. ** Free up as much memory as we can from the given database
  108107. ** connection.
  108108. */
  108109. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  108110. int i;
  108111. sqlite3_mutex_enter(db->mutex);
  108112. sqlite3BtreeEnterAll(db);
  108113. for(i=0; i<db->nDb; i++){
  108114. Btree *pBt = db->aDb[i].pBt;
  108115. if( pBt ){
  108116. Pager *pPager = sqlite3BtreePager(pBt);
  108117. sqlite3PagerShrink(pPager);
  108118. }
  108119. }
  108120. sqlite3BtreeLeaveAll(db);
  108121. sqlite3_mutex_leave(db->mutex);
  108122. return SQLITE_OK;
  108123. }
  108124. /*
  108125. ** Configuration settings for an individual database connection
  108126. */
  108127. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  108128. va_list ap;
  108129. int rc;
  108130. va_start(ap, op);
  108131. switch( op ){
  108132. case SQLITE_DBCONFIG_LOOKASIDE: {
  108133. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  108134. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  108135. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  108136. rc = setupLookaside(db, pBuf, sz, cnt);
  108137. break;
  108138. }
  108139. default: {
  108140. static const struct {
  108141. int op; /* The opcode */
  108142. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  108143. } aFlagOp[] = {
  108144. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  108145. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  108146. };
  108147. unsigned int i;
  108148. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  108149. for(i=0; i<ArraySize(aFlagOp); i++){
  108150. if( aFlagOp[i].op==op ){
  108151. int onoff = va_arg(ap, int);
  108152. int *pRes = va_arg(ap, int*);
  108153. int oldFlags = db->flags;
  108154. if( onoff>0 ){
  108155. db->flags |= aFlagOp[i].mask;
  108156. }else if( onoff==0 ){
  108157. db->flags &= ~aFlagOp[i].mask;
  108158. }
  108159. if( oldFlags!=db->flags ){
  108160. sqlite3ExpirePreparedStatements(db);
  108161. }
  108162. if( pRes ){
  108163. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  108164. }
  108165. rc = SQLITE_OK;
  108166. break;
  108167. }
  108168. }
  108169. break;
  108170. }
  108171. }
  108172. va_end(ap);
  108173. return rc;
  108174. }
  108175. /*
  108176. ** Return true if the buffer z[0..n-1] contains all spaces.
  108177. */
  108178. static int allSpaces(const char *z, int n){
  108179. while( n>0 && z[n-1]==' ' ){ n--; }
  108180. return n==0;
  108181. }
  108182. /*
  108183. ** This is the default collating function named "BINARY" which is always
  108184. ** available.
  108185. **
  108186. ** If the padFlag argument is not NULL then space padding at the end
  108187. ** of strings is ignored. This implements the RTRIM collation.
  108188. */
  108189. static int binCollFunc(
  108190. void *padFlag,
  108191. int nKey1, const void *pKey1,
  108192. int nKey2, const void *pKey2
  108193. ){
  108194. int rc, n;
  108195. n = nKey1<nKey2 ? nKey1 : nKey2;
  108196. rc = memcmp(pKey1, pKey2, n);
  108197. if( rc==0 ){
  108198. if( padFlag
  108199. && allSpaces(((char*)pKey1)+n, nKey1-n)
  108200. && allSpaces(((char*)pKey2)+n, nKey2-n)
  108201. ){
  108202. /* Leave rc unchanged at 0 */
  108203. }else{
  108204. rc = nKey1 - nKey2;
  108205. }
  108206. }
  108207. return rc;
  108208. }
  108209. /*
  108210. ** Another built-in collating sequence: NOCASE.
  108211. **
  108212. ** This collating sequence is intended to be used for "case independant
  108213. ** comparison". SQLite's knowledge of upper and lower case equivalents
  108214. ** extends only to the 26 characters used in the English language.
  108215. **
  108216. ** At the moment there is only a UTF-8 implementation.
  108217. */
  108218. static int nocaseCollatingFunc(
  108219. void *NotUsed,
  108220. int nKey1, const void *pKey1,
  108221. int nKey2, const void *pKey2
  108222. ){
  108223. int r = sqlite3StrNICmp(
  108224. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  108225. UNUSED_PARAMETER(NotUsed);
  108226. if( 0==r ){
  108227. r = nKey1-nKey2;
  108228. }
  108229. return r;
  108230. }
  108231. /*
  108232. ** Return the ROWID of the most recent insert
  108233. */
  108234. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  108235. return db->lastRowid;
  108236. }
  108237. /*
  108238. ** Return the number of changes in the most recent call to sqlite3_exec().
  108239. */
  108240. SQLITE_API int sqlite3_changes(sqlite3 *db){
  108241. return db->nChange;
  108242. }
  108243. /*
  108244. ** Return the number of changes since the database handle was opened.
  108245. */
  108246. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  108247. return db->nTotalChange;
  108248. }
  108249. /*
  108250. ** Close all open savepoints. This function only manipulates fields of the
  108251. ** database handle object, it does not close any savepoints that may be open
  108252. ** at the b-tree/pager level.
  108253. */
  108254. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  108255. while( db->pSavepoint ){
  108256. Savepoint *pTmp = db->pSavepoint;
  108257. db->pSavepoint = pTmp->pNext;
  108258. sqlite3DbFree(db, pTmp);
  108259. }
  108260. db->nSavepoint = 0;
  108261. db->nStatement = 0;
  108262. db->isTransactionSavepoint = 0;
  108263. }
  108264. /*
  108265. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  108266. ** if this is not the last copy of the function, do not invoke it. Multiple
  108267. ** copies of a single function are created when create_function() is called
  108268. ** with SQLITE_ANY as the encoding.
  108269. */
  108270. static void functionDestroy(sqlite3 *db, FuncDef *p){
  108271. FuncDestructor *pDestructor = p->pDestructor;
  108272. if( pDestructor ){
  108273. pDestructor->nRef--;
  108274. if( pDestructor->nRef==0 ){
  108275. pDestructor->xDestroy(pDestructor->pUserData);
  108276. sqlite3DbFree(db, pDestructor);
  108277. }
  108278. }
  108279. }
  108280. /*
  108281. ** Disconnect all sqlite3_vtab objects that belong to database connection
  108282. ** db. This is called when db is being closed.
  108283. */
  108284. static void disconnectAllVtab(sqlite3 *db){
  108285. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108286. int i;
  108287. sqlite3BtreeEnterAll(db);
  108288. for(i=0; i<db->nDb; i++){
  108289. Schema *pSchema = db->aDb[i].pSchema;
  108290. if( db->aDb[i].pSchema ){
  108291. HashElem *p;
  108292. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  108293. Table *pTab = (Table *)sqliteHashData(p);
  108294. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  108295. }
  108296. }
  108297. }
  108298. sqlite3BtreeLeaveAll(db);
  108299. #else
  108300. UNUSED_PARAMETER(db);
  108301. #endif
  108302. }
  108303. /*
  108304. ** Return TRUE if database connection db has unfinalized prepared
  108305. ** statements or unfinished sqlite3_backup objects.
  108306. */
  108307. static int connectionIsBusy(sqlite3 *db){
  108308. int j;
  108309. assert( sqlite3_mutex_held(db->mutex) );
  108310. if( db->pVdbe ) return 1;
  108311. for(j=0; j<db->nDb; j++){
  108312. Btree *pBt = db->aDb[j].pBt;
  108313. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  108314. }
  108315. return 0;
  108316. }
  108317. /*
  108318. ** Close an existing SQLite database
  108319. */
  108320. static int sqlite3Close(sqlite3 *db, int forceZombie){
  108321. if( !db ){
  108322. return SQLITE_OK;
  108323. }
  108324. if( !sqlite3SafetyCheckSickOrOk(db) ){
  108325. return SQLITE_MISUSE_BKPT;
  108326. }
  108327. sqlite3_mutex_enter(db->mutex);
  108328. /* Force xDisconnect calls on all virtual tables */
  108329. disconnectAllVtab(db);
  108330. /* If a transaction is open, the disconnectAllVtab() call above
  108331. ** will not have called the xDisconnect() method on any virtual
  108332. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  108333. ** call will do so. We need to do this before the check for active
  108334. ** SQL statements below, as the v-table implementation may be storing
  108335. ** some prepared statements internally.
  108336. */
  108337. sqlite3VtabRollback(db);
  108338. /* Legacy behavior (sqlite3_close() behavior) is to return
  108339. ** SQLITE_BUSY if the connection can not be closed immediately.
  108340. */
  108341. if( !forceZombie && connectionIsBusy(db) ){
  108342. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  108343. "statements or unfinished backups");
  108344. sqlite3_mutex_leave(db->mutex);
  108345. return SQLITE_BUSY;
  108346. }
  108347. #ifdef SQLITE_ENABLE_SQLLOG
  108348. if( sqlite3GlobalConfig.xSqllog ){
  108349. /* Closing the handle. Fourth parameter is passed the value 2. */
  108350. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  108351. }
  108352. #endif
  108353. /* Convert the connection into a zombie and then close it.
  108354. */
  108355. db->magic = SQLITE_MAGIC_ZOMBIE;
  108356. sqlite3LeaveMutexAndCloseZombie(db);
  108357. return SQLITE_OK;
  108358. }
  108359. /*
  108360. ** Two variations on the public interface for closing a database
  108361. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  108362. ** leaves the connection option if there are unfinalized prepared
  108363. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  108364. ** version forces the connection to become a zombie if there are
  108365. ** unclosed resources, and arranges for deallocation when the last
  108366. ** prepare statement or sqlite3_backup closes.
  108367. */
  108368. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  108369. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  108370. /*
  108371. ** Close the mutex on database connection db.
  108372. **
  108373. ** Furthermore, if database connection db is a zombie (meaning that there
  108374. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  108375. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  108376. ** finished, then free all resources.
  108377. */
  108378. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  108379. HashElem *i; /* Hash table iterator */
  108380. int j;
  108381. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  108382. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  108383. ** then just leave the mutex and return.
  108384. */
  108385. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  108386. sqlite3_mutex_leave(db->mutex);
  108387. return;
  108388. }
  108389. /* If we reach this point, it means that the database connection has
  108390. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  108391. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  108392. ** go ahead and free all resources.
  108393. */
  108394. /* If a transaction is open, roll it back. This also ensures that if
  108395. ** any database schemas have been modified by an uncommitted transaction
  108396. ** they are reset. And that the required b-tree mutex is held to make
  108397. ** the pager rollback and schema reset an atomic operation. */
  108398. sqlite3RollbackAll(db, SQLITE_OK);
  108399. /* Free any outstanding Savepoint structures. */
  108400. sqlite3CloseSavepoints(db);
  108401. /* Close all database connections */
  108402. for(j=0; j<db->nDb; j++){
  108403. struct Db *pDb = &db->aDb[j];
  108404. if( pDb->pBt ){
  108405. sqlite3BtreeClose(pDb->pBt);
  108406. pDb->pBt = 0;
  108407. if( j!=1 ){
  108408. pDb->pSchema = 0;
  108409. }
  108410. }
  108411. }
  108412. /* Clear the TEMP schema separately and last */
  108413. if( db->aDb[1].pSchema ){
  108414. sqlite3SchemaClear(db->aDb[1].pSchema);
  108415. }
  108416. sqlite3VtabUnlockList(db);
  108417. /* Free up the array of auxiliary databases */
  108418. sqlite3CollapseDatabaseArray(db);
  108419. assert( db->nDb<=2 );
  108420. assert( db->aDb==db->aDbStatic );
  108421. /* Tell the code in notify.c that the connection no longer holds any
  108422. ** locks and does not require any further unlock-notify callbacks.
  108423. */
  108424. sqlite3ConnectionClosed(db);
  108425. for(j=0; j<ArraySize(db->aFunc.a); j++){
  108426. FuncDef *pNext, *pHash, *p;
  108427. for(p=db->aFunc.a[j]; p; p=pHash){
  108428. pHash = p->pHash;
  108429. while( p ){
  108430. functionDestroy(db, p);
  108431. pNext = p->pNext;
  108432. sqlite3DbFree(db, p);
  108433. p = pNext;
  108434. }
  108435. }
  108436. }
  108437. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  108438. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  108439. /* Invoke any destructors registered for collation sequence user data. */
  108440. for(j=0; j<3; j++){
  108441. if( pColl[j].xDel ){
  108442. pColl[j].xDel(pColl[j].pUser);
  108443. }
  108444. }
  108445. sqlite3DbFree(db, pColl);
  108446. }
  108447. sqlite3HashClear(&db->aCollSeq);
  108448. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108449. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  108450. Module *pMod = (Module *)sqliteHashData(i);
  108451. if( pMod->xDestroy ){
  108452. pMod->xDestroy(pMod->pAux);
  108453. }
  108454. sqlite3DbFree(db, pMod);
  108455. }
  108456. sqlite3HashClear(&db->aModule);
  108457. #endif
  108458. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  108459. if( db->pErr ){
  108460. sqlite3ValueFree(db->pErr);
  108461. }
  108462. sqlite3CloseExtensions(db);
  108463. db->magic = SQLITE_MAGIC_ERROR;
  108464. /* The temp-database schema is allocated differently from the other schema
  108465. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  108466. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  108467. ** the same sqliteMalloc() as the one that allocates the database
  108468. ** structure?
  108469. */
  108470. sqlite3DbFree(db, db->aDb[1].pSchema);
  108471. sqlite3_mutex_leave(db->mutex);
  108472. db->magic = SQLITE_MAGIC_CLOSED;
  108473. sqlite3_mutex_free(db->mutex);
  108474. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  108475. if( db->lookaside.bMalloced ){
  108476. sqlite3_free(db->lookaside.pStart);
  108477. }
  108478. sqlite3_free(db);
  108479. }
  108480. /*
  108481. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  108482. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  108483. ** breaker") and made to return tripCode if there are any further
  108484. ** attempts to use that cursor.
  108485. */
  108486. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  108487. int i;
  108488. int inTrans = 0;
  108489. assert( sqlite3_mutex_held(db->mutex) );
  108490. sqlite3BeginBenignMalloc();
  108491. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  108492. ** This is important in case the transaction being rolled back has
  108493. ** modified the database schema. If the b-tree mutexes are not taken
  108494. ** here, then another shared-cache connection might sneak in between
  108495. ** the database rollback and schema reset, which can cause false
  108496. ** corruption reports in some cases. */
  108497. sqlite3BtreeEnterAll(db);
  108498. for(i=0; i<db->nDb; i++){
  108499. Btree *p = db->aDb[i].pBt;
  108500. if( p ){
  108501. if( sqlite3BtreeIsInTrans(p) ){
  108502. inTrans = 1;
  108503. }
  108504. sqlite3BtreeRollback(p, tripCode);
  108505. db->aDb[i].inTrans = 0;
  108506. }
  108507. }
  108508. sqlite3VtabRollback(db);
  108509. sqlite3EndBenignMalloc();
  108510. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  108511. sqlite3ExpirePreparedStatements(db);
  108512. sqlite3ResetAllSchemasOfConnection(db);
  108513. }
  108514. sqlite3BtreeLeaveAll(db);
  108515. /* Any deferred constraint violations have now been resolved. */
  108516. db->nDeferredCons = 0;
  108517. /* If one has been configured, invoke the rollback-hook callback */
  108518. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  108519. db->xRollbackCallback(db->pRollbackArg);
  108520. }
  108521. }
  108522. /*
  108523. ** Return a static string containing the name corresponding to the error code
  108524. ** specified in the argument.
  108525. */
  108526. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  108527. defined(SQLITE_DEBUG_OS_TRACE)
  108528. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  108529. const char *zName = 0;
  108530. int i, origRc = rc;
  108531. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  108532. switch( rc ){
  108533. case SQLITE_OK: zName = "SQLITE_OK"; break;
  108534. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  108535. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  108536. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  108537. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  108538. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  108539. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  108540. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  108541. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  108542. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  108543. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  108544. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  108545. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  108546. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  108547. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  108548. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  108549. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  108550. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  108551. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  108552. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  108553. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  108554. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  108555. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  108556. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  108557. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  108558. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  108559. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  108560. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  108561. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  108562. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  108563. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  108564. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  108565. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  108566. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  108567. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  108568. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  108569. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  108570. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  108571. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  108572. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  108573. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  108574. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  108575. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  108576. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  108577. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  108578. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  108579. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  108580. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  108581. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  108582. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  108583. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  108584. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  108585. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  108586. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  108587. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  108588. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  108589. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  108590. case SQLITE_CONSTRAINT_FOREIGNKEY:
  108591. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  108592. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  108593. case SQLITE_CONSTRAINT_PRIMARYKEY:
  108594. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  108595. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  108596. case SQLITE_CONSTRAINT_COMMITHOOK:
  108597. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  108598. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  108599. case SQLITE_CONSTRAINT_FUNCTION:
  108600. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  108601. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  108602. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  108603. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  108604. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  108605. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  108606. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  108607. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  108608. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  108609. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  108610. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  108611. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  108612. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  108613. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  108614. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  108615. }
  108616. }
  108617. if( zName==0 ){
  108618. static char zBuf[50];
  108619. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  108620. zName = zBuf;
  108621. }
  108622. return zName;
  108623. }
  108624. #endif
  108625. /*
  108626. ** Return a static string that describes the kind of error specified in the
  108627. ** argument.
  108628. */
  108629. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  108630. static const char* const aMsg[] = {
  108631. /* SQLITE_OK */ "not an error",
  108632. /* SQLITE_ERROR */ "SQL logic error or missing database",
  108633. /* SQLITE_INTERNAL */ 0,
  108634. /* SQLITE_PERM */ "access permission denied",
  108635. /* SQLITE_ABORT */ "callback requested query abort",
  108636. /* SQLITE_BUSY */ "database is locked",
  108637. /* SQLITE_LOCKED */ "database table is locked",
  108638. /* SQLITE_NOMEM */ "out of memory",
  108639. /* SQLITE_READONLY */ "attempt to write a readonly database",
  108640. /* SQLITE_INTERRUPT */ "interrupted",
  108641. /* SQLITE_IOERR */ "disk I/O error",
  108642. /* SQLITE_CORRUPT */ "database disk image is malformed",
  108643. /* SQLITE_NOTFOUND */ "unknown operation",
  108644. /* SQLITE_FULL */ "database or disk is full",
  108645. /* SQLITE_CANTOPEN */ "unable to open database file",
  108646. /* SQLITE_PROTOCOL */ "locking protocol",
  108647. /* SQLITE_EMPTY */ "table contains no data",
  108648. /* SQLITE_SCHEMA */ "database schema has changed",
  108649. /* SQLITE_TOOBIG */ "string or blob too big",
  108650. /* SQLITE_CONSTRAINT */ "constraint failed",
  108651. /* SQLITE_MISMATCH */ "datatype mismatch",
  108652. /* SQLITE_MISUSE */ "library routine called out of sequence",
  108653. /* SQLITE_NOLFS */ "large file support is disabled",
  108654. /* SQLITE_AUTH */ "authorization denied",
  108655. /* SQLITE_FORMAT */ "auxiliary database format error",
  108656. /* SQLITE_RANGE */ "bind or column index out of range",
  108657. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  108658. };
  108659. const char *zErr = "unknown error";
  108660. switch( rc ){
  108661. case SQLITE_ABORT_ROLLBACK: {
  108662. zErr = "abort due to ROLLBACK";
  108663. break;
  108664. }
  108665. default: {
  108666. rc &= 0xff;
  108667. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  108668. zErr = aMsg[rc];
  108669. }
  108670. break;
  108671. }
  108672. }
  108673. return zErr;
  108674. }
  108675. /*
  108676. ** This routine implements a busy callback that sleeps and tries
  108677. ** again until a timeout value is reached. The timeout value is
  108678. ** an integer number of milliseconds passed in as the first
  108679. ** argument.
  108680. */
  108681. static int sqliteDefaultBusyCallback(
  108682. void *ptr, /* Database connection */
  108683. int count /* Number of times table has been busy */
  108684. ){
  108685. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  108686. static const u8 delays[] =
  108687. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  108688. static const u8 totals[] =
  108689. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  108690. # define NDELAY ArraySize(delays)
  108691. sqlite3 *db = (sqlite3 *)ptr;
  108692. int timeout = db->busyTimeout;
  108693. int delay, prior;
  108694. assert( count>=0 );
  108695. if( count < NDELAY ){
  108696. delay = delays[count];
  108697. prior = totals[count];
  108698. }else{
  108699. delay = delays[NDELAY-1];
  108700. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  108701. }
  108702. if( prior + delay > timeout ){
  108703. delay = timeout - prior;
  108704. if( delay<=0 ) return 0;
  108705. }
  108706. sqlite3OsSleep(db->pVfs, delay*1000);
  108707. return 1;
  108708. #else
  108709. sqlite3 *db = (sqlite3 *)ptr;
  108710. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  108711. if( (count+1)*1000 > timeout ){
  108712. return 0;
  108713. }
  108714. sqlite3OsSleep(db->pVfs, 1000000);
  108715. return 1;
  108716. #endif
  108717. }
  108718. /*
  108719. ** Invoke the given busy handler.
  108720. **
  108721. ** This routine is called when an operation failed with a lock.
  108722. ** If this routine returns non-zero, the lock is retried. If it
  108723. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  108724. */
  108725. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  108726. int rc;
  108727. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  108728. rc = p->xFunc(p->pArg, p->nBusy);
  108729. if( rc==0 ){
  108730. p->nBusy = -1;
  108731. }else{
  108732. p->nBusy++;
  108733. }
  108734. return rc;
  108735. }
  108736. /*
  108737. ** This routine sets the busy callback for an Sqlite database to the
  108738. ** given callback function with the given argument.
  108739. */
  108740. SQLITE_API int sqlite3_busy_handler(
  108741. sqlite3 *db,
  108742. int (*xBusy)(void*,int),
  108743. void *pArg
  108744. ){
  108745. sqlite3_mutex_enter(db->mutex);
  108746. db->busyHandler.xFunc = xBusy;
  108747. db->busyHandler.pArg = pArg;
  108748. db->busyHandler.nBusy = 0;
  108749. db->busyTimeout = 0;
  108750. sqlite3_mutex_leave(db->mutex);
  108751. return SQLITE_OK;
  108752. }
  108753. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  108754. /*
  108755. ** This routine sets the progress callback for an Sqlite database to the
  108756. ** given callback function with the given argument. The progress callback will
  108757. ** be invoked every nOps opcodes.
  108758. */
  108759. SQLITE_API void sqlite3_progress_handler(
  108760. sqlite3 *db,
  108761. int nOps,
  108762. int (*xProgress)(void*),
  108763. void *pArg
  108764. ){
  108765. sqlite3_mutex_enter(db->mutex);
  108766. if( nOps>0 ){
  108767. db->xProgress = xProgress;
  108768. db->nProgressOps = nOps;
  108769. db->pProgressArg = pArg;
  108770. }else{
  108771. db->xProgress = 0;
  108772. db->nProgressOps = 0;
  108773. db->pProgressArg = 0;
  108774. }
  108775. sqlite3_mutex_leave(db->mutex);
  108776. }
  108777. #endif
  108778. /*
  108779. ** This routine installs a default busy handler that waits for the
  108780. ** specified number of milliseconds before returning 0.
  108781. */
  108782. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  108783. if( ms>0 ){
  108784. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  108785. db->busyTimeout = ms;
  108786. }else{
  108787. sqlite3_busy_handler(db, 0, 0);
  108788. }
  108789. return SQLITE_OK;
  108790. }
  108791. /*
  108792. ** Cause any pending operation to stop at its earliest opportunity.
  108793. */
  108794. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  108795. db->u1.isInterrupted = 1;
  108796. }
  108797. /*
  108798. ** This function is exactly the same as sqlite3_create_function(), except
  108799. ** that it is designed to be called by internal code. The difference is
  108800. ** that if a malloc() fails in sqlite3_create_function(), an error code
  108801. ** is returned and the mallocFailed flag cleared.
  108802. */
  108803. SQLITE_PRIVATE int sqlite3CreateFunc(
  108804. sqlite3 *db,
  108805. const char *zFunctionName,
  108806. int nArg,
  108807. int enc,
  108808. void *pUserData,
  108809. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  108810. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  108811. void (*xFinal)(sqlite3_context*),
  108812. FuncDestructor *pDestructor
  108813. ){
  108814. FuncDef *p;
  108815. int nName;
  108816. assert( sqlite3_mutex_held(db->mutex) );
  108817. if( zFunctionName==0 ||
  108818. (xFunc && (xFinal || xStep)) ||
  108819. (!xFunc && (xFinal && !xStep)) ||
  108820. (!xFunc && (!xFinal && xStep)) ||
  108821. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  108822. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  108823. return SQLITE_MISUSE_BKPT;
  108824. }
  108825. #ifndef SQLITE_OMIT_UTF16
  108826. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  108827. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  108828. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  108829. **
  108830. ** If SQLITE_ANY is specified, add three versions of the function
  108831. ** to the hash table.
  108832. */
  108833. if( enc==SQLITE_UTF16 ){
  108834. enc = SQLITE_UTF16NATIVE;
  108835. }else if( enc==SQLITE_ANY ){
  108836. int rc;
  108837. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  108838. pUserData, xFunc, xStep, xFinal, pDestructor);
  108839. if( rc==SQLITE_OK ){
  108840. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  108841. pUserData, xFunc, xStep, xFinal, pDestructor);
  108842. }
  108843. if( rc!=SQLITE_OK ){
  108844. return rc;
  108845. }
  108846. enc = SQLITE_UTF16BE;
  108847. }
  108848. #else
  108849. enc = SQLITE_UTF8;
  108850. #endif
  108851. /* Check if an existing function is being overridden or deleted. If so,
  108852. ** and there are active VMs, then return SQLITE_BUSY. If a function
  108853. ** is being overridden/deleted but there are no active VMs, allow the
  108854. ** operation to continue but invalidate all precompiled statements.
  108855. */
  108856. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  108857. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  108858. if( db->activeVdbeCnt ){
  108859. sqlite3Error(db, SQLITE_BUSY,
  108860. "unable to delete/modify user-function due to active statements");
  108861. assert( !db->mallocFailed );
  108862. return SQLITE_BUSY;
  108863. }else{
  108864. sqlite3ExpirePreparedStatements(db);
  108865. }
  108866. }
  108867. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  108868. assert(p || db->mallocFailed);
  108869. if( !p ){
  108870. return SQLITE_NOMEM;
  108871. }
  108872. /* If an older version of the function with a configured destructor is
  108873. ** being replaced invoke the destructor function here. */
  108874. functionDestroy(db, p);
  108875. if( pDestructor ){
  108876. pDestructor->nRef++;
  108877. }
  108878. p->pDestructor = pDestructor;
  108879. p->flags = 0;
  108880. p->xFunc = xFunc;
  108881. p->xStep = xStep;
  108882. p->xFinalize = xFinal;
  108883. p->pUserData = pUserData;
  108884. p->nArg = (u16)nArg;
  108885. return SQLITE_OK;
  108886. }
  108887. /*
  108888. ** Create new user functions.
  108889. */
  108890. SQLITE_API int sqlite3_create_function(
  108891. sqlite3 *db,
  108892. const char *zFunc,
  108893. int nArg,
  108894. int enc,
  108895. void *p,
  108896. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  108897. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  108898. void (*xFinal)(sqlite3_context*)
  108899. ){
  108900. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  108901. xFinal, 0);
  108902. }
  108903. SQLITE_API int sqlite3_create_function_v2(
  108904. sqlite3 *db,
  108905. const char *zFunc,
  108906. int nArg,
  108907. int enc,
  108908. void *p,
  108909. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  108910. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  108911. void (*xFinal)(sqlite3_context*),
  108912. void (*xDestroy)(void *)
  108913. ){
  108914. int rc = SQLITE_ERROR;
  108915. FuncDestructor *pArg = 0;
  108916. sqlite3_mutex_enter(db->mutex);
  108917. if( xDestroy ){
  108918. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  108919. if( !pArg ){
  108920. xDestroy(p);
  108921. goto out;
  108922. }
  108923. pArg->xDestroy = xDestroy;
  108924. pArg->pUserData = p;
  108925. }
  108926. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  108927. if( pArg && pArg->nRef==0 ){
  108928. assert( rc!=SQLITE_OK );
  108929. xDestroy(p);
  108930. sqlite3DbFree(db, pArg);
  108931. }
  108932. out:
  108933. rc = sqlite3ApiExit(db, rc);
  108934. sqlite3_mutex_leave(db->mutex);
  108935. return rc;
  108936. }
  108937. #ifndef SQLITE_OMIT_UTF16
  108938. SQLITE_API int sqlite3_create_function16(
  108939. sqlite3 *db,
  108940. const void *zFunctionName,
  108941. int nArg,
  108942. int eTextRep,
  108943. void *p,
  108944. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  108945. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  108946. void (*xFinal)(sqlite3_context*)
  108947. ){
  108948. int rc;
  108949. char *zFunc8;
  108950. sqlite3_mutex_enter(db->mutex);
  108951. assert( !db->mallocFailed );
  108952. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  108953. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  108954. sqlite3DbFree(db, zFunc8);
  108955. rc = sqlite3ApiExit(db, rc);
  108956. sqlite3_mutex_leave(db->mutex);
  108957. return rc;
  108958. }
  108959. #endif
  108960. /*
  108961. ** Declare that a function has been overloaded by a virtual table.
  108962. **
  108963. ** If the function already exists as a regular global function, then
  108964. ** this routine is a no-op. If the function does not exist, then create
  108965. ** a new one that always throws a run-time error.
  108966. **
  108967. ** When virtual tables intend to provide an overloaded function, they
  108968. ** should call this routine to make sure the global function exists.
  108969. ** A global function must exist in order for name resolution to work
  108970. ** properly.
  108971. */
  108972. SQLITE_API int sqlite3_overload_function(
  108973. sqlite3 *db,
  108974. const char *zName,
  108975. int nArg
  108976. ){
  108977. int nName = sqlite3Strlen30(zName);
  108978. int rc = SQLITE_OK;
  108979. sqlite3_mutex_enter(db->mutex);
  108980. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  108981. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  108982. 0, sqlite3InvalidFunction, 0, 0, 0);
  108983. }
  108984. rc = sqlite3ApiExit(db, rc);
  108985. sqlite3_mutex_leave(db->mutex);
  108986. return rc;
  108987. }
  108988. #ifndef SQLITE_OMIT_TRACE
  108989. /*
  108990. ** Register a trace function. The pArg from the previously registered trace
  108991. ** is returned.
  108992. **
  108993. ** A NULL trace function means that no tracing is executes. A non-NULL
  108994. ** trace is a pointer to a function that is invoked at the start of each
  108995. ** SQL statement.
  108996. */
  108997. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  108998. void *pOld;
  108999. sqlite3_mutex_enter(db->mutex);
  109000. pOld = db->pTraceArg;
  109001. db->xTrace = xTrace;
  109002. db->pTraceArg = pArg;
  109003. sqlite3_mutex_leave(db->mutex);
  109004. return pOld;
  109005. }
  109006. /*
  109007. ** Register a profile function. The pArg from the previously registered
  109008. ** profile function is returned.
  109009. **
  109010. ** A NULL profile function means that no profiling is executes. A non-NULL
  109011. ** profile is a pointer to a function that is invoked at the conclusion of
  109012. ** each SQL statement that is run.
  109013. */
  109014. SQLITE_API void *sqlite3_profile(
  109015. sqlite3 *db,
  109016. void (*xProfile)(void*,const char*,sqlite_uint64),
  109017. void *pArg
  109018. ){
  109019. void *pOld;
  109020. sqlite3_mutex_enter(db->mutex);
  109021. pOld = db->pProfileArg;
  109022. db->xProfile = xProfile;
  109023. db->pProfileArg = pArg;
  109024. sqlite3_mutex_leave(db->mutex);
  109025. return pOld;
  109026. }
  109027. #endif /* SQLITE_OMIT_TRACE */
  109028. /*
  109029. ** Register a function to be invoked when a transaction commits.
  109030. ** If the invoked function returns non-zero, then the commit becomes a
  109031. ** rollback.
  109032. */
  109033. SQLITE_API void *sqlite3_commit_hook(
  109034. sqlite3 *db, /* Attach the hook to this database */
  109035. int (*xCallback)(void*), /* Function to invoke on each commit */
  109036. void *pArg /* Argument to the function */
  109037. ){
  109038. void *pOld;
  109039. sqlite3_mutex_enter(db->mutex);
  109040. pOld = db->pCommitArg;
  109041. db->xCommitCallback = xCallback;
  109042. db->pCommitArg = pArg;
  109043. sqlite3_mutex_leave(db->mutex);
  109044. return pOld;
  109045. }
  109046. /*
  109047. ** Register a callback to be invoked each time a row is updated,
  109048. ** inserted or deleted using this database connection.
  109049. */
  109050. SQLITE_API void *sqlite3_update_hook(
  109051. sqlite3 *db, /* Attach the hook to this database */
  109052. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  109053. void *pArg /* Argument to the function */
  109054. ){
  109055. void *pRet;
  109056. sqlite3_mutex_enter(db->mutex);
  109057. pRet = db->pUpdateArg;
  109058. db->xUpdateCallback = xCallback;
  109059. db->pUpdateArg = pArg;
  109060. sqlite3_mutex_leave(db->mutex);
  109061. return pRet;
  109062. }
  109063. /*
  109064. ** Register a callback to be invoked each time a transaction is rolled
  109065. ** back by this database connection.
  109066. */
  109067. SQLITE_API void *sqlite3_rollback_hook(
  109068. sqlite3 *db, /* Attach the hook to this database */
  109069. void (*xCallback)(void*), /* Callback function */
  109070. void *pArg /* Argument to the function */
  109071. ){
  109072. void *pRet;
  109073. sqlite3_mutex_enter(db->mutex);
  109074. pRet = db->pRollbackArg;
  109075. db->xRollbackCallback = xCallback;
  109076. db->pRollbackArg = pArg;
  109077. sqlite3_mutex_leave(db->mutex);
  109078. return pRet;
  109079. }
  109080. #ifndef SQLITE_OMIT_WAL
  109081. /*
  109082. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  109083. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  109084. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  109085. ** wal_autocheckpoint()).
  109086. */
  109087. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  109088. void *pClientData, /* Argument */
  109089. sqlite3 *db, /* Connection */
  109090. const char *zDb, /* Database */
  109091. int nFrame /* Size of WAL */
  109092. ){
  109093. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  109094. sqlite3BeginBenignMalloc();
  109095. sqlite3_wal_checkpoint(db, zDb);
  109096. sqlite3EndBenignMalloc();
  109097. }
  109098. return SQLITE_OK;
  109099. }
  109100. #endif /* SQLITE_OMIT_WAL */
  109101. /*
  109102. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  109103. ** a database after committing a transaction if there are nFrame or
  109104. ** more frames in the log file. Passing zero or a negative value as the
  109105. ** nFrame parameter disables automatic checkpoints entirely.
  109106. **
  109107. ** The callback registered by this function replaces any existing callback
  109108. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  109109. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  109110. ** configured by this function.
  109111. */
  109112. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  109113. #ifdef SQLITE_OMIT_WAL
  109114. UNUSED_PARAMETER(db);
  109115. UNUSED_PARAMETER(nFrame);
  109116. #else
  109117. if( nFrame>0 ){
  109118. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  109119. }else{
  109120. sqlite3_wal_hook(db, 0, 0);
  109121. }
  109122. #endif
  109123. return SQLITE_OK;
  109124. }
  109125. /*
  109126. ** Register a callback to be invoked each time a transaction is written
  109127. ** into the write-ahead-log by this database connection.
  109128. */
  109129. SQLITE_API void *sqlite3_wal_hook(
  109130. sqlite3 *db, /* Attach the hook to this db handle */
  109131. int(*xCallback)(void *, sqlite3*, const char*, int),
  109132. void *pArg /* First argument passed to xCallback() */
  109133. ){
  109134. #ifndef SQLITE_OMIT_WAL
  109135. void *pRet;
  109136. sqlite3_mutex_enter(db->mutex);
  109137. pRet = db->pWalArg;
  109138. db->xWalCallback = xCallback;
  109139. db->pWalArg = pArg;
  109140. sqlite3_mutex_leave(db->mutex);
  109141. return pRet;
  109142. #else
  109143. return 0;
  109144. #endif
  109145. }
  109146. /*
  109147. ** Checkpoint database zDb.
  109148. */
  109149. SQLITE_API int sqlite3_wal_checkpoint_v2(
  109150. sqlite3 *db, /* Database handle */
  109151. const char *zDb, /* Name of attached database (or NULL) */
  109152. int eMode, /* SQLITE_CHECKPOINT_* value */
  109153. int *pnLog, /* OUT: Size of WAL log in frames */
  109154. int *pnCkpt /* OUT: Total number of frames checkpointed */
  109155. ){
  109156. #ifdef SQLITE_OMIT_WAL
  109157. return SQLITE_OK;
  109158. #else
  109159. int rc; /* Return code */
  109160. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  109161. /* Initialize the output variables to -1 in case an error occurs. */
  109162. if( pnLog ) *pnLog = -1;
  109163. if( pnCkpt ) *pnCkpt = -1;
  109164. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  109165. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  109166. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  109167. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  109168. return SQLITE_MISUSE;
  109169. }
  109170. sqlite3_mutex_enter(db->mutex);
  109171. if( zDb && zDb[0] ){
  109172. iDb = sqlite3FindDbName(db, zDb);
  109173. }
  109174. if( iDb<0 ){
  109175. rc = SQLITE_ERROR;
  109176. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  109177. }else{
  109178. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  109179. sqlite3Error(db, rc, 0);
  109180. }
  109181. rc = sqlite3ApiExit(db, rc);
  109182. sqlite3_mutex_leave(db->mutex);
  109183. return rc;
  109184. #endif
  109185. }
  109186. /*
  109187. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  109188. ** to contains a zero-length string, all attached databases are
  109189. ** checkpointed.
  109190. */
  109191. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  109192. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  109193. }
  109194. #ifndef SQLITE_OMIT_WAL
  109195. /*
  109196. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  109197. ** not currently open in WAL mode.
  109198. **
  109199. ** If a transaction is open on the database being checkpointed, this
  109200. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  109201. ** an error occurs while running the checkpoint, an SQLite error code is
  109202. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  109203. **
  109204. ** The mutex on database handle db should be held by the caller. The mutex
  109205. ** associated with the specific b-tree being checkpointed is taken by
  109206. ** this function while the checkpoint is running.
  109207. **
  109208. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  109209. ** checkpointed. If an error is encountered it is returned immediately -
  109210. ** no attempt is made to checkpoint any remaining databases.
  109211. **
  109212. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  109213. */
  109214. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  109215. int rc = SQLITE_OK; /* Return code */
  109216. int i; /* Used to iterate through attached dbs */
  109217. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  109218. assert( sqlite3_mutex_held(db->mutex) );
  109219. assert( !pnLog || *pnLog==-1 );
  109220. assert( !pnCkpt || *pnCkpt==-1 );
  109221. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  109222. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  109223. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  109224. pnLog = 0;
  109225. pnCkpt = 0;
  109226. if( rc==SQLITE_BUSY ){
  109227. bBusy = 1;
  109228. rc = SQLITE_OK;
  109229. }
  109230. }
  109231. }
  109232. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  109233. }
  109234. #endif /* SQLITE_OMIT_WAL */
  109235. /*
  109236. ** This function returns true if main-memory should be used instead of
  109237. ** a temporary file for transient pager files and statement journals.
  109238. ** The value returned depends on the value of db->temp_store (runtime
  109239. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  109240. ** following table describes the relationship between these two values
  109241. ** and this functions return value.
  109242. **
  109243. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  109244. ** ----------------- -------------- ------------------------------
  109245. ** 0 any file (return 0)
  109246. ** 1 1 file (return 0)
  109247. ** 1 2 memory (return 1)
  109248. ** 1 0 file (return 0)
  109249. ** 2 1 file (return 0)
  109250. ** 2 2 memory (return 1)
  109251. ** 2 0 memory (return 1)
  109252. ** 3 any memory (return 1)
  109253. */
  109254. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  109255. #if SQLITE_TEMP_STORE==1
  109256. return ( db->temp_store==2 );
  109257. #endif
  109258. #if SQLITE_TEMP_STORE==2
  109259. return ( db->temp_store!=1 );
  109260. #endif
  109261. #if SQLITE_TEMP_STORE==3
  109262. return 1;
  109263. #endif
  109264. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  109265. return 0;
  109266. #endif
  109267. }
  109268. /*
  109269. ** Return UTF-8 encoded English language explanation of the most recent
  109270. ** error.
  109271. */
  109272. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  109273. const char *z;
  109274. if( !db ){
  109275. return sqlite3ErrStr(SQLITE_NOMEM);
  109276. }
  109277. if( !sqlite3SafetyCheckSickOrOk(db) ){
  109278. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  109279. }
  109280. sqlite3_mutex_enter(db->mutex);
  109281. if( db->mallocFailed ){
  109282. z = sqlite3ErrStr(SQLITE_NOMEM);
  109283. }else{
  109284. z = (char*)sqlite3_value_text(db->pErr);
  109285. assert( !db->mallocFailed );
  109286. if( z==0 ){
  109287. z = sqlite3ErrStr(db->errCode);
  109288. }
  109289. }
  109290. sqlite3_mutex_leave(db->mutex);
  109291. return z;
  109292. }
  109293. #ifndef SQLITE_OMIT_UTF16
  109294. /*
  109295. ** Return UTF-16 encoded English language explanation of the most recent
  109296. ** error.
  109297. */
  109298. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  109299. static const u16 outOfMem[] = {
  109300. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  109301. };
  109302. static const u16 misuse[] = {
  109303. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  109304. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  109305. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  109306. 'o', 'u', 't', ' ',
  109307. 'o', 'f', ' ',
  109308. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  109309. };
  109310. const void *z;
  109311. if( !db ){
  109312. return (void *)outOfMem;
  109313. }
  109314. if( !sqlite3SafetyCheckSickOrOk(db) ){
  109315. return (void *)misuse;
  109316. }
  109317. sqlite3_mutex_enter(db->mutex);
  109318. if( db->mallocFailed ){
  109319. z = (void *)outOfMem;
  109320. }else{
  109321. z = sqlite3_value_text16(db->pErr);
  109322. if( z==0 ){
  109323. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  109324. SQLITE_UTF8, SQLITE_STATIC);
  109325. z = sqlite3_value_text16(db->pErr);
  109326. }
  109327. /* A malloc() may have failed within the call to sqlite3_value_text16()
  109328. ** above. If this is the case, then the db->mallocFailed flag needs to
  109329. ** be cleared before returning. Do this directly, instead of via
  109330. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  109331. */
  109332. db->mallocFailed = 0;
  109333. }
  109334. sqlite3_mutex_leave(db->mutex);
  109335. return z;
  109336. }
  109337. #endif /* SQLITE_OMIT_UTF16 */
  109338. /*
  109339. ** Return the most recent error code generated by an SQLite routine. If NULL is
  109340. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  109341. */
  109342. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  109343. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  109344. return SQLITE_MISUSE_BKPT;
  109345. }
  109346. if( !db || db->mallocFailed ){
  109347. return SQLITE_NOMEM;
  109348. }
  109349. return db->errCode & db->errMask;
  109350. }
  109351. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  109352. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  109353. return SQLITE_MISUSE_BKPT;
  109354. }
  109355. if( !db || db->mallocFailed ){
  109356. return SQLITE_NOMEM;
  109357. }
  109358. return db->errCode;
  109359. }
  109360. /*
  109361. ** Return a string that describes the kind of error specified in the
  109362. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  109363. ** function.
  109364. */
  109365. SQLITE_API const char *sqlite3_errstr(int rc){
  109366. return sqlite3ErrStr(rc);
  109367. }
  109368. /*
  109369. ** Create a new collating function for database "db". The name is zName
  109370. ** and the encoding is enc.
  109371. */
  109372. static int createCollation(
  109373. sqlite3* db,
  109374. const char *zName,
  109375. u8 enc,
  109376. void* pCtx,
  109377. int(*xCompare)(void*,int,const void*,int,const void*),
  109378. void(*xDel)(void*)
  109379. ){
  109380. CollSeq *pColl;
  109381. int enc2;
  109382. int nName = sqlite3Strlen30(zName);
  109383. assert( sqlite3_mutex_held(db->mutex) );
  109384. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  109385. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  109386. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  109387. */
  109388. enc2 = enc;
  109389. testcase( enc2==SQLITE_UTF16 );
  109390. testcase( enc2==SQLITE_UTF16_ALIGNED );
  109391. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  109392. enc2 = SQLITE_UTF16NATIVE;
  109393. }
  109394. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  109395. return SQLITE_MISUSE_BKPT;
  109396. }
  109397. /* Check if this call is removing or replacing an existing collation
  109398. ** sequence. If so, and there are active VMs, return busy. If there
  109399. ** are no active VMs, invalidate any pre-compiled statements.
  109400. */
  109401. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  109402. if( pColl && pColl->xCmp ){
  109403. if( db->activeVdbeCnt ){
  109404. sqlite3Error(db, SQLITE_BUSY,
  109405. "unable to delete/modify collation sequence due to active statements");
  109406. return SQLITE_BUSY;
  109407. }
  109408. sqlite3ExpirePreparedStatements(db);
  109409. /* If collation sequence pColl was created directly by a call to
  109410. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  109411. ** then any copies made by synthCollSeq() need to be invalidated.
  109412. ** Also, collation destructor - CollSeq.xDel() - function may need
  109413. ** to be called.
  109414. */
  109415. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  109416. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  109417. int j;
  109418. for(j=0; j<3; j++){
  109419. CollSeq *p = &aColl[j];
  109420. if( p->enc==pColl->enc ){
  109421. if( p->xDel ){
  109422. p->xDel(p->pUser);
  109423. }
  109424. p->xCmp = 0;
  109425. }
  109426. }
  109427. }
  109428. }
  109429. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  109430. if( pColl==0 ) return SQLITE_NOMEM;
  109431. pColl->xCmp = xCompare;
  109432. pColl->pUser = pCtx;
  109433. pColl->xDel = xDel;
  109434. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  109435. sqlite3Error(db, SQLITE_OK, 0);
  109436. return SQLITE_OK;
  109437. }
  109438. /*
  109439. ** This array defines hard upper bounds on limit values. The
  109440. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  109441. ** #defines in sqlite3.h.
  109442. */
  109443. static const int aHardLimit[] = {
  109444. SQLITE_MAX_LENGTH,
  109445. SQLITE_MAX_SQL_LENGTH,
  109446. SQLITE_MAX_COLUMN,
  109447. SQLITE_MAX_EXPR_DEPTH,
  109448. SQLITE_MAX_COMPOUND_SELECT,
  109449. SQLITE_MAX_VDBE_OP,
  109450. SQLITE_MAX_FUNCTION_ARG,
  109451. SQLITE_MAX_ATTACHED,
  109452. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  109453. SQLITE_MAX_VARIABLE_NUMBER,
  109454. SQLITE_MAX_TRIGGER_DEPTH,
  109455. };
  109456. /*
  109457. ** Make sure the hard limits are set to reasonable values
  109458. */
  109459. #if SQLITE_MAX_LENGTH<100
  109460. # error SQLITE_MAX_LENGTH must be at least 100
  109461. #endif
  109462. #if SQLITE_MAX_SQL_LENGTH<100
  109463. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  109464. #endif
  109465. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  109466. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  109467. #endif
  109468. #if SQLITE_MAX_COMPOUND_SELECT<2
  109469. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  109470. #endif
  109471. #if SQLITE_MAX_VDBE_OP<40
  109472. # error SQLITE_MAX_VDBE_OP must be at least 40
  109473. #endif
  109474. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  109475. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  109476. #endif
  109477. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  109478. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  109479. #endif
  109480. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  109481. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  109482. #endif
  109483. #if SQLITE_MAX_COLUMN>32767
  109484. # error SQLITE_MAX_COLUMN must not exceed 32767
  109485. #endif
  109486. #if SQLITE_MAX_TRIGGER_DEPTH<1
  109487. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  109488. #endif
  109489. /*
  109490. ** Change the value of a limit. Report the old value.
  109491. ** If an invalid limit index is supplied, report -1.
  109492. ** Make no changes but still report the old value if the
  109493. ** new limit is negative.
  109494. **
  109495. ** A new lower limit does not shrink existing constructs.
  109496. ** It merely prevents new constructs that exceed the limit
  109497. ** from forming.
  109498. */
  109499. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  109500. int oldLimit;
  109501. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  109502. ** there is a hard upper bound set at compile-time by a C preprocessor
  109503. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  109504. ** "_MAX_".)
  109505. */
  109506. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  109507. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  109508. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  109509. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  109510. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  109511. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  109512. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  109513. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  109514. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  109515. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  109516. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  109517. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  109518. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  109519. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  109520. return -1;
  109521. }
  109522. oldLimit = db->aLimit[limitId];
  109523. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  109524. if( newLimit>aHardLimit[limitId] ){
  109525. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  109526. }
  109527. db->aLimit[limitId] = newLimit;
  109528. }
  109529. return oldLimit; /* IMP: R-53341-35419 */
  109530. }
  109531. /*
  109532. ** This function is used to parse both URIs and non-URI filenames passed by the
  109533. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  109534. ** URIs specified as part of ATTACH statements.
  109535. **
  109536. ** The first argument to this function is the name of the VFS to use (or
  109537. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  109538. ** query parameter. The second argument contains the URI (or non-URI filename)
  109539. ** itself. When this function is called the *pFlags variable should contain
  109540. ** the default flags to open the database handle with. The value stored in
  109541. ** *pFlags may be updated before returning if the URI filename contains
  109542. ** "cache=xxx" or "mode=xxx" query parameters.
  109543. **
  109544. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  109545. ** the VFS that should be used to open the database file. *pzFile is set to
  109546. ** point to a buffer containing the name of the file to open. It is the
  109547. ** responsibility of the caller to eventually call sqlite3_free() to release
  109548. ** this buffer.
  109549. **
  109550. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  109551. ** may be set to point to a buffer containing an English language error
  109552. ** message. It is the responsibility of the caller to eventually release
  109553. ** this buffer by calling sqlite3_free().
  109554. */
  109555. SQLITE_PRIVATE int sqlite3ParseUri(
  109556. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  109557. const char *zUri, /* Nul-terminated URI to parse */
  109558. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  109559. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  109560. char **pzFile, /* OUT: Filename component of URI */
  109561. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  109562. ){
  109563. int rc = SQLITE_OK;
  109564. unsigned int flags = *pFlags;
  109565. const char *zVfs = zDefaultVfs;
  109566. char *zFile;
  109567. char c;
  109568. int nUri = sqlite3Strlen30(zUri);
  109569. assert( *pzErrMsg==0 );
  109570. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  109571. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  109572. ){
  109573. char *zOpt;
  109574. int eState; /* Parser state when parsing URI */
  109575. int iIn; /* Input character index */
  109576. int iOut = 0; /* Output character index */
  109577. int nByte = nUri+2; /* Bytes of space to allocate */
  109578. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  109579. ** method that there may be extra parameters following the file-name. */
  109580. flags |= SQLITE_OPEN_URI;
  109581. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  109582. zFile = sqlite3_malloc(nByte);
  109583. if( !zFile ) return SQLITE_NOMEM;
  109584. /* Discard the scheme and authority segments of the URI. */
  109585. if( zUri[5]=='/' && zUri[6]=='/' ){
  109586. iIn = 7;
  109587. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  109588. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  109589. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  109590. iIn-7, &zUri[7]);
  109591. rc = SQLITE_ERROR;
  109592. goto parse_uri_out;
  109593. }
  109594. }else{
  109595. iIn = 5;
  109596. }
  109597. /* Copy the filename and any query parameters into the zFile buffer.
  109598. ** Decode %HH escape codes along the way.
  109599. **
  109600. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  109601. ** on the parsing context. As follows:
  109602. **
  109603. ** 0: Parsing file-name.
  109604. ** 1: Parsing name section of a name=value query parameter.
  109605. ** 2: Parsing value section of a name=value query parameter.
  109606. */
  109607. eState = 0;
  109608. while( (c = zUri[iIn])!=0 && c!='#' ){
  109609. iIn++;
  109610. if( c=='%'
  109611. && sqlite3Isxdigit(zUri[iIn])
  109612. && sqlite3Isxdigit(zUri[iIn+1])
  109613. ){
  109614. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  109615. octet += sqlite3HexToInt(zUri[iIn++]);
  109616. assert( octet>=0 && octet<256 );
  109617. if( octet==0 ){
  109618. /* This branch is taken when "%00" appears within the URI. In this
  109619. ** case we ignore all text in the remainder of the path, name or
  109620. ** value currently being parsed. So ignore the current character
  109621. ** and skip to the next "?", "=" or "&", as appropriate. */
  109622. while( (c = zUri[iIn])!=0 && c!='#'
  109623. && (eState!=0 || c!='?')
  109624. && (eState!=1 || (c!='=' && c!='&'))
  109625. && (eState!=2 || c!='&')
  109626. ){
  109627. iIn++;
  109628. }
  109629. continue;
  109630. }
  109631. c = octet;
  109632. }else if( eState==1 && (c=='&' || c=='=') ){
  109633. if( zFile[iOut-1]==0 ){
  109634. /* An empty option name. Ignore this option altogether. */
  109635. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  109636. continue;
  109637. }
  109638. if( c=='&' ){
  109639. zFile[iOut++] = '\0';
  109640. }else{
  109641. eState = 2;
  109642. }
  109643. c = 0;
  109644. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  109645. c = 0;
  109646. eState = 1;
  109647. }
  109648. zFile[iOut++] = c;
  109649. }
  109650. if( eState==1 ) zFile[iOut++] = '\0';
  109651. zFile[iOut++] = '\0';
  109652. zFile[iOut++] = '\0';
  109653. /* Check if there were any options specified that should be interpreted
  109654. ** here. Options that are interpreted here include "vfs" and those that
  109655. ** correspond to flags that may be passed to the sqlite3_open_v2()
  109656. ** method. */
  109657. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  109658. while( zOpt[0] ){
  109659. int nOpt = sqlite3Strlen30(zOpt);
  109660. char *zVal = &zOpt[nOpt+1];
  109661. int nVal = sqlite3Strlen30(zVal);
  109662. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  109663. zVfs = zVal;
  109664. }else{
  109665. struct OpenMode {
  109666. const char *z;
  109667. int mode;
  109668. } *aMode = 0;
  109669. char *zModeType = 0;
  109670. int mask = 0;
  109671. int limit = 0;
  109672. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  109673. static struct OpenMode aCacheMode[] = {
  109674. { "shared", SQLITE_OPEN_SHAREDCACHE },
  109675. { "private", SQLITE_OPEN_PRIVATECACHE },
  109676. { 0, 0 }
  109677. };
  109678. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  109679. aMode = aCacheMode;
  109680. limit = mask;
  109681. zModeType = "cache";
  109682. }
  109683. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  109684. static struct OpenMode aOpenMode[] = {
  109685. { "ro", SQLITE_OPEN_READONLY },
  109686. { "rw", SQLITE_OPEN_READWRITE },
  109687. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  109688. { "memory", SQLITE_OPEN_MEMORY },
  109689. { 0, 0 }
  109690. };
  109691. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  109692. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  109693. aMode = aOpenMode;
  109694. limit = mask & flags;
  109695. zModeType = "access";
  109696. }
  109697. if( aMode ){
  109698. int i;
  109699. int mode = 0;
  109700. for(i=0; aMode[i].z; i++){
  109701. const char *z = aMode[i].z;
  109702. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  109703. mode = aMode[i].mode;
  109704. break;
  109705. }
  109706. }
  109707. if( mode==0 ){
  109708. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  109709. rc = SQLITE_ERROR;
  109710. goto parse_uri_out;
  109711. }
  109712. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  109713. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  109714. zModeType, zVal);
  109715. rc = SQLITE_PERM;
  109716. goto parse_uri_out;
  109717. }
  109718. flags = (flags & ~mask) | mode;
  109719. }
  109720. }
  109721. zOpt = &zVal[nVal+1];
  109722. }
  109723. }else{
  109724. zFile = sqlite3_malloc(nUri+2);
  109725. if( !zFile ) return SQLITE_NOMEM;
  109726. memcpy(zFile, zUri, nUri);
  109727. zFile[nUri] = '\0';
  109728. zFile[nUri+1] = '\0';
  109729. flags &= ~SQLITE_OPEN_URI;
  109730. }
  109731. *ppVfs = sqlite3_vfs_find(zVfs);
  109732. if( *ppVfs==0 ){
  109733. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  109734. rc = SQLITE_ERROR;
  109735. }
  109736. parse_uri_out:
  109737. if( rc!=SQLITE_OK ){
  109738. sqlite3_free(zFile);
  109739. zFile = 0;
  109740. }
  109741. *pFlags = flags;
  109742. *pzFile = zFile;
  109743. return rc;
  109744. }
  109745. /*
  109746. ** This routine does the work of opening a database on behalf of
  109747. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  109748. ** is UTF-8 encoded.
  109749. */
  109750. static int openDatabase(
  109751. const char *zFilename, /* Database filename UTF-8 encoded */
  109752. sqlite3 **ppDb, /* OUT: Returned database handle */
  109753. unsigned int flags, /* Operational flags */
  109754. const char *zVfs /* Name of the VFS to use */
  109755. ){
  109756. sqlite3 *db; /* Store allocated handle here */
  109757. int rc; /* Return code */
  109758. int isThreadsafe; /* True for threadsafe connections */
  109759. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  109760. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  109761. *ppDb = 0;
  109762. #ifndef SQLITE_OMIT_AUTOINIT
  109763. rc = sqlite3_initialize();
  109764. if( rc ) return rc;
  109765. #endif
  109766. /* Only allow sensible combinations of bits in the flags argument.
  109767. ** Throw an error if any non-sense combination is used. If we
  109768. ** do not block illegal combinations here, it could trigger
  109769. ** assert() statements in deeper layers. Sensible combinations
  109770. ** are:
  109771. **
  109772. ** 1: SQLITE_OPEN_READONLY
  109773. ** 2: SQLITE_OPEN_READWRITE
  109774. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  109775. */
  109776. assert( SQLITE_OPEN_READONLY == 0x01 );
  109777. assert( SQLITE_OPEN_READWRITE == 0x02 );
  109778. assert( SQLITE_OPEN_CREATE == 0x04 );
  109779. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  109780. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  109781. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  109782. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  109783. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  109784. isThreadsafe = 0;
  109785. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  109786. isThreadsafe = 0;
  109787. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  109788. isThreadsafe = 1;
  109789. }else{
  109790. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  109791. }
  109792. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  109793. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  109794. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  109795. flags |= SQLITE_OPEN_SHAREDCACHE;
  109796. }
  109797. /* Remove harmful bits from the flags parameter
  109798. **
  109799. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  109800. ** dealt with in the previous code block. Besides these, the only
  109801. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  109802. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  109803. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  109804. ** off all other flags.
  109805. */
  109806. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  109807. SQLITE_OPEN_EXCLUSIVE |
  109808. SQLITE_OPEN_MAIN_DB |
  109809. SQLITE_OPEN_TEMP_DB |
  109810. SQLITE_OPEN_TRANSIENT_DB |
  109811. SQLITE_OPEN_MAIN_JOURNAL |
  109812. SQLITE_OPEN_TEMP_JOURNAL |
  109813. SQLITE_OPEN_SUBJOURNAL |
  109814. SQLITE_OPEN_MASTER_JOURNAL |
  109815. SQLITE_OPEN_NOMUTEX |
  109816. SQLITE_OPEN_FULLMUTEX |
  109817. SQLITE_OPEN_WAL
  109818. );
  109819. /* Allocate the sqlite data structure */
  109820. db = sqlite3MallocZero( sizeof(sqlite3) );
  109821. if( db==0 ) goto opendb_out;
  109822. if( isThreadsafe ){
  109823. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  109824. if( db->mutex==0 ){
  109825. sqlite3_free(db);
  109826. db = 0;
  109827. goto opendb_out;
  109828. }
  109829. }
  109830. sqlite3_mutex_enter(db->mutex);
  109831. db->errMask = 0xff;
  109832. db->nDb = 2;
  109833. db->magic = SQLITE_MAGIC_BUSY;
  109834. db->aDb = db->aDbStatic;
  109835. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  109836. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  109837. db->autoCommit = 1;
  109838. db->nextAutovac = -1;
  109839. db->szMmap = sqlite3GlobalConfig.szMmap;
  109840. db->nextPagesize = 0;
  109841. db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
  109842. #if SQLITE_DEFAULT_FILE_FORMAT<4
  109843. | SQLITE_LegacyFileFmt
  109844. #endif
  109845. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  109846. | SQLITE_LoadExtension
  109847. #endif
  109848. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  109849. | SQLITE_RecTriggers
  109850. #endif
  109851. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  109852. | SQLITE_ForeignKeys
  109853. #endif
  109854. ;
  109855. sqlite3HashInit(&db->aCollSeq);
  109856. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109857. sqlite3HashInit(&db->aModule);
  109858. #endif
  109859. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  109860. ** and UTF-16, so add a version for each to avoid any unnecessary
  109861. ** conversions. The only error that can occur here is a malloc() failure.
  109862. */
  109863. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  109864. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  109865. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  109866. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  109867. if( db->mallocFailed ){
  109868. goto opendb_out;
  109869. }
  109870. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  109871. assert( db->pDfltColl!=0 );
  109872. /* Also add a UTF-8 case-insensitive collation sequence. */
  109873. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  109874. /* Parse the filename/URI argument. */
  109875. db->openFlags = flags;
  109876. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  109877. if( rc!=SQLITE_OK ){
  109878. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  109879. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  109880. sqlite3_free(zErrMsg);
  109881. goto opendb_out;
  109882. }
  109883. /* Open the backend database driver */
  109884. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  109885. flags | SQLITE_OPEN_MAIN_DB);
  109886. if( rc!=SQLITE_OK ){
  109887. if( rc==SQLITE_IOERR_NOMEM ){
  109888. rc = SQLITE_NOMEM;
  109889. }
  109890. sqlite3Error(db, rc, 0);
  109891. goto opendb_out;
  109892. }
  109893. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  109894. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  109895. /* The default safety_level for the main database is 'full'; for the temp
  109896. ** database it is 'NONE'. This matches the pager layer defaults.
  109897. */
  109898. db->aDb[0].zName = "main";
  109899. db->aDb[0].safety_level = 3;
  109900. db->aDb[1].zName = "temp";
  109901. db->aDb[1].safety_level = 1;
  109902. db->magic = SQLITE_MAGIC_OPEN;
  109903. if( db->mallocFailed ){
  109904. goto opendb_out;
  109905. }
  109906. /* Register all built-in functions, but do not attempt to read the
  109907. ** database schema yet. This is delayed until the first time the database
  109908. ** is accessed.
  109909. */
  109910. sqlite3Error(db, SQLITE_OK, 0);
  109911. sqlite3RegisterBuiltinFunctions(db);
  109912. /* Load automatic extensions - extensions that have been registered
  109913. ** using the sqlite3_automatic_extension() API.
  109914. */
  109915. rc = sqlite3_errcode(db);
  109916. if( rc==SQLITE_OK ){
  109917. sqlite3AutoLoadExtensions(db);
  109918. rc = sqlite3_errcode(db);
  109919. if( rc!=SQLITE_OK ){
  109920. goto opendb_out;
  109921. }
  109922. }
  109923. #ifdef SQLITE_ENABLE_FTS1
  109924. if( !db->mallocFailed ){
  109925. extern int sqlite3Fts1Init(sqlite3*);
  109926. rc = sqlite3Fts1Init(db);
  109927. }
  109928. #endif
  109929. #ifdef SQLITE_ENABLE_FTS2
  109930. if( !db->mallocFailed && rc==SQLITE_OK ){
  109931. extern int sqlite3Fts2Init(sqlite3*);
  109932. rc = sqlite3Fts2Init(db);
  109933. }
  109934. #endif
  109935. #ifdef SQLITE_ENABLE_FTS3
  109936. if( !db->mallocFailed && rc==SQLITE_OK ){
  109937. rc = sqlite3Fts3Init(db);
  109938. }
  109939. #endif
  109940. #ifdef SQLITE_ENABLE_ICU
  109941. if( !db->mallocFailed && rc==SQLITE_OK ){
  109942. rc = sqlite3IcuInit(db);
  109943. }
  109944. #endif
  109945. #ifdef SQLITE_ENABLE_RTREE
  109946. if( !db->mallocFailed && rc==SQLITE_OK){
  109947. rc = sqlite3RtreeInit(db);
  109948. }
  109949. #endif
  109950. sqlite3Error(db, rc, 0);
  109951. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  109952. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  109953. ** mode. Doing nothing at all also makes NORMAL the default.
  109954. */
  109955. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  109956. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  109957. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  109958. SQLITE_DEFAULT_LOCKING_MODE);
  109959. #endif
  109960. /* Enable the lookaside-malloc subsystem */
  109961. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  109962. sqlite3GlobalConfig.nLookaside);
  109963. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  109964. opendb_out:
  109965. sqlite3_free(zOpen);
  109966. if( db ){
  109967. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  109968. sqlite3_mutex_leave(db->mutex);
  109969. }
  109970. rc = sqlite3_errcode(db);
  109971. assert( db!=0 || rc==SQLITE_NOMEM );
  109972. if( rc==SQLITE_NOMEM ){
  109973. sqlite3_close(db);
  109974. db = 0;
  109975. }else if( rc!=SQLITE_OK ){
  109976. db->magic = SQLITE_MAGIC_SICK;
  109977. }
  109978. *ppDb = db;
  109979. #ifdef SQLITE_ENABLE_SQLLOG
  109980. if( sqlite3GlobalConfig.xSqllog ){
  109981. /* Opening a db handle. Fourth parameter is passed 0. */
  109982. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  109983. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  109984. }
  109985. #endif
  109986. return sqlite3ApiExit(0, rc);
  109987. }
  109988. /*
  109989. ** Open a new database handle.
  109990. */
  109991. SQLITE_API int sqlite3_open(
  109992. const char *zFilename,
  109993. sqlite3 **ppDb
  109994. ){
  109995. return openDatabase(zFilename, ppDb,
  109996. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  109997. }
  109998. SQLITE_API int sqlite3_open_v2(
  109999. const char *filename, /* Database filename (UTF-8) */
  110000. sqlite3 **ppDb, /* OUT: SQLite db handle */
  110001. int flags, /* Flags */
  110002. const char *zVfs /* Name of VFS module to use */
  110003. ){
  110004. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  110005. }
  110006. #ifndef SQLITE_OMIT_UTF16
  110007. /*
  110008. ** Open a new database handle.
  110009. */
  110010. SQLITE_API int sqlite3_open16(
  110011. const void *zFilename,
  110012. sqlite3 **ppDb
  110013. ){
  110014. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  110015. sqlite3_value *pVal;
  110016. int rc;
  110017. assert( zFilename );
  110018. assert( ppDb );
  110019. *ppDb = 0;
  110020. #ifndef SQLITE_OMIT_AUTOINIT
  110021. rc = sqlite3_initialize();
  110022. if( rc ) return rc;
  110023. #endif
  110024. pVal = sqlite3ValueNew(0);
  110025. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  110026. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  110027. if( zFilename8 ){
  110028. rc = openDatabase(zFilename8, ppDb,
  110029. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  110030. assert( *ppDb || rc==SQLITE_NOMEM );
  110031. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  110032. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  110033. }
  110034. }else{
  110035. rc = SQLITE_NOMEM;
  110036. }
  110037. sqlite3ValueFree(pVal);
  110038. return sqlite3ApiExit(0, rc);
  110039. }
  110040. #endif /* SQLITE_OMIT_UTF16 */
  110041. /*
  110042. ** Register a new collation sequence with the database handle db.
  110043. */
  110044. SQLITE_API int sqlite3_create_collation(
  110045. sqlite3* db,
  110046. const char *zName,
  110047. int enc,
  110048. void* pCtx,
  110049. int(*xCompare)(void*,int,const void*,int,const void*)
  110050. ){
  110051. int rc;
  110052. sqlite3_mutex_enter(db->mutex);
  110053. assert( !db->mallocFailed );
  110054. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  110055. rc = sqlite3ApiExit(db, rc);
  110056. sqlite3_mutex_leave(db->mutex);
  110057. return rc;
  110058. }
  110059. /*
  110060. ** Register a new collation sequence with the database handle db.
  110061. */
  110062. SQLITE_API int sqlite3_create_collation_v2(
  110063. sqlite3* db,
  110064. const char *zName,
  110065. int enc,
  110066. void* pCtx,
  110067. int(*xCompare)(void*,int,const void*,int,const void*),
  110068. void(*xDel)(void*)
  110069. ){
  110070. int rc;
  110071. sqlite3_mutex_enter(db->mutex);
  110072. assert( !db->mallocFailed );
  110073. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  110074. rc = sqlite3ApiExit(db, rc);
  110075. sqlite3_mutex_leave(db->mutex);
  110076. return rc;
  110077. }
  110078. #ifndef SQLITE_OMIT_UTF16
  110079. /*
  110080. ** Register a new collation sequence with the database handle db.
  110081. */
  110082. SQLITE_API int sqlite3_create_collation16(
  110083. sqlite3* db,
  110084. const void *zName,
  110085. int enc,
  110086. void* pCtx,
  110087. int(*xCompare)(void*,int,const void*,int,const void*)
  110088. ){
  110089. int rc = SQLITE_OK;
  110090. char *zName8;
  110091. sqlite3_mutex_enter(db->mutex);
  110092. assert( !db->mallocFailed );
  110093. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  110094. if( zName8 ){
  110095. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  110096. sqlite3DbFree(db, zName8);
  110097. }
  110098. rc = sqlite3ApiExit(db, rc);
  110099. sqlite3_mutex_leave(db->mutex);
  110100. return rc;
  110101. }
  110102. #endif /* SQLITE_OMIT_UTF16 */
  110103. /*
  110104. ** Register a collation sequence factory callback with the database handle
  110105. ** db. Replace any previously installed collation sequence factory.
  110106. */
  110107. SQLITE_API int sqlite3_collation_needed(
  110108. sqlite3 *db,
  110109. void *pCollNeededArg,
  110110. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  110111. ){
  110112. sqlite3_mutex_enter(db->mutex);
  110113. db->xCollNeeded = xCollNeeded;
  110114. db->xCollNeeded16 = 0;
  110115. db->pCollNeededArg = pCollNeededArg;
  110116. sqlite3_mutex_leave(db->mutex);
  110117. return SQLITE_OK;
  110118. }
  110119. #ifndef SQLITE_OMIT_UTF16
  110120. /*
  110121. ** Register a collation sequence factory callback with the database handle
  110122. ** db. Replace any previously installed collation sequence factory.
  110123. */
  110124. SQLITE_API int sqlite3_collation_needed16(
  110125. sqlite3 *db,
  110126. void *pCollNeededArg,
  110127. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  110128. ){
  110129. sqlite3_mutex_enter(db->mutex);
  110130. db->xCollNeeded = 0;
  110131. db->xCollNeeded16 = xCollNeeded16;
  110132. db->pCollNeededArg = pCollNeededArg;
  110133. sqlite3_mutex_leave(db->mutex);
  110134. return SQLITE_OK;
  110135. }
  110136. #endif /* SQLITE_OMIT_UTF16 */
  110137. #ifndef SQLITE_OMIT_DEPRECATED
  110138. /*
  110139. ** This function is now an anachronism. It used to be used to recover from a
  110140. ** malloc() failure, but SQLite now does this automatically.
  110141. */
  110142. SQLITE_API int sqlite3_global_recover(void){
  110143. return SQLITE_OK;
  110144. }
  110145. #endif
  110146. /*
  110147. ** Test to see whether or not the database connection is in autocommit
  110148. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  110149. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  110150. ** by the next COMMIT or ROLLBACK.
  110151. **
  110152. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  110153. */
  110154. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  110155. return db->autoCommit;
  110156. }
  110157. /*
  110158. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  110159. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  110160. ** constants. They server two purposes:
  110161. **
  110162. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  110163. ** to detect when version error conditions occurs.
  110164. **
  110165. ** 2. Invoke sqlite3_log() to provide the source code location where
  110166. ** a low-level error is first detected.
  110167. */
  110168. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  110169. testcase( sqlite3GlobalConfig.xLog!=0 );
  110170. sqlite3_log(SQLITE_CORRUPT,
  110171. "database corruption at line %d of [%.10s]",
  110172. lineno, 20+sqlite3_sourceid());
  110173. return SQLITE_CORRUPT;
  110174. }
  110175. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  110176. testcase( sqlite3GlobalConfig.xLog!=0 );
  110177. sqlite3_log(SQLITE_MISUSE,
  110178. "misuse at line %d of [%.10s]",
  110179. lineno, 20+sqlite3_sourceid());
  110180. return SQLITE_MISUSE;
  110181. }
  110182. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  110183. testcase( sqlite3GlobalConfig.xLog!=0 );
  110184. sqlite3_log(SQLITE_CANTOPEN,
  110185. "cannot open file at line %d of [%.10s]",
  110186. lineno, 20+sqlite3_sourceid());
  110187. return SQLITE_CANTOPEN;
  110188. }
  110189. #ifndef SQLITE_OMIT_DEPRECATED
  110190. /*
  110191. ** This is a convenience routine that makes sure that all thread-specific
  110192. ** data for this thread has been deallocated.
  110193. **
  110194. ** SQLite no longer uses thread-specific data so this routine is now a
  110195. ** no-op. It is retained for historical compatibility.
  110196. */
  110197. SQLITE_API void sqlite3_thread_cleanup(void){
  110198. }
  110199. #endif
  110200. /*
  110201. ** Return meta information about a specific column of a database table.
  110202. ** See comment in sqlite3.h (sqlite.h.in) for details.
  110203. */
  110204. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110205. SQLITE_API int sqlite3_table_column_metadata(
  110206. sqlite3 *db, /* Connection handle */
  110207. const char *zDbName, /* Database name or NULL */
  110208. const char *zTableName, /* Table name */
  110209. const char *zColumnName, /* Column name */
  110210. char const **pzDataType, /* OUTPUT: Declared data type */
  110211. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  110212. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  110213. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  110214. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  110215. ){
  110216. int rc;
  110217. char *zErrMsg = 0;
  110218. Table *pTab = 0;
  110219. Column *pCol = 0;
  110220. int iCol;
  110221. char const *zDataType = 0;
  110222. char const *zCollSeq = 0;
  110223. int notnull = 0;
  110224. int primarykey = 0;
  110225. int autoinc = 0;
  110226. /* Ensure the database schema has been loaded */
  110227. sqlite3_mutex_enter(db->mutex);
  110228. sqlite3BtreeEnterAll(db);
  110229. rc = sqlite3Init(db, &zErrMsg);
  110230. if( SQLITE_OK!=rc ){
  110231. goto error_out;
  110232. }
  110233. /* Locate the table in question */
  110234. pTab = sqlite3FindTable(db, zTableName, zDbName);
  110235. if( !pTab || pTab->pSelect ){
  110236. pTab = 0;
  110237. goto error_out;
  110238. }
  110239. /* Find the column for which info is requested */
  110240. if( sqlite3IsRowid(zColumnName) ){
  110241. iCol = pTab->iPKey;
  110242. if( iCol>=0 ){
  110243. pCol = &pTab->aCol[iCol];
  110244. }
  110245. }else{
  110246. for(iCol=0; iCol<pTab->nCol; iCol++){
  110247. pCol = &pTab->aCol[iCol];
  110248. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  110249. break;
  110250. }
  110251. }
  110252. if( iCol==pTab->nCol ){
  110253. pTab = 0;
  110254. goto error_out;
  110255. }
  110256. }
  110257. /* The following block stores the meta information that will be returned
  110258. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  110259. ** and autoinc. At this point there are two possibilities:
  110260. **
  110261. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  110262. ** and there is no explicitly declared IPK column.
  110263. **
  110264. ** 2. The table is not a view and the column name identified an
  110265. ** explicitly declared column. Copy meta information from *pCol.
  110266. */
  110267. if( pCol ){
  110268. zDataType = pCol->zType;
  110269. zCollSeq = pCol->zColl;
  110270. notnull = pCol->notNull!=0;
  110271. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  110272. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  110273. }else{
  110274. zDataType = "INTEGER";
  110275. primarykey = 1;
  110276. }
  110277. if( !zCollSeq ){
  110278. zCollSeq = "BINARY";
  110279. }
  110280. error_out:
  110281. sqlite3BtreeLeaveAll(db);
  110282. /* Whether the function call succeeded or failed, set the output parameters
  110283. ** to whatever their local counterparts contain. If an error did occur,
  110284. ** this has the effect of zeroing all output parameters.
  110285. */
  110286. if( pzDataType ) *pzDataType = zDataType;
  110287. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  110288. if( pNotNull ) *pNotNull = notnull;
  110289. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  110290. if( pAutoinc ) *pAutoinc = autoinc;
  110291. if( SQLITE_OK==rc && !pTab ){
  110292. sqlite3DbFree(db, zErrMsg);
  110293. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  110294. zColumnName);
  110295. rc = SQLITE_ERROR;
  110296. }
  110297. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  110298. sqlite3DbFree(db, zErrMsg);
  110299. rc = sqlite3ApiExit(db, rc);
  110300. sqlite3_mutex_leave(db->mutex);
  110301. return rc;
  110302. }
  110303. #endif
  110304. /*
  110305. ** Sleep for a little while. Return the amount of time slept.
  110306. */
  110307. SQLITE_API int sqlite3_sleep(int ms){
  110308. sqlite3_vfs *pVfs;
  110309. int rc;
  110310. pVfs = sqlite3_vfs_find(0);
  110311. if( pVfs==0 ) return 0;
  110312. /* This function works in milliseconds, but the underlying OsSleep()
  110313. ** API uses microseconds. Hence the 1000's.
  110314. */
  110315. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  110316. return rc;
  110317. }
  110318. /*
  110319. ** Enable or disable the extended result codes.
  110320. */
  110321. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  110322. sqlite3_mutex_enter(db->mutex);
  110323. db->errMask = onoff ? 0xffffffff : 0xff;
  110324. sqlite3_mutex_leave(db->mutex);
  110325. return SQLITE_OK;
  110326. }
  110327. /*
  110328. ** Invoke the xFileControl method on a particular database.
  110329. */
  110330. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  110331. int rc = SQLITE_ERROR;
  110332. Btree *pBtree;
  110333. sqlite3_mutex_enter(db->mutex);
  110334. pBtree = sqlite3DbNameToBtree(db, zDbName);
  110335. if( pBtree ){
  110336. Pager *pPager;
  110337. sqlite3_file *fd;
  110338. sqlite3BtreeEnter(pBtree);
  110339. pPager = sqlite3BtreePager(pBtree);
  110340. assert( pPager!=0 );
  110341. fd = sqlite3PagerFile(pPager);
  110342. assert( fd!=0 );
  110343. if( op==SQLITE_FCNTL_FILE_POINTER ){
  110344. *(sqlite3_file**)pArg = fd;
  110345. rc = SQLITE_OK;
  110346. }else if( fd->pMethods ){
  110347. rc = sqlite3OsFileControl(fd, op, pArg);
  110348. }else{
  110349. rc = SQLITE_NOTFOUND;
  110350. }
  110351. sqlite3BtreeLeave(pBtree);
  110352. }
  110353. sqlite3_mutex_leave(db->mutex);
  110354. return rc;
  110355. }
  110356. /*
  110357. ** Interface to the testing logic.
  110358. */
  110359. SQLITE_API int sqlite3_test_control(int op, ...){
  110360. int rc = 0;
  110361. #ifndef SQLITE_OMIT_BUILTIN_TEST
  110362. va_list ap;
  110363. va_start(ap, op);
  110364. switch( op ){
  110365. /*
  110366. ** Save the current state of the PRNG.
  110367. */
  110368. case SQLITE_TESTCTRL_PRNG_SAVE: {
  110369. sqlite3PrngSaveState();
  110370. break;
  110371. }
  110372. /*
  110373. ** Restore the state of the PRNG to the last state saved using
  110374. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  110375. ** this verb acts like PRNG_RESET.
  110376. */
  110377. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  110378. sqlite3PrngRestoreState();
  110379. break;
  110380. }
  110381. /*
  110382. ** Reset the PRNG back to its uninitialized state. The next call
  110383. ** to sqlite3_randomness() will reseed the PRNG using a single call
  110384. ** to the xRandomness method of the default VFS.
  110385. */
  110386. case SQLITE_TESTCTRL_PRNG_RESET: {
  110387. sqlite3PrngResetState();
  110388. break;
  110389. }
  110390. /*
  110391. ** sqlite3_test_control(BITVEC_TEST, size, program)
  110392. **
  110393. ** Run a test against a Bitvec object of size. The program argument
  110394. ** is an array of integers that defines the test. Return -1 on a
  110395. ** memory allocation error, 0 on success, or non-zero for an error.
  110396. ** See the sqlite3BitvecBuiltinTest() for additional information.
  110397. */
  110398. case SQLITE_TESTCTRL_BITVEC_TEST: {
  110399. int sz = va_arg(ap, int);
  110400. int *aProg = va_arg(ap, int*);
  110401. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  110402. break;
  110403. }
  110404. /*
  110405. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  110406. **
  110407. ** Register hooks to call to indicate which malloc() failures
  110408. ** are benign.
  110409. */
  110410. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  110411. typedef void (*void_function)(void);
  110412. void_function xBenignBegin;
  110413. void_function xBenignEnd;
  110414. xBenignBegin = va_arg(ap, void_function);
  110415. xBenignEnd = va_arg(ap, void_function);
  110416. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  110417. break;
  110418. }
  110419. /*
  110420. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  110421. **
  110422. ** Set the PENDING byte to the value in the argument, if X>0.
  110423. ** Make no changes if X==0. Return the value of the pending byte
  110424. ** as it existing before this routine was called.
  110425. **
  110426. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  110427. ** an incompatible database file format. Changing the PENDING byte
  110428. ** while any database connection is open results in undefined and
  110429. ** dileterious behavior.
  110430. */
  110431. case SQLITE_TESTCTRL_PENDING_BYTE: {
  110432. rc = PENDING_BYTE;
  110433. #ifndef SQLITE_OMIT_WSD
  110434. {
  110435. unsigned int newVal = va_arg(ap, unsigned int);
  110436. if( newVal ) sqlite3PendingByte = newVal;
  110437. }
  110438. #endif
  110439. break;
  110440. }
  110441. /*
  110442. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  110443. **
  110444. ** This action provides a run-time test to see whether or not
  110445. ** assert() was enabled at compile-time. If X is true and assert()
  110446. ** is enabled, then the return value is true. If X is true and
  110447. ** assert() is disabled, then the return value is zero. If X is
  110448. ** false and assert() is enabled, then the assertion fires and the
  110449. ** process aborts. If X is false and assert() is disabled, then the
  110450. ** return value is zero.
  110451. */
  110452. case SQLITE_TESTCTRL_ASSERT: {
  110453. volatile int x = 0;
  110454. assert( (x = va_arg(ap,int))!=0 );
  110455. rc = x;
  110456. break;
  110457. }
  110458. /*
  110459. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  110460. **
  110461. ** This action provides a run-time test to see how the ALWAYS and
  110462. ** NEVER macros were defined at compile-time.
  110463. **
  110464. ** The return value is ALWAYS(X).
  110465. **
  110466. ** The recommended test is X==2. If the return value is 2, that means
  110467. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  110468. ** default setting. If the return value is 1, then ALWAYS() is either
  110469. ** hard-coded to true or else it asserts if its argument is false.
  110470. ** The first behavior (hard-coded to true) is the case if
  110471. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  110472. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  110473. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  110474. **
  110475. ** The run-time test procedure might look something like this:
  110476. **
  110477. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  110478. ** // ALWAYS() and NEVER() are no-op pass-through macros
  110479. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  110480. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  110481. ** }else{
  110482. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  110483. ** }
  110484. */
  110485. case SQLITE_TESTCTRL_ALWAYS: {
  110486. int x = va_arg(ap,int);
  110487. rc = ALWAYS(x);
  110488. break;
  110489. }
  110490. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  110491. **
  110492. ** Set the nReserve size to N for the main database on the database
  110493. ** connection db.
  110494. */
  110495. case SQLITE_TESTCTRL_RESERVE: {
  110496. sqlite3 *db = va_arg(ap, sqlite3*);
  110497. int x = va_arg(ap,int);
  110498. sqlite3_mutex_enter(db->mutex);
  110499. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  110500. sqlite3_mutex_leave(db->mutex);
  110501. break;
  110502. }
  110503. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  110504. **
  110505. ** Enable or disable various optimizations for testing purposes. The
  110506. ** argument N is a bitmask of optimizations to be disabled. For normal
  110507. ** operation N should be 0. The idea is that a test program (like the
  110508. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  110509. ** with various optimizations disabled to verify that the same answer
  110510. ** is obtained in every case.
  110511. */
  110512. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  110513. sqlite3 *db = va_arg(ap, sqlite3*);
  110514. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  110515. break;
  110516. }
  110517. #ifdef SQLITE_N_KEYWORD
  110518. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  110519. **
  110520. ** If zWord is a keyword recognized by the parser, then return the
  110521. ** number of keywords. Or if zWord is not a keyword, return 0.
  110522. **
  110523. ** This test feature is only available in the amalgamation since
  110524. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  110525. ** is built using separate source files.
  110526. */
  110527. case SQLITE_TESTCTRL_ISKEYWORD: {
  110528. const char *zWord = va_arg(ap, const char*);
  110529. int n = sqlite3Strlen30(zWord);
  110530. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  110531. break;
  110532. }
  110533. #endif
  110534. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  110535. **
  110536. ** Pass pFree into sqlite3ScratchFree().
  110537. ** If sz>0 then allocate a scratch buffer into pNew.
  110538. */
  110539. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  110540. void *pFree, **ppNew;
  110541. int sz;
  110542. sz = va_arg(ap, int);
  110543. ppNew = va_arg(ap, void**);
  110544. pFree = va_arg(ap, void*);
  110545. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  110546. sqlite3ScratchFree(pFree);
  110547. break;
  110548. }
  110549. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  110550. **
  110551. ** If parameter onoff is non-zero, configure the wrappers so that all
  110552. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  110553. ** undo this setting.
  110554. */
  110555. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  110556. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  110557. break;
  110558. }
  110559. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  110560. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  110561. ** sqlite3_stmt*,const char**);
  110562. **
  110563. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  110564. ** a string that describes the optimized parse tree. This test-control
  110565. ** returns a pointer to that string.
  110566. */
  110567. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  110568. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  110569. const char **pzRet = va_arg(ap, const char**);
  110570. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  110571. break;
  110572. }
  110573. #endif
  110574. }
  110575. va_end(ap);
  110576. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  110577. return rc;
  110578. }
  110579. /*
  110580. ** This is a utility routine, useful to VFS implementations, that checks
  110581. ** to see if a database file was a URI that contained a specific query
  110582. ** parameter, and if so obtains the value of the query parameter.
  110583. **
  110584. ** The zFilename argument is the filename pointer passed into the xOpen()
  110585. ** method of a VFS implementation. The zParam argument is the name of the
  110586. ** query parameter we seek. This routine returns the value of the zParam
  110587. ** parameter if it exists. If the parameter does not exist, this routine
  110588. ** returns a NULL pointer.
  110589. */
  110590. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  110591. if( zFilename==0 ) return 0;
  110592. zFilename += sqlite3Strlen30(zFilename) + 1;
  110593. while( zFilename[0] ){
  110594. int x = strcmp(zFilename, zParam);
  110595. zFilename += sqlite3Strlen30(zFilename) + 1;
  110596. if( x==0 ) return zFilename;
  110597. zFilename += sqlite3Strlen30(zFilename) + 1;
  110598. }
  110599. return 0;
  110600. }
  110601. /*
  110602. ** Return a boolean value for a query parameter.
  110603. */
  110604. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  110605. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  110606. bDflt = bDflt!=0;
  110607. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  110608. }
  110609. /*
  110610. ** Return a 64-bit integer value for a query parameter.
  110611. */
  110612. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  110613. const char *zFilename, /* Filename as passed to xOpen */
  110614. const char *zParam, /* URI parameter sought */
  110615. sqlite3_int64 bDflt /* return if parameter is missing */
  110616. ){
  110617. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  110618. sqlite3_int64 v;
  110619. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  110620. bDflt = v;
  110621. }
  110622. return bDflt;
  110623. }
  110624. /*
  110625. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  110626. */
  110627. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  110628. int i;
  110629. for(i=0; i<db->nDb; i++){
  110630. if( db->aDb[i].pBt
  110631. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  110632. ){
  110633. return db->aDb[i].pBt;
  110634. }
  110635. }
  110636. return 0;
  110637. }
  110638. /*
  110639. ** Return the filename of the database associated with a database
  110640. ** connection.
  110641. */
  110642. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  110643. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  110644. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  110645. }
  110646. /*
  110647. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  110648. ** no such database exists.
  110649. */
  110650. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  110651. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  110652. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  110653. }
  110654. /************** End of main.c ************************************************/
  110655. /************** Begin file notify.c ******************************************/
  110656. /*
  110657. ** 2009 March 3
  110658. **
  110659. ** The author disclaims copyright to this source code. In place of
  110660. ** a legal notice, here is a blessing:
  110661. **
  110662. ** May you do good and not evil.
  110663. ** May you find forgiveness for yourself and forgive others.
  110664. ** May you share freely, never taking more than you give.
  110665. **
  110666. *************************************************************************
  110667. **
  110668. ** This file contains the implementation of the sqlite3_unlock_notify()
  110669. ** API method and its associated functionality.
  110670. */
  110671. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  110672. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  110673. /*
  110674. ** Public interfaces:
  110675. **
  110676. ** sqlite3ConnectionBlocked()
  110677. ** sqlite3ConnectionUnlocked()
  110678. ** sqlite3ConnectionClosed()
  110679. ** sqlite3_unlock_notify()
  110680. */
  110681. #define assertMutexHeld() \
  110682. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  110683. /*
  110684. ** Head of a linked list of all sqlite3 objects created by this process
  110685. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  110686. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  110687. ** mutex is held.
  110688. */
  110689. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  110690. #ifndef NDEBUG
  110691. /*
  110692. ** This function is a complex assert() that verifies the following
  110693. ** properties of the blocked connections list:
  110694. **
  110695. ** 1) Each entry in the list has a non-NULL value for either
  110696. ** pUnlockConnection or pBlockingConnection, or both.
  110697. **
  110698. ** 2) All entries in the list that share a common value for
  110699. ** xUnlockNotify are grouped together.
  110700. **
  110701. ** 3) If the argument db is not NULL, then none of the entries in the
  110702. ** blocked connections list have pUnlockConnection or pBlockingConnection
  110703. ** set to db. This is used when closing connection db.
  110704. */
  110705. static void checkListProperties(sqlite3 *db){
  110706. sqlite3 *p;
  110707. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  110708. int seen = 0;
  110709. sqlite3 *p2;
  110710. /* Verify property (1) */
  110711. assert( p->pUnlockConnection || p->pBlockingConnection );
  110712. /* Verify property (2) */
  110713. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  110714. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  110715. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  110716. assert( db==0 || p->pUnlockConnection!=db );
  110717. assert( db==0 || p->pBlockingConnection!=db );
  110718. }
  110719. }
  110720. }
  110721. #else
  110722. # define checkListProperties(x)
  110723. #endif
  110724. /*
  110725. ** Remove connection db from the blocked connections list. If connection
  110726. ** db is not currently a part of the list, this function is a no-op.
  110727. */
  110728. static void removeFromBlockedList(sqlite3 *db){
  110729. sqlite3 **pp;
  110730. assertMutexHeld();
  110731. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  110732. if( *pp==db ){
  110733. *pp = (*pp)->pNextBlocked;
  110734. break;
  110735. }
  110736. }
  110737. }
  110738. /*
  110739. ** Add connection db to the blocked connections list. It is assumed
  110740. ** that it is not already a part of the list.
  110741. */
  110742. static void addToBlockedList(sqlite3 *db){
  110743. sqlite3 **pp;
  110744. assertMutexHeld();
  110745. for(
  110746. pp=&sqlite3BlockedList;
  110747. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  110748. pp=&(*pp)->pNextBlocked
  110749. );
  110750. db->pNextBlocked = *pp;
  110751. *pp = db;
  110752. }
  110753. /*
  110754. ** Obtain the STATIC_MASTER mutex.
  110755. */
  110756. static void enterMutex(void){
  110757. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  110758. checkListProperties(0);
  110759. }
  110760. /*
  110761. ** Release the STATIC_MASTER mutex.
  110762. */
  110763. static void leaveMutex(void){
  110764. assertMutexHeld();
  110765. checkListProperties(0);
  110766. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  110767. }
  110768. /*
  110769. ** Register an unlock-notify callback.
  110770. **
  110771. ** This is called after connection "db" has attempted some operation
  110772. ** but has received an SQLITE_LOCKED error because another connection
  110773. ** (call it pOther) in the same process was busy using the same shared
  110774. ** cache. pOther is found by looking at db->pBlockingConnection.
  110775. **
  110776. ** If there is no blocking connection, the callback is invoked immediately,
  110777. ** before this routine returns.
  110778. **
  110779. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  110780. ** a deadlock.
  110781. **
  110782. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  110783. ** its locks.
  110784. **
  110785. ** Each call to this routine overrides any prior callbacks registered
  110786. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  110787. ** cancelled.
  110788. */
  110789. SQLITE_API int sqlite3_unlock_notify(
  110790. sqlite3 *db,
  110791. void (*xNotify)(void **, int),
  110792. void *pArg
  110793. ){
  110794. int rc = SQLITE_OK;
  110795. sqlite3_mutex_enter(db->mutex);
  110796. enterMutex();
  110797. if( xNotify==0 ){
  110798. removeFromBlockedList(db);
  110799. db->pBlockingConnection = 0;
  110800. db->pUnlockConnection = 0;
  110801. db->xUnlockNotify = 0;
  110802. db->pUnlockArg = 0;
  110803. }else if( 0==db->pBlockingConnection ){
  110804. /* The blocking transaction has been concluded. Or there never was a
  110805. ** blocking transaction. In either case, invoke the notify callback
  110806. ** immediately.
  110807. */
  110808. xNotify(&pArg, 1);
  110809. }else{
  110810. sqlite3 *p;
  110811. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  110812. if( p ){
  110813. rc = SQLITE_LOCKED; /* Deadlock detected. */
  110814. }else{
  110815. db->pUnlockConnection = db->pBlockingConnection;
  110816. db->xUnlockNotify = xNotify;
  110817. db->pUnlockArg = pArg;
  110818. removeFromBlockedList(db);
  110819. addToBlockedList(db);
  110820. }
  110821. }
  110822. leaveMutex();
  110823. assert( !db->mallocFailed );
  110824. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  110825. sqlite3_mutex_leave(db->mutex);
  110826. return rc;
  110827. }
  110828. /*
  110829. ** This function is called while stepping or preparing a statement
  110830. ** associated with connection db. The operation will return SQLITE_LOCKED
  110831. ** to the user because it requires a lock that will not be available
  110832. ** until connection pBlocker concludes its current transaction.
  110833. */
  110834. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  110835. enterMutex();
  110836. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  110837. addToBlockedList(db);
  110838. }
  110839. db->pBlockingConnection = pBlocker;
  110840. leaveMutex();
  110841. }
  110842. /*
  110843. ** This function is called when
  110844. ** the transaction opened by database db has just finished. Locks held
  110845. ** by database connection db have been released.
  110846. **
  110847. ** This function loops through each entry in the blocked connections
  110848. ** list and does the following:
  110849. **
  110850. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  110851. ** set to db, then set pBlockingConnection=0.
  110852. **
  110853. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  110854. ** set to db, then invoke the configured unlock-notify callback and
  110855. ** set pUnlockConnection=0.
  110856. **
  110857. ** 3) If the two steps above mean that pBlockingConnection==0 and
  110858. ** pUnlockConnection==0, remove the entry from the blocked connections
  110859. ** list.
  110860. */
  110861. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  110862. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  110863. int nArg = 0; /* Number of entries in aArg[] */
  110864. sqlite3 **pp; /* Iterator variable */
  110865. void **aArg; /* Arguments to the unlock callback */
  110866. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  110867. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  110868. aArg = aStatic;
  110869. enterMutex(); /* Enter STATIC_MASTER mutex */
  110870. /* This loop runs once for each entry in the blocked-connections list. */
  110871. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  110872. sqlite3 *p = *pp;
  110873. /* Step 1. */
  110874. if( p->pBlockingConnection==db ){
  110875. p->pBlockingConnection = 0;
  110876. }
  110877. /* Step 2. */
  110878. if( p->pUnlockConnection==db ){
  110879. assert( p->xUnlockNotify );
  110880. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  110881. xUnlockNotify(aArg, nArg);
  110882. nArg = 0;
  110883. }
  110884. sqlite3BeginBenignMalloc();
  110885. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  110886. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  110887. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  110888. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  110889. ){
  110890. /* The aArg[] array needs to grow. */
  110891. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  110892. if( pNew ){
  110893. memcpy(pNew, aArg, nArg*sizeof(void *));
  110894. sqlite3_free(aDyn);
  110895. aDyn = aArg = pNew;
  110896. }else{
  110897. /* This occurs when the array of context pointers that need to
  110898. ** be passed to the unlock-notify callback is larger than the
  110899. ** aStatic[] array allocated on the stack and the attempt to
  110900. ** allocate a larger array from the heap has failed.
  110901. **
  110902. ** This is a difficult situation to handle. Returning an error
  110903. ** code to the caller is insufficient, as even if an error code
  110904. ** is returned the transaction on connection db will still be
  110905. ** closed and the unlock-notify callbacks on blocked connections
  110906. ** will go unissued. This might cause the application to wait
  110907. ** indefinitely for an unlock-notify callback that will never
  110908. ** arrive.
  110909. **
  110910. ** Instead, invoke the unlock-notify callback with the context
  110911. ** array already accumulated. We can then clear the array and
  110912. ** begin accumulating any further context pointers without
  110913. ** requiring any dynamic allocation. This is sub-optimal because
  110914. ** it means that instead of one callback with a large array of
  110915. ** context pointers the application will receive two or more
  110916. ** callbacks with smaller arrays of context pointers, which will
  110917. ** reduce the applications ability to prioritize multiple
  110918. ** connections. But it is the best that can be done under the
  110919. ** circumstances.
  110920. */
  110921. xUnlockNotify(aArg, nArg);
  110922. nArg = 0;
  110923. }
  110924. }
  110925. sqlite3EndBenignMalloc();
  110926. aArg[nArg++] = p->pUnlockArg;
  110927. xUnlockNotify = p->xUnlockNotify;
  110928. p->pUnlockConnection = 0;
  110929. p->xUnlockNotify = 0;
  110930. p->pUnlockArg = 0;
  110931. }
  110932. /* Step 3. */
  110933. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  110934. /* Remove connection p from the blocked connections list. */
  110935. *pp = p->pNextBlocked;
  110936. p->pNextBlocked = 0;
  110937. }else{
  110938. pp = &p->pNextBlocked;
  110939. }
  110940. }
  110941. if( nArg!=0 ){
  110942. xUnlockNotify(aArg, nArg);
  110943. }
  110944. sqlite3_free(aDyn);
  110945. leaveMutex(); /* Leave STATIC_MASTER mutex */
  110946. }
  110947. /*
  110948. ** This is called when the database connection passed as an argument is
  110949. ** being closed. The connection is removed from the blocked list.
  110950. */
  110951. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  110952. sqlite3ConnectionUnlocked(db);
  110953. enterMutex();
  110954. removeFromBlockedList(db);
  110955. checkListProperties(db);
  110956. leaveMutex();
  110957. }
  110958. #endif
  110959. /************** End of notify.c **********************************************/
  110960. /************** Begin file fts3.c ********************************************/
  110961. /*
  110962. ** 2006 Oct 10
  110963. **
  110964. ** The author disclaims copyright to this source code. In place of
  110965. ** a legal notice, here is a blessing:
  110966. **
  110967. ** May you do good and not evil.
  110968. ** May you find forgiveness for yourself and forgive others.
  110969. ** May you share freely, never taking more than you give.
  110970. **
  110971. ******************************************************************************
  110972. **
  110973. ** This is an SQLite module implementing full-text search.
  110974. */
  110975. /*
  110976. ** The code in this file is only compiled if:
  110977. **
  110978. ** * The FTS3 module is being built as an extension
  110979. ** (in which case SQLITE_CORE is not defined), or
  110980. **
  110981. ** * The FTS3 module is being built into the core of
  110982. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  110983. */
  110984. /* The full-text index is stored in a series of b+tree (-like)
  110985. ** structures called segments which map terms to doclists. The
  110986. ** structures are like b+trees in layout, but are constructed from the
  110987. ** bottom up in optimal fashion and are not updatable. Since trees
  110988. ** are built from the bottom up, things will be described from the
  110989. ** bottom up.
  110990. **
  110991. **
  110992. **** Varints ****
  110993. ** The basic unit of encoding is a variable-length integer called a
  110994. ** varint. We encode variable-length integers in little-endian order
  110995. ** using seven bits * per byte as follows:
  110996. **
  110997. ** KEY:
  110998. ** A = 0xxxxxxx 7 bits of data and one flag bit
  110999. ** B = 1xxxxxxx 7 bits of data and one flag bit
  111000. **
  111001. ** 7 bits - A
  111002. ** 14 bits - BA
  111003. ** 21 bits - BBA
  111004. ** and so on.
  111005. **
  111006. ** This is similar in concept to how sqlite encodes "varints" but
  111007. ** the encoding is not the same. SQLite varints are big-endian
  111008. ** are are limited to 9 bytes in length whereas FTS3 varints are
  111009. ** little-endian and can be up to 10 bytes in length (in theory).
  111010. **
  111011. ** Example encodings:
  111012. **
  111013. ** 1: 0x01
  111014. ** 127: 0x7f
  111015. ** 128: 0x81 0x00
  111016. **
  111017. **
  111018. **** Document lists ****
  111019. ** A doclist (document list) holds a docid-sorted list of hits for a
  111020. ** given term. Doclists hold docids and associated token positions.
  111021. ** A docid is the unique integer identifier for a single document.
  111022. ** A position is the index of a word within the document. The first
  111023. ** word of the document has a position of 0.
  111024. **
  111025. ** FTS3 used to optionally store character offsets using a compile-time
  111026. ** option. But that functionality is no longer supported.
  111027. **
  111028. ** A doclist is stored like this:
  111029. **
  111030. ** array {
  111031. ** varint docid; (delta from previous doclist)
  111032. ** array { (position list for column 0)
  111033. ** varint position; (2 more than the delta from previous position)
  111034. ** }
  111035. ** array {
  111036. ** varint POS_COLUMN; (marks start of position list for new column)
  111037. ** varint column; (index of new column)
  111038. ** array {
  111039. ** varint position; (2 more than the delta from previous position)
  111040. ** }
  111041. ** }
  111042. ** varint POS_END; (marks end of positions for this document.
  111043. ** }
  111044. **
  111045. ** Here, array { X } means zero or more occurrences of X, adjacent in
  111046. ** memory. A "position" is an index of a token in the token stream
  111047. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  111048. ** in the same logical place as the position element, and act as sentinals
  111049. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  111050. ** The positions numbers are not stored literally but rather as two more
  111051. ** than the difference from the prior position, or the just the position plus
  111052. ** 2 for the first position. Example:
  111053. **
  111054. ** label: A B C D E F G H I J K
  111055. ** value: 123 5 9 1 1 14 35 0 234 72 0
  111056. **
  111057. ** The 123 value is the first docid. For column zero in this document
  111058. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  111059. ** at D signals the start of a new column; the 1 at E indicates that the
  111060. ** new column is column number 1. There are two positions at 12 and 45
  111061. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  111062. ** 234 at I is the delta to next docid (357). It has one position 70
  111063. ** (72-2) and then terminates with the 0 at K.
  111064. **
  111065. ** A "position-list" is the list of positions for multiple columns for
  111066. ** a single docid. A "column-list" is the set of positions for a single
  111067. ** column. Hence, a position-list consists of one or more column-lists,
  111068. ** a document record consists of a docid followed by a position-list and
  111069. ** a doclist consists of one or more document records.
  111070. **
  111071. ** A bare doclist omits the position information, becoming an
  111072. ** array of varint-encoded docids.
  111073. **
  111074. **** Segment leaf nodes ****
  111075. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  111076. ** nodes are written using LeafWriter, and read using LeafReader (to
  111077. ** iterate through a single leaf node's data) and LeavesReader (to
  111078. ** iterate through a segment's entire leaf layer). Leaf nodes have
  111079. ** the format:
  111080. **
  111081. ** varint iHeight; (height from leaf level, always 0)
  111082. ** varint nTerm; (length of first term)
  111083. ** char pTerm[nTerm]; (content of first term)
  111084. ** varint nDoclist; (length of term's associated doclist)
  111085. ** char pDoclist[nDoclist]; (content of doclist)
  111086. ** array {
  111087. ** (further terms are delta-encoded)
  111088. ** varint nPrefix; (length of prefix shared with previous term)
  111089. ** varint nSuffix; (length of unshared suffix)
  111090. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  111091. ** varint nDoclist; (length of term's associated doclist)
  111092. ** char pDoclist[nDoclist]; (content of doclist)
  111093. ** }
  111094. **
  111095. ** Here, array { X } means zero or more occurrences of X, adjacent in
  111096. ** memory.
  111097. **
  111098. ** Leaf nodes are broken into blocks which are stored contiguously in
  111099. ** the %_segments table in sorted order. This means that when the end
  111100. ** of a node is reached, the next term is in the node with the next
  111101. ** greater node id.
  111102. **
  111103. ** New data is spilled to a new leaf node when the current node
  111104. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  111105. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  111106. ** node (a leaf node with a single term and doclist). The goal of
  111107. ** these settings is to pack together groups of small doclists while
  111108. ** making it efficient to directly access large doclists. The
  111109. ** assumption is that large doclists represent terms which are more
  111110. ** likely to be query targets.
  111111. **
  111112. ** TODO(shess) It may be useful for blocking decisions to be more
  111113. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  111114. ** node rather than splitting into 2k and .5k nodes. My intuition is
  111115. ** that this might extend through 2x or 4x the pagesize.
  111116. **
  111117. **
  111118. **** Segment interior nodes ****
  111119. ** Segment interior nodes store blockids for subtree nodes and terms
  111120. ** to describe what data is stored by the each subtree. Interior
  111121. ** nodes are written using InteriorWriter, and read using
  111122. ** InteriorReader. InteriorWriters are created as needed when
  111123. ** SegmentWriter creates new leaf nodes, or when an interior node
  111124. ** itself grows too big and must be split. The format of interior
  111125. ** nodes:
  111126. **
  111127. ** varint iHeight; (height from leaf level, always >0)
  111128. ** varint iBlockid; (block id of node's leftmost subtree)
  111129. ** optional {
  111130. ** varint nTerm; (length of first term)
  111131. ** char pTerm[nTerm]; (content of first term)
  111132. ** array {
  111133. ** (further terms are delta-encoded)
  111134. ** varint nPrefix; (length of shared prefix with previous term)
  111135. ** varint nSuffix; (length of unshared suffix)
  111136. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  111137. ** }
  111138. ** }
  111139. **
  111140. ** Here, optional { X } means an optional element, while array { X }
  111141. ** means zero or more occurrences of X, adjacent in memory.
  111142. **
  111143. ** An interior node encodes n terms separating n+1 subtrees. The
  111144. ** subtree blocks are contiguous, so only the first subtree's blockid
  111145. ** is encoded. The subtree at iBlockid will contain all terms less
  111146. ** than the first term encoded (or all terms if no term is encoded).
  111147. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  111148. ** than pTerm[i+1], the subtree for that term will be rooted at
  111149. ** iBlockid+i. Interior nodes only store enough term data to
  111150. ** distinguish adjacent children (if the rightmost term of the left
  111151. ** child is "something", and the leftmost term of the right child is
  111152. ** "wicked", only "w" is stored).
  111153. **
  111154. ** New data is spilled to a new interior node at the same height when
  111155. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  111156. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  111157. ** interior nodes and making the tree too skinny. The interior nodes
  111158. ** at a given height are naturally tracked by interior nodes at
  111159. ** height+1, and so on.
  111160. **
  111161. **
  111162. **** Segment directory ****
  111163. ** The segment directory in table %_segdir stores meta-information for
  111164. ** merging and deleting segments, and also the root node of the
  111165. ** segment's tree.
  111166. **
  111167. ** The root node is the top node of the segment's tree after encoding
  111168. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  111169. ** This could be either a leaf node or an interior node. If the top
  111170. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  111171. ** and a new root interior node is generated (which should always fit
  111172. ** within ROOT_MAX because it only needs space for 2 varints, the
  111173. ** height and the blockid of the previous root).
  111174. **
  111175. ** The meta-information in the segment directory is:
  111176. ** level - segment level (see below)
  111177. ** idx - index within level
  111178. ** - (level,idx uniquely identify a segment)
  111179. ** start_block - first leaf node
  111180. ** leaves_end_block - last leaf node
  111181. ** end_block - last block (including interior nodes)
  111182. ** root - contents of root node
  111183. **
  111184. ** If the root node is a leaf node, then start_block,
  111185. ** leaves_end_block, and end_block are all 0.
  111186. **
  111187. **
  111188. **** Segment merging ****
  111189. ** To amortize update costs, segments are grouped into levels and
  111190. ** merged in batches. Each increase in level represents exponentially
  111191. ** more documents.
  111192. **
  111193. ** New documents (actually, document updates) are tokenized and
  111194. ** written individually (using LeafWriter) to a level 0 segment, with
  111195. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  111196. ** level 0 segments are merged into a single level 1 segment. Level 1
  111197. ** is populated like level 0, and eventually MERGE_COUNT level 1
  111198. ** segments are merged to a single level 2 segment (representing
  111199. ** MERGE_COUNT^2 updates), and so on.
  111200. **
  111201. ** A segment merge traverses all segments at a given level in
  111202. ** parallel, performing a straightforward sorted merge. Since segment
  111203. ** leaf nodes are written in to the %_segments table in order, this
  111204. ** merge traverses the underlying sqlite disk structures efficiently.
  111205. ** After the merge, all segment blocks from the merged level are
  111206. ** deleted.
  111207. **
  111208. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  111209. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  111210. ** very similar performance numbers to 16 on insertion, though they're
  111211. ** a tiny bit slower (perhaps due to more overhead in merge-time
  111212. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  111213. ** 16, 2 about 66% slower than 16.
  111214. **
  111215. ** At query time, high MERGE_COUNT increases the number of segments
  111216. ** which need to be scanned and merged. For instance, with 100k docs
  111217. ** inserted:
  111218. **
  111219. ** MERGE_COUNT segments
  111220. ** 16 25
  111221. ** 8 12
  111222. ** 4 10
  111223. ** 2 6
  111224. **
  111225. ** This appears to have only a moderate impact on queries for very
  111226. ** frequent terms (which are somewhat dominated by segment merge
  111227. ** costs), and infrequent and non-existent terms still seem to be fast
  111228. ** even with many segments.
  111229. **
  111230. ** TODO(shess) That said, it would be nice to have a better query-side
  111231. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  111232. ** optimizations to things like doclist merging will swing the sweet
  111233. ** spot around.
  111234. **
  111235. **
  111236. **
  111237. **** Handling of deletions and updates ****
  111238. ** Since we're using a segmented structure, with no docid-oriented
  111239. ** index into the term index, we clearly cannot simply update the term
  111240. ** index when a document is deleted or updated. For deletions, we
  111241. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  111242. ** we simply write the new doclist. Segment merges overwrite older
  111243. ** data for a particular docid with newer data, so deletes or updates
  111244. ** will eventually overtake the earlier data and knock it out. The
  111245. ** query logic likewise merges doclists so that newer data knocks out
  111246. ** older data.
  111247. */
  111248. /************** Include fts3Int.h in the middle of fts3.c ********************/
  111249. /************** Begin file fts3Int.h *****************************************/
  111250. /*
  111251. ** 2009 Nov 12
  111252. **
  111253. ** The author disclaims copyright to this source code. In place of
  111254. ** a legal notice, here is a blessing:
  111255. **
  111256. ** May you do good and not evil.
  111257. ** May you find forgiveness for yourself and forgive others.
  111258. ** May you share freely, never taking more than you give.
  111259. **
  111260. ******************************************************************************
  111261. **
  111262. */
  111263. #ifndef _FTSINT_H
  111264. #define _FTSINT_H
  111265. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  111266. # define NDEBUG 1
  111267. #endif
  111268. /*
  111269. ** FTS4 is really an extension for FTS3. It is enabled using the
  111270. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  111271. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  111272. */
  111273. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  111274. # define SQLITE_ENABLE_FTS3
  111275. #endif
  111276. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  111277. /* If not building as part of the core, include sqlite3ext.h. */
  111278. #ifndef SQLITE_CORE
  111279. SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
  111280. #endif
  111281. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  111282. /************** Begin file fts3_tokenizer.h **********************************/
  111283. /*
  111284. ** 2006 July 10
  111285. **
  111286. ** The author disclaims copyright to this source code.
  111287. **
  111288. *************************************************************************
  111289. ** Defines the interface to tokenizers used by fulltext-search. There
  111290. ** are three basic components:
  111291. **
  111292. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  111293. ** interface functions. This is essentially the class structure for
  111294. ** tokenizers.
  111295. **
  111296. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  111297. ** including customization information defined at creation time.
  111298. **
  111299. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  111300. ** tokens from a particular input.
  111301. */
  111302. #ifndef _FTS3_TOKENIZER_H_
  111303. #define _FTS3_TOKENIZER_H_
  111304. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  111305. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  111306. ** we will need a way to register the API consistently.
  111307. */
  111308. /*
  111309. ** Structures used by the tokenizer interface. When a new tokenizer
  111310. ** implementation is registered, the caller provides a pointer to
  111311. ** an sqlite3_tokenizer_module containing pointers to the callback
  111312. ** functions that make up an implementation.
  111313. **
  111314. ** When an fts3 table is created, it passes any arguments passed to
  111315. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  111316. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  111317. ** implementation. The xCreate() function in turn returns an
  111318. ** sqlite3_tokenizer structure representing the specific tokenizer to
  111319. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  111320. **
  111321. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  111322. ** method is called. It returns an sqlite3_tokenizer_cursor object
  111323. ** that may be used to tokenize a specific input buffer based on
  111324. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  111325. ** object.
  111326. */
  111327. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  111328. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  111329. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  111330. struct sqlite3_tokenizer_module {
  111331. /*
  111332. ** Structure version. Should always be set to 0 or 1.
  111333. */
  111334. int iVersion;
  111335. /*
  111336. ** Create a new tokenizer. The values in the argv[] array are the
  111337. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  111338. ** TABLE statement that created the fts3 table. For example, if
  111339. ** the following SQL is executed:
  111340. **
  111341. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  111342. **
  111343. ** then argc is set to 2, and the argv[] array contains pointers
  111344. ** to the strings "arg1" and "arg2".
  111345. **
  111346. ** This method should return either SQLITE_OK (0), or an SQLite error
  111347. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  111348. ** to point at the newly created tokenizer structure. The generic
  111349. ** sqlite3_tokenizer.pModule variable should not be initialized by
  111350. ** this callback. The caller will do so.
  111351. */
  111352. int (*xCreate)(
  111353. int argc, /* Size of argv array */
  111354. const char *const*argv, /* Tokenizer argument strings */
  111355. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  111356. );
  111357. /*
  111358. ** Destroy an existing tokenizer. The fts3 module calls this method
  111359. ** exactly once for each successful call to xCreate().
  111360. */
  111361. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  111362. /*
  111363. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  111364. ** is responsible for ensuring that the input buffer remains valid
  111365. ** until the cursor is closed (using the xClose() method).
  111366. */
  111367. int (*xOpen)(
  111368. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  111369. const char *pInput, int nBytes, /* Input buffer */
  111370. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  111371. );
  111372. /*
  111373. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  111374. ** method exactly once for each successful call to xOpen().
  111375. */
  111376. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  111377. /*
  111378. ** Retrieve the next token from the tokenizer cursor pCursor. This
  111379. ** method should either return SQLITE_OK and set the values of the
  111380. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  111381. ** the end of the buffer has been reached, or an SQLite error code.
  111382. **
  111383. ** *ppToken should be set to point at a buffer containing the
  111384. ** normalized version of the token (i.e. after any case-folding and/or
  111385. ** stemming has been performed). *pnBytes should be set to the length
  111386. ** of this buffer in bytes. The input text that generated the token is
  111387. ** identified by the byte offsets returned in *piStartOffset and
  111388. ** *piEndOffset. *piStartOffset should be set to the index of the first
  111389. ** byte of the token in the input buffer. *piEndOffset should be set
  111390. ** to the index of the first byte just past the end of the token in
  111391. ** the input buffer.
  111392. **
  111393. ** The buffer *ppToken is set to point at is managed by the tokenizer
  111394. ** implementation. It is only required to be valid until the next call
  111395. ** to xNext() or xClose().
  111396. */
  111397. /* TODO(shess) current implementation requires pInput to be
  111398. ** nul-terminated. This should either be fixed, or pInput/nBytes
  111399. ** should be converted to zInput.
  111400. */
  111401. int (*xNext)(
  111402. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  111403. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  111404. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  111405. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  111406. int *piPosition /* OUT: Number of tokens returned before this one */
  111407. );
  111408. /***********************************************************************
  111409. ** Methods below this point are only available if iVersion>=1.
  111410. */
  111411. /*
  111412. ** Configure the language id of a tokenizer cursor.
  111413. */
  111414. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  111415. };
  111416. struct sqlite3_tokenizer {
  111417. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  111418. /* Tokenizer implementations will typically add additional fields */
  111419. };
  111420. struct sqlite3_tokenizer_cursor {
  111421. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  111422. /* Tokenizer implementations will typically add additional fields */
  111423. };
  111424. int fts3_global_term_cnt(int iTerm, int iCol);
  111425. int fts3_term_cnt(int iTerm, int iCol);
  111426. #endif /* _FTS3_TOKENIZER_H_ */
  111427. /************** End of fts3_tokenizer.h **************************************/
  111428. /************** Continuing where we left off in fts3Int.h ********************/
  111429. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  111430. /************** Begin file fts3_hash.h ***************************************/
  111431. /*
  111432. ** 2001 September 22
  111433. **
  111434. ** The author disclaims copyright to this source code. In place of
  111435. ** a legal notice, here is a blessing:
  111436. **
  111437. ** May you do good and not evil.
  111438. ** May you find forgiveness for yourself and forgive others.
  111439. ** May you share freely, never taking more than you give.
  111440. **
  111441. *************************************************************************
  111442. ** This is the header file for the generic hash-table implementation
  111443. ** used in SQLite. We've modified it slightly to serve as a standalone
  111444. ** hash table implementation for the full-text indexing module.
  111445. **
  111446. */
  111447. #ifndef _FTS3_HASH_H_
  111448. #define _FTS3_HASH_H_
  111449. /* Forward declarations of structures. */
  111450. typedef struct Fts3Hash Fts3Hash;
  111451. typedef struct Fts3HashElem Fts3HashElem;
  111452. /* A complete hash table is an instance of the following structure.
  111453. ** The internals of this structure are intended to be opaque -- client
  111454. ** code should not attempt to access or modify the fields of this structure
  111455. ** directly. Change this structure only by using the routines below.
  111456. ** However, many of the "procedures" and "functions" for modifying and
  111457. ** accessing this structure are really macros, so we can't really make
  111458. ** this structure opaque.
  111459. */
  111460. struct Fts3Hash {
  111461. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  111462. char copyKey; /* True if copy of key made on insert */
  111463. int count; /* Number of entries in this table */
  111464. Fts3HashElem *first; /* The first element of the array */
  111465. int htsize; /* Number of buckets in the hash table */
  111466. struct _fts3ht { /* the hash table */
  111467. int count; /* Number of entries with this hash */
  111468. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  111469. } *ht;
  111470. };
  111471. /* Each element in the hash table is an instance of the following
  111472. ** structure. All elements are stored on a single doubly-linked list.
  111473. **
  111474. ** Again, this structure is intended to be opaque, but it can't really
  111475. ** be opaque because it is used by macros.
  111476. */
  111477. struct Fts3HashElem {
  111478. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  111479. void *data; /* Data associated with this element */
  111480. void *pKey; int nKey; /* Key associated with this element */
  111481. };
  111482. /*
  111483. ** There are 2 different modes of operation for a hash table:
  111484. **
  111485. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  111486. ** (including the null-terminator, if any). Case
  111487. ** is respected in comparisons.
  111488. **
  111489. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  111490. ** memcmp() is used to compare keys.
  111491. **
  111492. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  111493. */
  111494. #define FTS3_HASH_STRING 1
  111495. #define FTS3_HASH_BINARY 2
  111496. /*
  111497. ** Access routines. To delete, insert a NULL pointer.
  111498. */
  111499. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  111500. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  111501. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  111502. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  111503. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  111504. /*
  111505. ** Shorthand for the functions above
  111506. */
  111507. #define fts3HashInit sqlite3Fts3HashInit
  111508. #define fts3HashInsert sqlite3Fts3HashInsert
  111509. #define fts3HashFind sqlite3Fts3HashFind
  111510. #define fts3HashClear sqlite3Fts3HashClear
  111511. #define fts3HashFindElem sqlite3Fts3HashFindElem
  111512. /*
  111513. ** Macros for looping over all elements of a hash table. The idiom is
  111514. ** like this:
  111515. **
  111516. ** Fts3Hash h;
  111517. ** Fts3HashElem *p;
  111518. ** ...
  111519. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  111520. ** SomeStructure *pData = fts3HashData(p);
  111521. ** // do something with pData
  111522. ** }
  111523. */
  111524. #define fts3HashFirst(H) ((H)->first)
  111525. #define fts3HashNext(E) ((E)->next)
  111526. #define fts3HashData(E) ((E)->data)
  111527. #define fts3HashKey(E) ((E)->pKey)
  111528. #define fts3HashKeysize(E) ((E)->nKey)
  111529. /*
  111530. ** Number of entries in a hash table
  111531. */
  111532. #define fts3HashCount(H) ((H)->count)
  111533. #endif /* _FTS3_HASH_H_ */
  111534. /************** End of fts3_hash.h *******************************************/
  111535. /************** Continuing where we left off in fts3Int.h ********************/
  111536. /*
  111537. ** This constant controls how often segments are merged. Once there are
  111538. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  111539. ** segment of level N+1.
  111540. */
  111541. #define FTS3_MERGE_COUNT 16
  111542. /*
  111543. ** This is the maximum amount of data (in bytes) to store in the
  111544. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  111545. ** populated as documents are inserted/updated/deleted in a transaction
  111546. ** and used to create a new segment when the transaction is committed.
  111547. ** However if this limit is reached midway through a transaction, a new
  111548. ** segment is created and the hash table cleared immediately.
  111549. */
  111550. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  111551. /*
  111552. ** Macro to return the number of elements in an array. SQLite has a
  111553. ** similar macro called ArraySize(). Use a different name to avoid
  111554. ** a collision when building an amalgamation with built-in FTS3.
  111555. */
  111556. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  111557. #ifndef MIN
  111558. # define MIN(x,y) ((x)<(y)?(x):(y))
  111559. #endif
  111560. #ifndef MAX
  111561. # define MAX(x,y) ((x)>(y)?(x):(y))
  111562. #endif
  111563. /*
  111564. ** Maximum length of a varint encoded integer. The varint format is different
  111565. ** from that used by SQLite, so the maximum length is 10, not 9.
  111566. */
  111567. #define FTS3_VARINT_MAX 10
  111568. /*
  111569. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  111570. ** in the document set and zero or more prefix indexes. All indexes are stored
  111571. ** as one or more b+-trees in the %_segments and %_segdir tables.
  111572. **
  111573. ** It is possible to determine which index a b+-tree belongs to based on the
  111574. ** value stored in the "%_segdir.level" column. Given this value L, the index
  111575. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  111576. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  111577. ** between 1024 and 2047 to index 1, and so on.
  111578. **
  111579. ** It is considered impossible for an index to use more than 1024 levels. In
  111580. ** theory though this may happen, but only after at least
  111581. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  111582. */
  111583. #define FTS3_SEGDIR_MAXLEVEL 1024
  111584. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  111585. /*
  111586. ** The testcase() macro is only used by the amalgamation. If undefined,
  111587. ** make it a no-op.
  111588. */
  111589. #ifndef testcase
  111590. # define testcase(X)
  111591. #endif
  111592. /*
  111593. ** Terminator values for position-lists and column-lists.
  111594. */
  111595. #define POS_COLUMN (1) /* Column-list terminator */
  111596. #define POS_END (0) /* Position-list terminator */
  111597. /*
  111598. ** This section provides definitions to allow the
  111599. ** FTS3 extension to be compiled outside of the
  111600. ** amalgamation.
  111601. */
  111602. #ifndef SQLITE_AMALGAMATION
  111603. /*
  111604. ** Macros indicating that conditional expressions are always true or
  111605. ** false.
  111606. */
  111607. #ifdef SQLITE_COVERAGE_TEST
  111608. # define ALWAYS(x) (1)
  111609. # define NEVER(X) (0)
  111610. #else
  111611. # define ALWAYS(x) (x)
  111612. # define NEVER(x) (x)
  111613. #endif
  111614. /*
  111615. ** Internal types used by SQLite.
  111616. */
  111617. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  111618. typedef short int i16; /* 2-byte (or larger) signed integer */
  111619. typedef unsigned int u32; /* 4-byte unsigned integer */
  111620. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  111621. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  111622. /*
  111623. ** Macro used to suppress compiler warnings for unused parameters.
  111624. */
  111625. #define UNUSED_PARAMETER(x) (void)(x)
  111626. /*
  111627. ** Activate assert() only if SQLITE_TEST is enabled.
  111628. */
  111629. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  111630. # define NDEBUG 1
  111631. #endif
  111632. /*
  111633. ** The TESTONLY macro is used to enclose variable declarations or
  111634. ** other bits of code that are needed to support the arguments
  111635. ** within testcase() and assert() macros.
  111636. */
  111637. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  111638. # define TESTONLY(X) X
  111639. #else
  111640. # define TESTONLY(X)
  111641. #endif
  111642. #endif /* SQLITE_AMALGAMATION */
  111643. #ifdef SQLITE_DEBUG
  111644. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  111645. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  111646. #else
  111647. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  111648. #endif
  111649. typedef struct Fts3Table Fts3Table;
  111650. typedef struct Fts3Cursor Fts3Cursor;
  111651. typedef struct Fts3Expr Fts3Expr;
  111652. typedef struct Fts3Phrase Fts3Phrase;
  111653. typedef struct Fts3PhraseToken Fts3PhraseToken;
  111654. typedef struct Fts3Doclist Fts3Doclist;
  111655. typedef struct Fts3SegFilter Fts3SegFilter;
  111656. typedef struct Fts3DeferredToken Fts3DeferredToken;
  111657. typedef struct Fts3SegReader Fts3SegReader;
  111658. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  111659. /*
  111660. ** A connection to a fulltext index is an instance of the following
  111661. ** structure. The xCreate and xConnect methods create an instance
  111662. ** of this structure and xDestroy and xDisconnect free that instance.
  111663. ** All other methods receive a pointer to the structure as one of their
  111664. ** arguments.
  111665. */
  111666. struct Fts3Table {
  111667. sqlite3_vtab base; /* Base class used by SQLite core */
  111668. sqlite3 *db; /* The database connection */
  111669. const char *zDb; /* logical database name */
  111670. const char *zName; /* virtual table name */
  111671. int nColumn; /* number of named columns in virtual table */
  111672. char **azColumn; /* column names. malloced */
  111673. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  111674. char *zContentTbl; /* content=xxx option, or NULL */
  111675. char *zLanguageid; /* languageid=xxx option, or NULL */
  111676. u8 bAutoincrmerge; /* True if automerge=1 */
  111677. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  111678. /* Precompiled statements used by the implementation. Each of these
  111679. ** statements is run and reset within a single virtual table API call.
  111680. */
  111681. sqlite3_stmt *aStmt[37];
  111682. char *zReadExprlist;
  111683. char *zWriteExprlist;
  111684. int nNodeSize; /* Soft limit for node size */
  111685. u8 bFts4; /* True for FTS4, false for FTS3 */
  111686. u8 bHasStat; /* True if %_stat table exists */
  111687. u8 bHasDocsize; /* True if %_docsize table exists */
  111688. u8 bDescIdx; /* True if doclists are in reverse order */
  111689. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  111690. int nPgsz; /* Page size for host database */
  111691. char *zSegmentsTbl; /* Name of %_segments table */
  111692. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  111693. /*
  111694. ** The following array of hash tables is used to buffer pending index
  111695. ** updates during transactions. All pending updates buffered at any one
  111696. ** time must share a common language-id (see the FTS4 langid= feature).
  111697. ** The current language id is stored in variable iPrevLangid.
  111698. **
  111699. ** A single FTS4 table may have multiple full-text indexes. For each index
  111700. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  111701. ** terms that appear in the document set. Each subsequent index in aIndex[]
  111702. ** is an index of prefixes of a specific length.
  111703. **
  111704. ** Variable nPendingData contains an estimate the memory consumed by the
  111705. ** pending data structures, including hash table overhead, but not including
  111706. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  111707. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  111708. ** recently inserted record.
  111709. */
  111710. int nIndex; /* Size of aIndex[] */
  111711. struct Fts3Index {
  111712. int nPrefix; /* Prefix length (0 for main terms index) */
  111713. Fts3Hash hPending; /* Pending terms table for this index */
  111714. } *aIndex;
  111715. int nMaxPendingData; /* Max pending data before flush to disk */
  111716. int nPendingData; /* Current bytes of pending data */
  111717. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  111718. int iPrevLangid; /* Langid of recently inserted document */
  111719. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  111720. /* State variables used for validating that the transaction control
  111721. ** methods of the virtual table are called at appropriate times. These
  111722. ** values do not contribute to FTS functionality; they are used for
  111723. ** verifying the operation of the SQLite core.
  111724. */
  111725. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  111726. int mxSavepoint; /* Largest valid xSavepoint integer */
  111727. #endif
  111728. };
  111729. /*
  111730. ** When the core wants to read from the virtual table, it creates a
  111731. ** virtual table cursor (an instance of the following structure) using
  111732. ** the xOpen method. Cursors are destroyed using the xClose method.
  111733. */
  111734. struct Fts3Cursor {
  111735. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  111736. i16 eSearch; /* Search strategy (see below) */
  111737. u8 isEof; /* True if at End Of Results */
  111738. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  111739. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  111740. Fts3Expr *pExpr; /* Parsed MATCH query string */
  111741. int iLangid; /* Language being queried for */
  111742. int nPhrase; /* Number of matchable phrases in query */
  111743. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  111744. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  111745. char *pNextId; /* Pointer into the body of aDoclist */
  111746. char *aDoclist; /* List of docids for full-text queries */
  111747. int nDoclist; /* Size of buffer at aDoclist */
  111748. u8 bDesc; /* True to sort in descending order */
  111749. int eEvalmode; /* An FTS3_EVAL_XX constant */
  111750. int nRowAvg; /* Average size of database rows, in pages */
  111751. sqlite3_int64 nDoc; /* Documents in table */
  111752. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  111753. u32 *aMatchinfo; /* Information about most recent match */
  111754. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  111755. char *zMatchinfo; /* Matchinfo specification */
  111756. };
  111757. #define FTS3_EVAL_FILTER 0
  111758. #define FTS3_EVAL_NEXT 1
  111759. #define FTS3_EVAL_MATCHINFO 2
  111760. /*
  111761. ** The Fts3Cursor.eSearch member is always set to one of the following.
  111762. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  111763. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  111764. ** of the column to be searched. For example, in
  111765. **
  111766. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  111767. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  111768. **
  111769. ** Because the LHS of the MATCH operator is 2nd column "b",
  111770. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  111771. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  111772. ** indicating that all columns should be searched,
  111773. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  111774. */
  111775. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  111776. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  111777. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  111778. struct Fts3Doclist {
  111779. char *aAll; /* Array containing doclist (or NULL) */
  111780. int nAll; /* Size of a[] in bytes */
  111781. char *pNextDocid; /* Pointer to next docid */
  111782. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  111783. int bFreeList; /* True if pList should be sqlite3_free()d */
  111784. char *pList; /* Pointer to position list following iDocid */
  111785. int nList; /* Length of position list */
  111786. };
  111787. /*
  111788. ** A "phrase" is a sequence of one or more tokens that must match in
  111789. ** sequence. A single token is the base case and the most common case.
  111790. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  111791. ** nToken will be the number of tokens in the string.
  111792. */
  111793. struct Fts3PhraseToken {
  111794. char *z; /* Text of the token */
  111795. int n; /* Number of bytes in buffer z */
  111796. int isPrefix; /* True if token ends with a "*" character */
  111797. int bFirst; /* True if token must appear at position 0 */
  111798. /* Variables above this point are populated when the expression is
  111799. ** parsed (by code in fts3_expr.c). Below this point the variables are
  111800. ** used when evaluating the expression. */
  111801. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  111802. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  111803. };
  111804. struct Fts3Phrase {
  111805. /* Cache of doclist for this phrase. */
  111806. Fts3Doclist doclist;
  111807. int bIncr; /* True if doclist is loaded incrementally */
  111808. int iDoclistToken;
  111809. /* Variables below this point are populated by fts3_expr.c when parsing
  111810. ** a MATCH expression. Everything above is part of the evaluation phase.
  111811. */
  111812. int nToken; /* Number of tokens in the phrase */
  111813. int iColumn; /* Index of column this phrase must match */
  111814. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  111815. };
  111816. /*
  111817. ** A tree of these objects forms the RHS of a MATCH operator.
  111818. **
  111819. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  111820. ** points to a malloced buffer, size nDoclist bytes, containing the results
  111821. ** of this phrase query in FTS3 doclist format. As usual, the initial
  111822. ** "Length" field found in doclists stored on disk is omitted from this
  111823. ** buffer.
  111824. **
  111825. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  111826. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  111827. ** where nCol is the number of columns in the queried FTS table. The array
  111828. ** is populated as follows:
  111829. **
  111830. ** aMI[iCol*3 + 0] = Undefined
  111831. ** aMI[iCol*3 + 1] = Number of occurrences
  111832. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  111833. **
  111834. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  111835. ** when the expression node is.
  111836. */
  111837. struct Fts3Expr {
  111838. int eType; /* One of the FTSQUERY_XXX values defined below */
  111839. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  111840. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  111841. Fts3Expr *pLeft; /* Left operand */
  111842. Fts3Expr *pRight; /* Right operand */
  111843. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  111844. /* The following are used by the fts3_eval.c module. */
  111845. sqlite3_int64 iDocid; /* Current docid */
  111846. u8 bEof; /* True this expression is at EOF already */
  111847. u8 bStart; /* True if iDocid is valid */
  111848. u8 bDeferred; /* True if this expression is entirely deferred */
  111849. u32 *aMI;
  111850. };
  111851. /*
  111852. ** Candidate values for Fts3Query.eType. Note that the order of the first
  111853. ** four values is in order of precedence when parsing expressions. For
  111854. ** example, the following:
  111855. **
  111856. ** "a OR b AND c NOT d NEAR e"
  111857. **
  111858. ** is equivalent to:
  111859. **
  111860. ** "a OR (b AND (c NOT (d NEAR e)))"
  111861. */
  111862. #define FTSQUERY_NEAR 1
  111863. #define FTSQUERY_NOT 2
  111864. #define FTSQUERY_AND 3
  111865. #define FTSQUERY_OR 4
  111866. #define FTSQUERY_PHRASE 5
  111867. /* fts3_write.c */
  111868. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  111869. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  111870. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  111871. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  111872. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  111873. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  111874. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  111875. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  111876. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  111877. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  111878. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
  111879. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  111880. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  111881. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  111882. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  111883. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  111884. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  111885. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  111886. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  111887. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  111888. #else
  111889. # define sqlite3Fts3FreeDeferredTokens(x)
  111890. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  111891. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  111892. # define sqlite3Fts3FreeDeferredDoclists(x)
  111893. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  111894. #endif
  111895. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  111896. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  111897. /* Special values interpreted by sqlite3SegReaderCursor() */
  111898. #define FTS3_SEGCURSOR_PENDING -1
  111899. #define FTS3_SEGCURSOR_ALL -2
  111900. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  111901. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  111902. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  111903. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  111904. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  111905. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  111906. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  111907. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  111908. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  111909. #define FTS3_SEGMENT_PREFIX 0x00000008
  111910. #define FTS3_SEGMENT_SCAN 0x00000010
  111911. #define FTS3_SEGMENT_FIRST 0x00000020
  111912. /* Type passed as 4th argument to SegmentReaderIterate() */
  111913. struct Fts3SegFilter {
  111914. const char *zTerm;
  111915. int nTerm;
  111916. int iCol;
  111917. int flags;
  111918. };
  111919. struct Fts3MultiSegReader {
  111920. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  111921. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  111922. int nSegment; /* Size of apSegment array */
  111923. int nAdvance; /* How many seg-readers to advance */
  111924. Fts3SegFilter *pFilter; /* Pointer to filter object */
  111925. char *aBuffer; /* Buffer to merge doclists in */
  111926. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  111927. int iColFilter; /* If >=0, filter for this column */
  111928. int bRestart;
  111929. /* Used by fts3.c only. */
  111930. int nCost; /* Cost of running iterator */
  111931. int bLookup; /* True if a lookup of a single entry. */
  111932. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  111933. char *zTerm; /* Pointer to term buffer */
  111934. int nTerm; /* Size of zTerm in bytes */
  111935. char *aDoclist; /* Pointer to doclist buffer */
  111936. int nDoclist; /* Size of aDoclist[] in bytes */
  111937. };
  111938. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  111939. /* fts3.c */
  111940. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  111941. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  111942. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  111943. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  111944. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  111945. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  111946. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  111947. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  111948. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  111949. /* fts3_tokenizer.c */
  111950. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  111951. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  111952. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  111953. sqlite3_tokenizer **, char **
  111954. );
  111955. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  111956. /* fts3_snippet.c */
  111957. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  111958. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  111959. const char *, const char *, int, int
  111960. );
  111961. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  111962. /* fts3_expr.c */
  111963. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  111964. char **, int, int, int, const char *, int, Fts3Expr **, char **
  111965. );
  111966. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  111967. #ifdef SQLITE_TEST
  111968. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  111969. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  111970. #endif
  111971. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  111972. sqlite3_tokenizer_cursor **
  111973. );
  111974. /* fts3_aux.c */
  111975. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  111976. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  111977. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  111978. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  111979. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  111980. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  111981. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  111982. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  111983. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  111984. /* fts3_tokenize_vtab.c */
  111985. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  111986. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  111987. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  111988. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  111989. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  111990. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  111991. #endif
  111992. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  111993. #endif /* _FTSINT_H */
  111994. /************** End of fts3Int.h *********************************************/
  111995. /************** Continuing where we left off in fts3.c ***********************/
  111996. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  111997. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  111998. # define SQLITE_CORE 1
  111999. #endif
  112000. /* #include <assert.h> */
  112001. /* #include <stdlib.h> */
  112002. /* #include <stddef.h> */
  112003. /* #include <stdio.h> */
  112004. /* #include <string.h> */
  112005. /* #include <stdarg.h> */
  112006. #ifndef SQLITE_CORE
  112007. SQLITE_EXTENSION_INIT1
  112008. #endif
  112009. static int fts3EvalNext(Fts3Cursor *pCsr);
  112010. static int fts3EvalStart(Fts3Cursor *pCsr);
  112011. static int fts3TermSegReaderCursor(
  112012. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  112013. /*
  112014. ** Write a 64-bit variable-length integer to memory starting at p[0].
  112015. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  112016. ** The number of bytes written is returned.
  112017. */
  112018. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  112019. unsigned char *q = (unsigned char *) p;
  112020. sqlite_uint64 vu = v;
  112021. do{
  112022. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  112023. vu >>= 7;
  112024. }while( vu!=0 );
  112025. q[-1] &= 0x7f; /* turn off high bit in final byte */
  112026. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  112027. return (int) (q - (unsigned char *)p);
  112028. }
  112029. /*
  112030. ** Read a 64-bit variable-length integer from memory starting at p[0].
  112031. ** Return the number of bytes read, or 0 on error.
  112032. ** The value is stored in *v.
  112033. */
  112034. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  112035. const unsigned char *q = (const unsigned char *) p;
  112036. sqlite_uint64 x = 0, y = 1;
  112037. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  112038. x += y * (*q++ & 0x7f);
  112039. y <<= 7;
  112040. }
  112041. x += y * (*q++);
  112042. *v = (sqlite_int64) x;
  112043. return (int) (q - (unsigned char *)p);
  112044. }
  112045. /*
  112046. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  112047. ** 32-bit integer before it is returned.
  112048. */
  112049. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  112050. sqlite_int64 i;
  112051. int ret = sqlite3Fts3GetVarint(p, &i);
  112052. *pi = (int) i;
  112053. return ret;
  112054. }
  112055. /*
  112056. ** Return the number of bytes required to encode v as a varint
  112057. */
  112058. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  112059. int i = 0;
  112060. do{
  112061. i++;
  112062. v >>= 7;
  112063. }while( v!=0 );
  112064. return i;
  112065. }
  112066. /*
  112067. ** Convert an SQL-style quoted string into a normal string by removing
  112068. ** the quote characters. The conversion is done in-place. If the
  112069. ** input does not begin with a quote character, then this routine
  112070. ** is a no-op.
  112071. **
  112072. ** Examples:
  112073. **
  112074. ** "abc" becomes abc
  112075. ** 'xyz' becomes xyz
  112076. ** [pqr] becomes pqr
  112077. ** `mno` becomes mno
  112078. **
  112079. */
  112080. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  112081. char quote; /* Quote character (if any ) */
  112082. quote = z[0];
  112083. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  112084. int iIn = 1; /* Index of next byte to read from input */
  112085. int iOut = 0; /* Index of next byte to write to output */
  112086. /* If the first byte was a '[', then the close-quote character is a ']' */
  112087. if( quote=='[' ) quote = ']';
  112088. while( ALWAYS(z[iIn]) ){
  112089. if( z[iIn]==quote ){
  112090. if( z[iIn+1]!=quote ) break;
  112091. z[iOut++] = quote;
  112092. iIn += 2;
  112093. }else{
  112094. z[iOut++] = z[iIn++];
  112095. }
  112096. }
  112097. z[iOut] = '\0';
  112098. }
  112099. }
  112100. /*
  112101. ** Read a single varint from the doclist at *pp and advance *pp to point
  112102. ** to the first byte past the end of the varint. Add the value of the varint
  112103. ** to *pVal.
  112104. */
  112105. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  112106. sqlite3_int64 iVal;
  112107. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  112108. *pVal += iVal;
  112109. }
  112110. /*
  112111. ** When this function is called, *pp points to the first byte following a
  112112. ** varint that is part of a doclist (or position-list, or any other list
  112113. ** of varints). This function moves *pp to point to the start of that varint,
  112114. ** and sets *pVal by the varint value.
  112115. **
  112116. ** Argument pStart points to the first byte of the doclist that the
  112117. ** varint is part of.
  112118. */
  112119. static void fts3GetReverseVarint(
  112120. char **pp,
  112121. char *pStart,
  112122. sqlite3_int64 *pVal
  112123. ){
  112124. sqlite3_int64 iVal;
  112125. char *p;
  112126. /* Pointer p now points at the first byte past the varint we are
  112127. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  112128. ** clear on character p[-1]. */
  112129. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  112130. p++;
  112131. *pp = p;
  112132. sqlite3Fts3GetVarint(p, &iVal);
  112133. *pVal = iVal;
  112134. }
  112135. /*
  112136. ** The xDisconnect() virtual table method.
  112137. */
  112138. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  112139. Fts3Table *p = (Fts3Table *)pVtab;
  112140. int i;
  112141. assert( p->nPendingData==0 );
  112142. assert( p->pSegments==0 );
  112143. /* Free any prepared statements held */
  112144. for(i=0; i<SizeofArray(p->aStmt); i++){
  112145. sqlite3_finalize(p->aStmt[i]);
  112146. }
  112147. sqlite3_free(p->zSegmentsTbl);
  112148. sqlite3_free(p->zReadExprlist);
  112149. sqlite3_free(p->zWriteExprlist);
  112150. sqlite3_free(p->zContentTbl);
  112151. sqlite3_free(p->zLanguageid);
  112152. /* Invoke the tokenizer destructor to free the tokenizer. */
  112153. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  112154. sqlite3_free(p);
  112155. return SQLITE_OK;
  112156. }
  112157. /*
  112158. ** Construct one or more SQL statements from the format string given
  112159. ** and then evaluate those statements. The success code is written
  112160. ** into *pRc.
  112161. **
  112162. ** If *pRc is initially non-zero then this routine is a no-op.
  112163. */
  112164. static void fts3DbExec(
  112165. int *pRc, /* Success code */
  112166. sqlite3 *db, /* Database in which to run SQL */
  112167. const char *zFormat, /* Format string for SQL */
  112168. ... /* Arguments to the format string */
  112169. ){
  112170. va_list ap;
  112171. char *zSql;
  112172. if( *pRc ) return;
  112173. va_start(ap, zFormat);
  112174. zSql = sqlite3_vmprintf(zFormat, ap);
  112175. va_end(ap);
  112176. if( zSql==0 ){
  112177. *pRc = SQLITE_NOMEM;
  112178. }else{
  112179. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  112180. sqlite3_free(zSql);
  112181. }
  112182. }
  112183. /*
  112184. ** The xDestroy() virtual table method.
  112185. */
  112186. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  112187. Fts3Table *p = (Fts3Table *)pVtab;
  112188. int rc = SQLITE_OK; /* Return code */
  112189. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  112190. sqlite3 *db = p->db; /* Database handle */
  112191. /* Drop the shadow tables */
  112192. if( p->zContentTbl==0 ){
  112193. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  112194. }
  112195. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  112196. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  112197. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  112198. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  112199. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  112200. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  112201. ** Otherwise, return an SQLite error code.
  112202. */
  112203. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  112204. }
  112205. /*
  112206. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  112207. ** passed as the first argument. This is done as part of the xConnect()
  112208. ** and xCreate() methods.
  112209. **
  112210. ** If *pRc is non-zero when this function is called, it is a no-op.
  112211. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  112212. ** before returning.
  112213. */
  112214. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  112215. if( *pRc==SQLITE_OK ){
  112216. int i; /* Iterator variable */
  112217. int rc; /* Return code */
  112218. char *zSql; /* SQL statement passed to declare_vtab() */
  112219. char *zCols; /* List of user defined columns */
  112220. const char *zLanguageid;
  112221. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  112222. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  112223. /* Create a list of user columns for the virtual table */
  112224. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  112225. for(i=1; zCols && i<p->nColumn; i++){
  112226. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  112227. }
  112228. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  112229. zSql = sqlite3_mprintf(
  112230. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  112231. zCols, p->zName, zLanguageid
  112232. );
  112233. if( !zCols || !zSql ){
  112234. rc = SQLITE_NOMEM;
  112235. }else{
  112236. rc = sqlite3_declare_vtab(p->db, zSql);
  112237. }
  112238. sqlite3_free(zSql);
  112239. sqlite3_free(zCols);
  112240. *pRc = rc;
  112241. }
  112242. }
  112243. /*
  112244. ** Create the %_stat table if it does not already exist.
  112245. */
  112246. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  112247. fts3DbExec(pRc, p->db,
  112248. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  112249. "(id INTEGER PRIMARY KEY, value BLOB);",
  112250. p->zDb, p->zName
  112251. );
  112252. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  112253. }
  112254. /*
  112255. ** Create the backing store tables (%_content, %_segments and %_segdir)
  112256. ** required by the FTS3 table passed as the only argument. This is done
  112257. ** as part of the vtab xCreate() method.
  112258. **
  112259. ** If the p->bHasDocsize boolean is true (indicating that this is an
  112260. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  112261. ** %_stat tables required by FTS4.
  112262. */
  112263. static int fts3CreateTables(Fts3Table *p){
  112264. int rc = SQLITE_OK; /* Return code */
  112265. int i; /* Iterator variable */
  112266. sqlite3 *db = p->db; /* The database connection */
  112267. if( p->zContentTbl==0 ){
  112268. const char *zLanguageid = p->zLanguageid;
  112269. char *zContentCols; /* Columns of %_content table */
  112270. /* Create a list of user columns for the content table */
  112271. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  112272. for(i=0; zContentCols && i<p->nColumn; i++){
  112273. char *z = p->azColumn[i];
  112274. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  112275. }
  112276. if( zLanguageid && zContentCols ){
  112277. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  112278. }
  112279. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  112280. /* Create the content table */
  112281. fts3DbExec(&rc, db,
  112282. "CREATE TABLE %Q.'%q_content'(%s)",
  112283. p->zDb, p->zName, zContentCols
  112284. );
  112285. sqlite3_free(zContentCols);
  112286. }
  112287. /* Create other tables */
  112288. fts3DbExec(&rc, db,
  112289. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  112290. p->zDb, p->zName
  112291. );
  112292. fts3DbExec(&rc, db,
  112293. "CREATE TABLE %Q.'%q_segdir'("
  112294. "level INTEGER,"
  112295. "idx INTEGER,"
  112296. "start_block INTEGER,"
  112297. "leaves_end_block INTEGER,"
  112298. "end_block INTEGER,"
  112299. "root BLOB,"
  112300. "PRIMARY KEY(level, idx)"
  112301. ");",
  112302. p->zDb, p->zName
  112303. );
  112304. if( p->bHasDocsize ){
  112305. fts3DbExec(&rc, db,
  112306. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  112307. p->zDb, p->zName
  112308. );
  112309. }
  112310. assert( p->bHasStat==p->bFts4 );
  112311. if( p->bHasStat ){
  112312. sqlite3Fts3CreateStatTable(&rc, p);
  112313. }
  112314. return rc;
  112315. }
  112316. /*
  112317. ** Store the current database page-size in bytes in p->nPgsz.
  112318. **
  112319. ** If *pRc is non-zero when this function is called, it is a no-op.
  112320. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  112321. ** before returning.
  112322. */
  112323. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  112324. if( *pRc==SQLITE_OK ){
  112325. int rc; /* Return code */
  112326. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  112327. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  112328. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  112329. if( !zSql ){
  112330. rc = SQLITE_NOMEM;
  112331. }else{
  112332. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  112333. if( rc==SQLITE_OK ){
  112334. sqlite3_step(pStmt);
  112335. p->nPgsz = sqlite3_column_int(pStmt, 0);
  112336. rc = sqlite3_finalize(pStmt);
  112337. }else if( rc==SQLITE_AUTH ){
  112338. p->nPgsz = 1024;
  112339. rc = SQLITE_OK;
  112340. }
  112341. }
  112342. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  112343. sqlite3_free(zSql);
  112344. *pRc = rc;
  112345. }
  112346. }
  112347. /*
  112348. ** "Special" FTS4 arguments are column specifications of the following form:
  112349. **
  112350. ** <key> = <value>
  112351. **
  112352. ** There may not be whitespace surrounding the "=" character. The <value>
  112353. ** term may be quoted, but the <key> may not.
  112354. */
  112355. static int fts3IsSpecialColumn(
  112356. const char *z,
  112357. int *pnKey,
  112358. char **pzValue
  112359. ){
  112360. char *zValue;
  112361. const char *zCsr = z;
  112362. while( *zCsr!='=' ){
  112363. if( *zCsr=='\0' ) return 0;
  112364. zCsr++;
  112365. }
  112366. *pnKey = (int)(zCsr-z);
  112367. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  112368. if( zValue ){
  112369. sqlite3Fts3Dequote(zValue);
  112370. }
  112371. *pzValue = zValue;
  112372. return 1;
  112373. }
  112374. /*
  112375. ** Append the output of a printf() style formatting to an existing string.
  112376. */
  112377. static void fts3Appendf(
  112378. int *pRc, /* IN/OUT: Error code */
  112379. char **pz, /* IN/OUT: Pointer to string buffer */
  112380. const char *zFormat, /* Printf format string to append */
  112381. ... /* Arguments for printf format string */
  112382. ){
  112383. if( *pRc==SQLITE_OK ){
  112384. va_list ap;
  112385. char *z;
  112386. va_start(ap, zFormat);
  112387. z = sqlite3_vmprintf(zFormat, ap);
  112388. va_end(ap);
  112389. if( z && *pz ){
  112390. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  112391. sqlite3_free(z);
  112392. z = z2;
  112393. }
  112394. if( z==0 ) *pRc = SQLITE_NOMEM;
  112395. sqlite3_free(*pz);
  112396. *pz = z;
  112397. }
  112398. }
  112399. /*
  112400. ** Return a copy of input string zInput enclosed in double-quotes (") and
  112401. ** with all double quote characters escaped. For example:
  112402. **
  112403. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  112404. **
  112405. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  112406. ** is the callers responsibility to call sqlite3_free() to release this
  112407. ** memory.
  112408. */
  112409. static char *fts3QuoteId(char const *zInput){
  112410. int nRet;
  112411. char *zRet;
  112412. nRet = 2 + (int)strlen(zInput)*2 + 1;
  112413. zRet = sqlite3_malloc(nRet);
  112414. if( zRet ){
  112415. int i;
  112416. char *z = zRet;
  112417. *(z++) = '"';
  112418. for(i=0; zInput[i]; i++){
  112419. if( zInput[i]=='"' ) *(z++) = '"';
  112420. *(z++) = zInput[i];
  112421. }
  112422. *(z++) = '"';
  112423. *(z++) = '\0';
  112424. }
  112425. return zRet;
  112426. }
  112427. /*
  112428. ** Return a list of comma separated SQL expressions and a FROM clause that
  112429. ** could be used in a SELECT statement such as the following:
  112430. **
  112431. ** SELECT <list of expressions> FROM %_content AS x ...
  112432. **
  112433. ** to return the docid, followed by each column of text data in order
  112434. ** from left to write. If parameter zFunc is not NULL, then instead of
  112435. ** being returned directly each column of text data is passed to an SQL
  112436. ** function named zFunc first. For example, if zFunc is "unzip" and the
  112437. ** table has the three user-defined columns "a", "b", and "c", the following
  112438. ** string is returned:
  112439. **
  112440. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  112441. **
  112442. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  112443. ** is the responsibility of the caller to eventually free it.
  112444. **
  112445. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  112446. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  112447. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  112448. ** no error occurs, *pRc is left unmodified.
  112449. */
  112450. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  112451. char *zRet = 0;
  112452. char *zFree = 0;
  112453. char *zFunction;
  112454. int i;
  112455. if( p->zContentTbl==0 ){
  112456. if( !zFunc ){
  112457. zFunction = "";
  112458. }else{
  112459. zFree = zFunction = fts3QuoteId(zFunc);
  112460. }
  112461. fts3Appendf(pRc, &zRet, "docid");
  112462. for(i=0; i<p->nColumn; i++){
  112463. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  112464. }
  112465. if( p->zLanguageid ){
  112466. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  112467. }
  112468. sqlite3_free(zFree);
  112469. }else{
  112470. fts3Appendf(pRc, &zRet, "rowid");
  112471. for(i=0; i<p->nColumn; i++){
  112472. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  112473. }
  112474. if( p->zLanguageid ){
  112475. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  112476. }
  112477. }
  112478. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  112479. p->zDb,
  112480. (p->zContentTbl ? p->zContentTbl : p->zName),
  112481. (p->zContentTbl ? "" : "_content")
  112482. );
  112483. return zRet;
  112484. }
  112485. /*
  112486. ** Return a list of N comma separated question marks, where N is the number
  112487. ** of columns in the %_content table (one for the docid plus one for each
  112488. ** user-defined text column).
  112489. **
  112490. ** If argument zFunc is not NULL, then all but the first question mark
  112491. ** is preceded by zFunc and an open bracket, and followed by a closed
  112492. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  112493. ** user-defined text columns, the following string is returned:
  112494. **
  112495. ** "?, zip(?), zip(?), zip(?)"
  112496. **
  112497. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  112498. ** is the responsibility of the caller to eventually free it.
  112499. **
  112500. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  112501. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  112502. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  112503. ** no error occurs, *pRc is left unmodified.
  112504. */
  112505. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  112506. char *zRet = 0;
  112507. char *zFree = 0;
  112508. char *zFunction;
  112509. int i;
  112510. if( !zFunc ){
  112511. zFunction = "";
  112512. }else{
  112513. zFree = zFunction = fts3QuoteId(zFunc);
  112514. }
  112515. fts3Appendf(pRc, &zRet, "?");
  112516. for(i=0; i<p->nColumn; i++){
  112517. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  112518. }
  112519. if( p->zLanguageid ){
  112520. fts3Appendf(pRc, &zRet, ", ?");
  112521. }
  112522. sqlite3_free(zFree);
  112523. return zRet;
  112524. }
  112525. /*
  112526. ** This function interprets the string at (*pp) as a non-negative integer
  112527. ** value. It reads the integer and sets *pnOut to the value read, then
  112528. ** sets *pp to point to the byte immediately following the last byte of
  112529. ** the integer value.
  112530. **
  112531. ** Only decimal digits ('0'..'9') may be part of an integer value.
  112532. **
  112533. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  112534. ** the output value undefined. Otherwise SQLITE_OK is returned.
  112535. **
  112536. ** This function is used when parsing the "prefix=" FTS4 parameter.
  112537. */
  112538. static int fts3GobbleInt(const char **pp, int *pnOut){
  112539. const char *p; /* Iterator pointer */
  112540. int nInt = 0; /* Output value */
  112541. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  112542. nInt = nInt * 10 + (p[0] - '0');
  112543. }
  112544. if( p==*pp ) return SQLITE_ERROR;
  112545. *pnOut = nInt;
  112546. *pp = p;
  112547. return SQLITE_OK;
  112548. }
  112549. /*
  112550. ** This function is called to allocate an array of Fts3Index structures
  112551. ** representing the indexes maintained by the current FTS table. FTS tables
  112552. ** always maintain the main "terms" index, but may also maintain one or
  112553. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  112554. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  112555. **
  112556. ** Argument zParam is passed the value of the "prefix=" option if one was
  112557. ** specified, or NULL otherwise.
  112558. **
  112559. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  112560. ** the allocated array. *pnIndex is set to the number of elements in the
  112561. ** array. If an error does occur, an SQLite error code is returned.
  112562. **
  112563. ** Regardless of whether or not an error is returned, it is the responsibility
  112564. ** of the caller to call sqlite3_free() on the output array to free it.
  112565. */
  112566. static int fts3PrefixParameter(
  112567. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  112568. int *pnIndex, /* OUT: size of *apIndex[] array */
  112569. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  112570. ){
  112571. struct Fts3Index *aIndex; /* Allocated array */
  112572. int nIndex = 1; /* Number of entries in array */
  112573. if( zParam && zParam[0] ){
  112574. const char *p;
  112575. nIndex++;
  112576. for(p=zParam; *p; p++){
  112577. if( *p==',' ) nIndex++;
  112578. }
  112579. }
  112580. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  112581. *apIndex = aIndex;
  112582. *pnIndex = nIndex;
  112583. if( !aIndex ){
  112584. return SQLITE_NOMEM;
  112585. }
  112586. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  112587. if( zParam ){
  112588. const char *p = zParam;
  112589. int i;
  112590. for(i=1; i<nIndex; i++){
  112591. int nPrefix;
  112592. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  112593. aIndex[i].nPrefix = nPrefix;
  112594. p++;
  112595. }
  112596. }
  112597. return SQLITE_OK;
  112598. }
  112599. /*
  112600. ** This function is called when initializing an FTS4 table that uses the
  112601. ** content=xxx option. It determines the number of and names of the columns
  112602. ** of the new FTS4 table.
  112603. **
  112604. ** The third argument passed to this function is the value passed to the
  112605. ** config=xxx option (i.e. "xxx"). This function queries the database for
  112606. ** a table of that name. If found, the output variables are populated
  112607. ** as follows:
  112608. **
  112609. ** *pnCol: Set to the number of columns table xxx has,
  112610. **
  112611. ** *pnStr: Set to the total amount of space required to store a copy
  112612. ** of each columns name, including the nul-terminator.
  112613. **
  112614. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  112615. ** the name of the corresponding column in table xxx. The array
  112616. ** and its contents are allocated using a single allocation. It
  112617. ** is the responsibility of the caller to free this allocation
  112618. ** by eventually passing the *pazCol value to sqlite3_free().
  112619. **
  112620. ** If the table cannot be found, an error code is returned and the output
  112621. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  112622. ** returned (and the output variables are undefined).
  112623. */
  112624. static int fts3ContentColumns(
  112625. sqlite3 *db, /* Database handle */
  112626. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  112627. const char *zTbl, /* Name of content table */
  112628. const char ***pazCol, /* OUT: Malloc'd array of column names */
  112629. int *pnCol, /* OUT: Size of array *pazCol */
  112630. int *pnStr /* OUT: Bytes of string content */
  112631. ){
  112632. int rc = SQLITE_OK; /* Return code */
  112633. char *zSql; /* "SELECT *" statement on zTbl */
  112634. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  112635. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  112636. if( !zSql ){
  112637. rc = SQLITE_NOMEM;
  112638. }else{
  112639. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  112640. }
  112641. sqlite3_free(zSql);
  112642. if( rc==SQLITE_OK ){
  112643. const char **azCol; /* Output array */
  112644. int nStr = 0; /* Size of all column names (incl. 0x00) */
  112645. int nCol; /* Number of table columns */
  112646. int i; /* Used to iterate through columns */
  112647. /* Loop through the returned columns. Set nStr to the number of bytes of
  112648. ** space required to store a copy of each column name, including the
  112649. ** nul-terminator byte. */
  112650. nCol = sqlite3_column_count(pStmt);
  112651. for(i=0; i<nCol; i++){
  112652. const char *zCol = sqlite3_column_name(pStmt, i);
  112653. nStr += (int)strlen(zCol) + 1;
  112654. }
  112655. /* Allocate and populate the array to return. */
  112656. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  112657. if( azCol==0 ){
  112658. rc = SQLITE_NOMEM;
  112659. }else{
  112660. char *p = (char *)&azCol[nCol];
  112661. for(i=0; i<nCol; i++){
  112662. const char *zCol = sqlite3_column_name(pStmt, i);
  112663. int n = (int)strlen(zCol)+1;
  112664. memcpy(p, zCol, n);
  112665. azCol[i] = p;
  112666. p += n;
  112667. }
  112668. }
  112669. sqlite3_finalize(pStmt);
  112670. /* Set the output variables. */
  112671. *pnCol = nCol;
  112672. *pnStr = nStr;
  112673. *pazCol = azCol;
  112674. }
  112675. return rc;
  112676. }
  112677. /*
  112678. ** This function is the implementation of both the xConnect and xCreate
  112679. ** methods of the FTS3 virtual table.
  112680. **
  112681. ** The argv[] array contains the following:
  112682. **
  112683. ** argv[0] -> module name ("fts3" or "fts4")
  112684. ** argv[1] -> database name
  112685. ** argv[2] -> table name
  112686. ** argv[...] -> "column name" and other module argument fields.
  112687. */
  112688. static int fts3InitVtab(
  112689. int isCreate, /* True for xCreate, false for xConnect */
  112690. sqlite3 *db, /* The SQLite database connection */
  112691. void *pAux, /* Hash table containing tokenizers */
  112692. int argc, /* Number of elements in argv array */
  112693. const char * const *argv, /* xCreate/xConnect argument array */
  112694. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  112695. char **pzErr /* Write any error message here */
  112696. ){
  112697. Fts3Hash *pHash = (Fts3Hash *)pAux;
  112698. Fts3Table *p = 0; /* Pointer to allocated vtab */
  112699. int rc = SQLITE_OK; /* Return code */
  112700. int i; /* Iterator variable */
  112701. int nByte; /* Size of allocation used for *p */
  112702. int iCol; /* Column index */
  112703. int nString = 0; /* Bytes required to hold all column names */
  112704. int nCol = 0; /* Number of columns in the FTS table */
  112705. char *zCsr; /* Space for holding column names */
  112706. int nDb; /* Bytes required to hold database name */
  112707. int nName; /* Bytes required to hold table name */
  112708. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  112709. const char **aCol; /* Array of column names */
  112710. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  112711. int nIndex; /* Size of aIndex[] array */
  112712. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  112713. /* The results of parsing supported FTS4 key=value options: */
  112714. int bNoDocsize = 0; /* True to omit %_docsize table */
  112715. int bDescIdx = 0; /* True to store descending indexes */
  112716. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  112717. char *zCompress = 0; /* compress=? parameter (or NULL) */
  112718. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  112719. char *zContent = 0; /* content=? parameter (or NULL) */
  112720. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  112721. assert( strlen(argv[0])==4 );
  112722. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  112723. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  112724. );
  112725. nDb = (int)strlen(argv[1]) + 1;
  112726. nName = (int)strlen(argv[2]) + 1;
  112727. aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
  112728. if( !aCol ) return SQLITE_NOMEM;
  112729. memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
  112730. /* Loop through all of the arguments passed by the user to the FTS3/4
  112731. ** module (i.e. all the column names and special arguments). This loop
  112732. ** does the following:
  112733. **
  112734. ** + Figures out the number of columns the FTSX table will have, and
  112735. ** the number of bytes of space that must be allocated to store copies
  112736. ** of the column names.
  112737. **
  112738. ** + If there is a tokenizer specification included in the arguments,
  112739. ** initializes the tokenizer pTokenizer.
  112740. */
  112741. for(i=3; rc==SQLITE_OK && i<argc; i++){
  112742. char const *z = argv[i];
  112743. int nKey;
  112744. char *zVal;
  112745. /* Check if this is a tokenizer specification */
  112746. if( !pTokenizer
  112747. && strlen(z)>8
  112748. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  112749. && 0==sqlite3Fts3IsIdChar(z[8])
  112750. ){
  112751. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  112752. }
  112753. /* Check if it is an FTS4 special argument. */
  112754. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  112755. struct Fts4Option {
  112756. const char *zOpt;
  112757. int nOpt;
  112758. } aFts4Opt[] = {
  112759. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  112760. { "prefix", 6 }, /* 1 -> PREFIX */
  112761. { "compress", 8 }, /* 2 -> COMPRESS */
  112762. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  112763. { "order", 5 }, /* 4 -> ORDER */
  112764. { "content", 7 }, /* 5 -> CONTENT */
  112765. { "languageid", 10 } /* 6 -> LANGUAGEID */
  112766. };
  112767. int iOpt;
  112768. if( !zVal ){
  112769. rc = SQLITE_NOMEM;
  112770. }else{
  112771. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  112772. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  112773. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  112774. break;
  112775. }
  112776. }
  112777. if( iOpt==SizeofArray(aFts4Opt) ){
  112778. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  112779. rc = SQLITE_ERROR;
  112780. }else{
  112781. switch( iOpt ){
  112782. case 0: /* MATCHINFO */
  112783. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  112784. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  112785. rc = SQLITE_ERROR;
  112786. }
  112787. bNoDocsize = 1;
  112788. break;
  112789. case 1: /* PREFIX */
  112790. sqlite3_free(zPrefix);
  112791. zPrefix = zVal;
  112792. zVal = 0;
  112793. break;
  112794. case 2: /* COMPRESS */
  112795. sqlite3_free(zCompress);
  112796. zCompress = zVal;
  112797. zVal = 0;
  112798. break;
  112799. case 3: /* UNCOMPRESS */
  112800. sqlite3_free(zUncompress);
  112801. zUncompress = zVal;
  112802. zVal = 0;
  112803. break;
  112804. case 4: /* ORDER */
  112805. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  112806. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  112807. ){
  112808. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  112809. rc = SQLITE_ERROR;
  112810. }
  112811. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  112812. break;
  112813. case 5: /* CONTENT */
  112814. sqlite3_free(zContent);
  112815. zContent = zVal;
  112816. zVal = 0;
  112817. break;
  112818. case 6: /* LANGUAGEID */
  112819. assert( iOpt==6 );
  112820. sqlite3_free(zLanguageid);
  112821. zLanguageid = zVal;
  112822. zVal = 0;
  112823. break;
  112824. }
  112825. }
  112826. sqlite3_free(zVal);
  112827. }
  112828. }
  112829. /* Otherwise, the argument is a column name. */
  112830. else {
  112831. nString += (int)(strlen(z) + 1);
  112832. aCol[nCol++] = z;
  112833. }
  112834. }
  112835. /* If a content=xxx option was specified, the following:
  112836. **
  112837. ** 1. Ignore any compress= and uncompress= options.
  112838. **
  112839. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  112840. ** TABLE statement, use all columns from the content table.
  112841. */
  112842. if( rc==SQLITE_OK && zContent ){
  112843. sqlite3_free(zCompress);
  112844. sqlite3_free(zUncompress);
  112845. zCompress = 0;
  112846. zUncompress = 0;
  112847. if( nCol==0 ){
  112848. sqlite3_free((void*)aCol);
  112849. aCol = 0;
  112850. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  112851. /* If a languageid= option was specified, remove the language id
  112852. ** column from the aCol[] array. */
  112853. if( rc==SQLITE_OK && zLanguageid ){
  112854. int j;
  112855. for(j=0; j<nCol; j++){
  112856. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  112857. int k;
  112858. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  112859. nCol--;
  112860. break;
  112861. }
  112862. }
  112863. }
  112864. }
  112865. }
  112866. if( rc!=SQLITE_OK ) goto fts3_init_out;
  112867. if( nCol==0 ){
  112868. assert( nString==0 );
  112869. aCol[0] = "content";
  112870. nString = 8;
  112871. nCol = 1;
  112872. }
  112873. if( pTokenizer==0 ){
  112874. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  112875. if( rc!=SQLITE_OK ) goto fts3_init_out;
  112876. }
  112877. assert( pTokenizer );
  112878. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  112879. if( rc==SQLITE_ERROR ){
  112880. assert( zPrefix );
  112881. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  112882. }
  112883. if( rc!=SQLITE_OK ) goto fts3_init_out;
  112884. /* Allocate and populate the Fts3Table structure. */
  112885. nByte = sizeof(Fts3Table) + /* Fts3Table */
  112886. nCol * sizeof(char *) + /* azColumn */
  112887. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  112888. nName + /* zName */
  112889. nDb + /* zDb */
  112890. nString; /* Space for azColumn strings */
  112891. p = (Fts3Table*)sqlite3_malloc(nByte);
  112892. if( p==0 ){
  112893. rc = SQLITE_NOMEM;
  112894. goto fts3_init_out;
  112895. }
  112896. memset(p, 0, nByte);
  112897. p->db = db;
  112898. p->nColumn = nCol;
  112899. p->nPendingData = 0;
  112900. p->azColumn = (char **)&p[1];
  112901. p->pTokenizer = pTokenizer;
  112902. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  112903. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  112904. p->bHasStat = isFts4;
  112905. p->bFts4 = isFts4;
  112906. p->bDescIdx = bDescIdx;
  112907. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  112908. p->zContentTbl = zContent;
  112909. p->zLanguageid = zLanguageid;
  112910. zContent = 0;
  112911. zLanguageid = 0;
  112912. TESTONLY( p->inTransaction = -1 );
  112913. TESTONLY( p->mxSavepoint = -1 );
  112914. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  112915. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  112916. p->nIndex = nIndex;
  112917. for(i=0; i<nIndex; i++){
  112918. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  112919. }
  112920. /* Fill in the zName and zDb fields of the vtab structure. */
  112921. zCsr = (char *)&p->aIndex[nIndex];
  112922. p->zName = zCsr;
  112923. memcpy(zCsr, argv[2], nName);
  112924. zCsr += nName;
  112925. p->zDb = zCsr;
  112926. memcpy(zCsr, argv[1], nDb);
  112927. zCsr += nDb;
  112928. /* Fill in the azColumn array */
  112929. for(iCol=0; iCol<nCol; iCol++){
  112930. char *z;
  112931. int n = 0;
  112932. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  112933. memcpy(zCsr, z, n);
  112934. zCsr[n] = '\0';
  112935. sqlite3Fts3Dequote(zCsr);
  112936. p->azColumn[iCol] = zCsr;
  112937. zCsr += n+1;
  112938. assert( zCsr <= &((char *)p)[nByte] );
  112939. }
  112940. if( (zCompress==0)!=(zUncompress==0) ){
  112941. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  112942. rc = SQLITE_ERROR;
  112943. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  112944. }
  112945. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  112946. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  112947. if( rc!=SQLITE_OK ) goto fts3_init_out;
  112948. /* If this is an xCreate call, create the underlying tables in the
  112949. ** database. TODO: For xConnect(), it could verify that said tables exist.
  112950. */
  112951. if( isCreate ){
  112952. rc = fts3CreateTables(p);
  112953. }
  112954. /* Check to see if a legacy fts3 table has been "upgraded" by the
  112955. ** addition of a %_stat table so that it can use incremental merge.
  112956. */
  112957. if( !isFts4 && !isCreate ){
  112958. int rc2 = SQLITE_OK;
  112959. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  112960. p->zDb, p->zName);
  112961. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  112962. }
  112963. /* Figure out the page-size for the database. This is required in order to
  112964. ** estimate the cost of loading large doclists from the database. */
  112965. fts3DatabasePageSize(&rc, p);
  112966. p->nNodeSize = p->nPgsz-35;
  112967. /* Declare the table schema to SQLite. */
  112968. fts3DeclareVtab(&rc, p);
  112969. fts3_init_out:
  112970. sqlite3_free(zPrefix);
  112971. sqlite3_free(aIndex);
  112972. sqlite3_free(zCompress);
  112973. sqlite3_free(zUncompress);
  112974. sqlite3_free(zContent);
  112975. sqlite3_free(zLanguageid);
  112976. sqlite3_free((void *)aCol);
  112977. if( rc!=SQLITE_OK ){
  112978. if( p ){
  112979. fts3DisconnectMethod((sqlite3_vtab *)p);
  112980. }else if( pTokenizer ){
  112981. pTokenizer->pModule->xDestroy(pTokenizer);
  112982. }
  112983. }else{
  112984. assert( p->pSegments==0 );
  112985. *ppVTab = &p->base;
  112986. }
  112987. return rc;
  112988. }
  112989. /*
  112990. ** The xConnect() and xCreate() methods for the virtual table. All the
  112991. ** work is done in function fts3InitVtab().
  112992. */
  112993. static int fts3ConnectMethod(
  112994. sqlite3 *db, /* Database connection */
  112995. void *pAux, /* Pointer to tokenizer hash table */
  112996. int argc, /* Number of elements in argv array */
  112997. const char * const *argv, /* xCreate/xConnect argument array */
  112998. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  112999. char **pzErr /* OUT: sqlite3_malloc'd error message */
  113000. ){
  113001. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  113002. }
  113003. static int fts3CreateMethod(
  113004. sqlite3 *db, /* Database connection */
  113005. void *pAux, /* Pointer to tokenizer hash table */
  113006. int argc, /* Number of elements in argv array */
  113007. const char * const *argv, /* xCreate/xConnect argument array */
  113008. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  113009. char **pzErr /* OUT: sqlite3_malloc'd error message */
  113010. ){
  113011. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  113012. }
  113013. /*
  113014. ** Implementation of the xBestIndex method for FTS3 tables. There
  113015. ** are three possible strategies, in order of preference:
  113016. **
  113017. ** 1. Direct lookup by rowid or docid.
  113018. ** 2. Full-text search using a MATCH operator on a non-docid column.
  113019. ** 3. Linear scan of %_content table.
  113020. */
  113021. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  113022. Fts3Table *p = (Fts3Table *)pVTab;
  113023. int i; /* Iterator variable */
  113024. int iCons = -1; /* Index of constraint to use */
  113025. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  113026. /* By default use a full table scan. This is an expensive option,
  113027. ** so search through the constraints to see if a more efficient
  113028. ** strategy is possible.
  113029. */
  113030. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  113031. pInfo->estimatedCost = 500000;
  113032. for(i=0; i<pInfo->nConstraint; i++){
  113033. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  113034. if( pCons->usable==0 ) continue;
  113035. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  113036. if( iCons<0
  113037. && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  113038. && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
  113039. ){
  113040. pInfo->idxNum = FTS3_DOCID_SEARCH;
  113041. pInfo->estimatedCost = 1.0;
  113042. iCons = i;
  113043. }
  113044. /* A MATCH constraint. Use a full-text search.
  113045. **
  113046. ** If there is more than one MATCH constraint available, use the first
  113047. ** one encountered. If there is both a MATCH constraint and a direct
  113048. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  113049. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  113050. ** it would lead to an "unable to use function MATCH in the requested
  113051. ** context" error.
  113052. */
  113053. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  113054. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  113055. ){
  113056. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  113057. pInfo->estimatedCost = 2.0;
  113058. iCons = i;
  113059. }
  113060. /* Equality constraint on the langid column */
  113061. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  113062. && pCons->iColumn==p->nColumn + 2
  113063. ){
  113064. iLangidCons = i;
  113065. }
  113066. }
  113067. if( iCons>=0 ){
  113068. pInfo->aConstraintUsage[iCons].argvIndex = 1;
  113069. pInfo->aConstraintUsage[iCons].omit = 1;
  113070. }
  113071. if( iLangidCons>=0 ){
  113072. pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
  113073. }
  113074. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  113075. ** docid) order. Both ascending and descending are possible.
  113076. */
  113077. if( pInfo->nOrderBy==1 ){
  113078. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  113079. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  113080. if( pOrder->desc ){
  113081. pInfo->idxStr = "DESC";
  113082. }else{
  113083. pInfo->idxStr = "ASC";
  113084. }
  113085. pInfo->orderByConsumed = 1;
  113086. }
  113087. }
  113088. assert( p->pSegments==0 );
  113089. return SQLITE_OK;
  113090. }
  113091. /*
  113092. ** Implementation of xOpen method.
  113093. */
  113094. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  113095. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  113096. UNUSED_PARAMETER(pVTab);
  113097. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  113098. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  113099. ** if the allocation fails, return SQLITE_NOMEM.
  113100. */
  113101. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  113102. if( !pCsr ){
  113103. return SQLITE_NOMEM;
  113104. }
  113105. memset(pCsr, 0, sizeof(Fts3Cursor));
  113106. return SQLITE_OK;
  113107. }
  113108. /*
  113109. ** Close the cursor. For additional information see the documentation
  113110. ** on the xClose method of the virtual table interface.
  113111. */
  113112. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  113113. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  113114. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  113115. sqlite3_finalize(pCsr->pStmt);
  113116. sqlite3Fts3ExprFree(pCsr->pExpr);
  113117. sqlite3Fts3FreeDeferredTokens(pCsr);
  113118. sqlite3_free(pCsr->aDoclist);
  113119. sqlite3_free(pCsr->aMatchinfo);
  113120. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  113121. sqlite3_free(pCsr);
  113122. return SQLITE_OK;
  113123. }
  113124. /*
  113125. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  113126. ** compose and prepare an SQL statement of the form:
  113127. **
  113128. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  113129. **
  113130. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  113131. ** it. If an error occurs, return an SQLite error code.
  113132. **
  113133. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  113134. */
  113135. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  113136. int rc = SQLITE_OK;
  113137. if( pCsr->pStmt==0 ){
  113138. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  113139. char *zSql;
  113140. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  113141. if( !zSql ) return SQLITE_NOMEM;
  113142. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  113143. sqlite3_free(zSql);
  113144. }
  113145. *ppStmt = pCsr->pStmt;
  113146. return rc;
  113147. }
  113148. /*
  113149. ** Position the pCsr->pStmt statement so that it is on the row
  113150. ** of the %_content table that contains the last match. Return
  113151. ** SQLITE_OK on success.
  113152. */
  113153. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  113154. int rc = SQLITE_OK;
  113155. if( pCsr->isRequireSeek ){
  113156. sqlite3_stmt *pStmt = 0;
  113157. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  113158. if( rc==SQLITE_OK ){
  113159. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  113160. pCsr->isRequireSeek = 0;
  113161. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  113162. return SQLITE_OK;
  113163. }else{
  113164. rc = sqlite3_reset(pCsr->pStmt);
  113165. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  113166. /* If no row was found and no error has occurred, then the %_content
  113167. ** table is missing a row that is present in the full-text index.
  113168. ** The data structures are corrupt. */
  113169. rc = FTS_CORRUPT_VTAB;
  113170. pCsr->isEof = 1;
  113171. }
  113172. }
  113173. }
  113174. }
  113175. if( rc!=SQLITE_OK && pContext ){
  113176. sqlite3_result_error_code(pContext, rc);
  113177. }
  113178. return rc;
  113179. }
  113180. /*
  113181. ** This function is used to process a single interior node when searching
  113182. ** a b-tree for a term or term prefix. The node data is passed to this
  113183. ** function via the zNode/nNode parameters. The term to search for is
  113184. ** passed in zTerm/nTerm.
  113185. **
  113186. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  113187. ** of the child node that heads the sub-tree that may contain the term.
  113188. **
  113189. ** If piLast is not NULL, then *piLast is set to the right-most child node
  113190. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  113191. ** a prefix.
  113192. **
  113193. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  113194. */
  113195. static int fts3ScanInteriorNode(
  113196. const char *zTerm, /* Term to select leaves for */
  113197. int nTerm, /* Size of term zTerm in bytes */
  113198. const char *zNode, /* Buffer containing segment interior node */
  113199. int nNode, /* Size of buffer at zNode */
  113200. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  113201. sqlite3_int64 *piLast /* OUT: Selected child node */
  113202. ){
  113203. int rc = SQLITE_OK; /* Return code */
  113204. const char *zCsr = zNode; /* Cursor to iterate through node */
  113205. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  113206. char *zBuffer = 0; /* Buffer to load terms into */
  113207. int nAlloc = 0; /* Size of allocated buffer */
  113208. int isFirstTerm = 1; /* True when processing first term on page */
  113209. sqlite3_int64 iChild; /* Block id of child node to descend to */
  113210. /* Skip over the 'height' varint that occurs at the start of every
  113211. ** interior node. Then load the blockid of the left-child of the b-tree
  113212. ** node into variable iChild.
  113213. **
  113214. ** Even if the data structure on disk is corrupted, this (reading two
  113215. ** varints from the buffer) does not risk an overread. If zNode is a
  113216. ** root node, then the buffer comes from a SELECT statement. SQLite does
  113217. ** not make this guarantee explicitly, but in practice there are always
  113218. ** either more than 20 bytes of allocated space following the nNode bytes of
  113219. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  113220. ** table, then there are always 20 bytes of zeroed padding following the
  113221. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  113222. */
  113223. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  113224. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  113225. if( zCsr>zEnd ){
  113226. return FTS_CORRUPT_VTAB;
  113227. }
  113228. while( zCsr<zEnd && (piFirst || piLast) ){
  113229. int cmp; /* memcmp() result */
  113230. int nSuffix; /* Size of term suffix */
  113231. int nPrefix = 0; /* Size of term prefix */
  113232. int nBuffer; /* Total term size */
  113233. /* Load the next term on the node into zBuffer. Use realloc() to expand
  113234. ** the size of zBuffer if required. */
  113235. if( !isFirstTerm ){
  113236. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  113237. }
  113238. isFirstTerm = 0;
  113239. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  113240. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  113241. rc = FTS_CORRUPT_VTAB;
  113242. goto finish_scan;
  113243. }
  113244. if( nPrefix+nSuffix>nAlloc ){
  113245. char *zNew;
  113246. nAlloc = (nPrefix+nSuffix) * 2;
  113247. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  113248. if( !zNew ){
  113249. rc = SQLITE_NOMEM;
  113250. goto finish_scan;
  113251. }
  113252. zBuffer = zNew;
  113253. }
  113254. assert( zBuffer );
  113255. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  113256. nBuffer = nPrefix + nSuffix;
  113257. zCsr += nSuffix;
  113258. /* Compare the term we are searching for with the term just loaded from
  113259. ** the interior node. If the specified term is greater than or equal
  113260. ** to the term from the interior node, then all terms on the sub-tree
  113261. ** headed by node iChild are smaller than zTerm. No need to search
  113262. ** iChild.
  113263. **
  113264. ** If the interior node term is larger than the specified term, then
  113265. ** the tree headed by iChild may contain the specified term.
  113266. */
  113267. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  113268. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  113269. *piFirst = iChild;
  113270. piFirst = 0;
  113271. }
  113272. if( piLast && cmp<0 ){
  113273. *piLast = iChild;
  113274. piLast = 0;
  113275. }
  113276. iChild++;
  113277. };
  113278. if( piFirst ) *piFirst = iChild;
  113279. if( piLast ) *piLast = iChild;
  113280. finish_scan:
  113281. sqlite3_free(zBuffer);
  113282. return rc;
  113283. }
  113284. /*
  113285. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  113286. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  113287. ** contains a term. This function searches the sub-tree headed by the zNode
  113288. ** node for the range of leaf nodes that may contain the specified term
  113289. ** or terms for which the specified term is a prefix.
  113290. **
  113291. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  113292. ** left-most leaf node in the tree that may contain the specified term.
  113293. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  113294. ** right-most leaf node that may contain a term for which the specified
  113295. ** term is a prefix.
  113296. **
  113297. ** It is possible that the range of returned leaf nodes does not contain
  113298. ** the specified term or any terms for which it is a prefix. However, if the
  113299. ** segment does contain any such terms, they are stored within the identified
  113300. ** range. Because this function only inspects interior segment nodes (and
  113301. ** never loads leaf nodes into memory), it is not possible to be sure.
  113302. **
  113303. ** If an error occurs, an error code other than SQLITE_OK is returned.
  113304. */
  113305. static int fts3SelectLeaf(
  113306. Fts3Table *p, /* Virtual table handle */
  113307. const char *zTerm, /* Term to select leaves for */
  113308. int nTerm, /* Size of term zTerm in bytes */
  113309. const char *zNode, /* Buffer containing segment interior node */
  113310. int nNode, /* Size of buffer at zNode */
  113311. sqlite3_int64 *piLeaf, /* Selected leaf node */
  113312. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  113313. ){
  113314. int rc; /* Return code */
  113315. int iHeight; /* Height of this node in tree */
  113316. assert( piLeaf || piLeaf2 );
  113317. sqlite3Fts3GetVarint32(zNode, &iHeight);
  113318. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  113319. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  113320. if( rc==SQLITE_OK && iHeight>1 ){
  113321. char *zBlob = 0; /* Blob read from %_segments table */
  113322. int nBlob; /* Size of zBlob in bytes */
  113323. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  113324. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  113325. if( rc==SQLITE_OK ){
  113326. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  113327. }
  113328. sqlite3_free(zBlob);
  113329. piLeaf = 0;
  113330. zBlob = 0;
  113331. }
  113332. if( rc==SQLITE_OK ){
  113333. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  113334. }
  113335. if( rc==SQLITE_OK ){
  113336. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  113337. }
  113338. sqlite3_free(zBlob);
  113339. }
  113340. return rc;
  113341. }
  113342. /*
  113343. ** This function is used to create delta-encoded serialized lists of FTS3
  113344. ** varints. Each call to this function appends a single varint to a list.
  113345. */
  113346. static void fts3PutDeltaVarint(
  113347. char **pp, /* IN/OUT: Output pointer */
  113348. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  113349. sqlite3_int64 iVal /* Write this value to the list */
  113350. ){
  113351. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  113352. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  113353. *piPrev = iVal;
  113354. }
  113355. /*
  113356. ** When this function is called, *ppPoslist is assumed to point to the
  113357. ** start of a position-list. After it returns, *ppPoslist points to the
  113358. ** first byte after the position-list.
  113359. **
  113360. ** A position list is list of positions (delta encoded) and columns for
  113361. ** a single document record of a doclist. So, in other words, this
  113362. ** routine advances *ppPoslist so that it points to the next docid in
  113363. ** the doclist, or to the first byte past the end of the doclist.
  113364. **
  113365. ** If pp is not NULL, then the contents of the position list are copied
  113366. ** to *pp. *pp is set to point to the first byte past the last byte copied
  113367. ** before this function returns.
  113368. */
  113369. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  113370. char *pEnd = *ppPoslist;
  113371. char c = 0;
  113372. /* The end of a position list is marked by a zero encoded as an FTS3
  113373. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  113374. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  113375. ** of some other, multi-byte, value.
  113376. **
  113377. ** The following while-loop moves pEnd to point to the first byte that is not
  113378. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  113379. ** pEnd once more so that it points to the byte immediately following the
  113380. ** last byte in the position-list.
  113381. */
  113382. while( *pEnd | c ){
  113383. c = *pEnd++ & 0x80;
  113384. testcase( c!=0 && (*pEnd)==0 );
  113385. }
  113386. pEnd++; /* Advance past the POS_END terminator byte */
  113387. if( pp ){
  113388. int n = (int)(pEnd - *ppPoslist);
  113389. char *p = *pp;
  113390. memcpy(p, *ppPoslist, n);
  113391. p += n;
  113392. *pp = p;
  113393. }
  113394. *ppPoslist = pEnd;
  113395. }
  113396. /*
  113397. ** When this function is called, *ppPoslist is assumed to point to the
  113398. ** start of a column-list. After it returns, *ppPoslist points to the
  113399. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  113400. **
  113401. ** A column-list is list of delta-encoded positions for a single column
  113402. ** within a single document within a doclist.
  113403. **
  113404. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  113405. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  113406. ** the POS_COLUMN or POS_END that terminates the column-list.
  113407. **
  113408. ** If pp is not NULL, then the contents of the column-list are copied
  113409. ** to *pp. *pp is set to point to the first byte past the last byte copied
  113410. ** before this function returns. The POS_COLUMN or POS_END terminator
  113411. ** is not copied into *pp.
  113412. */
  113413. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  113414. char *pEnd = *ppPoslist;
  113415. char c = 0;
  113416. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  113417. ** not part of a multi-byte varint.
  113418. */
  113419. while( 0xFE & (*pEnd | c) ){
  113420. c = *pEnd++ & 0x80;
  113421. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  113422. }
  113423. if( pp ){
  113424. int n = (int)(pEnd - *ppPoslist);
  113425. char *p = *pp;
  113426. memcpy(p, *ppPoslist, n);
  113427. p += n;
  113428. *pp = p;
  113429. }
  113430. *ppPoslist = pEnd;
  113431. }
  113432. /*
  113433. ** Value used to signify the end of an position-list. This is safe because
  113434. ** it is not possible to have a document with 2^31 terms.
  113435. */
  113436. #define POSITION_LIST_END 0x7fffffff
  113437. /*
  113438. ** This function is used to help parse position-lists. When this function is
  113439. ** called, *pp may point to the start of the next varint in the position-list
  113440. ** being parsed, or it may point to 1 byte past the end of the position-list
  113441. ** (in which case **pp will be a terminator bytes POS_END (0) or
  113442. ** (1)).
  113443. **
  113444. ** If *pp points past the end of the current position-list, set *pi to
  113445. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  113446. ** increment the current value of *pi by the value read, and set *pp to
  113447. ** point to the next value before returning.
  113448. **
  113449. ** Before calling this routine *pi must be initialized to the value of
  113450. ** the previous position, or zero if we are reading the first position
  113451. ** in the position-list. Because positions are delta-encoded, the value
  113452. ** of the previous position is needed in order to compute the value of
  113453. ** the next position.
  113454. */
  113455. static void fts3ReadNextPos(
  113456. char **pp, /* IN/OUT: Pointer into position-list buffer */
  113457. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  113458. ){
  113459. if( (**pp)&0xFE ){
  113460. fts3GetDeltaVarint(pp, pi);
  113461. *pi -= 2;
  113462. }else{
  113463. *pi = POSITION_LIST_END;
  113464. }
  113465. }
  113466. /*
  113467. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  113468. ** the value of iCol encoded as a varint to *pp. This will start a new
  113469. ** column list.
  113470. **
  113471. ** Set *pp to point to the byte just after the last byte written before
  113472. ** returning (do not modify it if iCol==0). Return the total number of bytes
  113473. ** written (0 if iCol==0).
  113474. */
  113475. static int fts3PutColNumber(char **pp, int iCol){
  113476. int n = 0; /* Number of bytes written */
  113477. if( iCol ){
  113478. char *p = *pp; /* Output pointer */
  113479. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  113480. *p = 0x01;
  113481. *pp = &p[n];
  113482. }
  113483. return n;
  113484. }
  113485. /*
  113486. ** Compute the union of two position lists. The output written
  113487. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  113488. ** order and with any duplicates removed. All pointers are
  113489. ** updated appropriately. The caller is responsible for insuring
  113490. ** that there is enough space in *pp to hold the complete output.
  113491. */
  113492. static void fts3PoslistMerge(
  113493. char **pp, /* Output buffer */
  113494. char **pp1, /* Left input list */
  113495. char **pp2 /* Right input list */
  113496. ){
  113497. char *p = *pp;
  113498. char *p1 = *pp1;
  113499. char *p2 = *pp2;
  113500. while( *p1 || *p2 ){
  113501. int iCol1; /* The current column index in pp1 */
  113502. int iCol2; /* The current column index in pp2 */
  113503. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  113504. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  113505. else iCol1 = 0;
  113506. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  113507. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  113508. else iCol2 = 0;
  113509. if( iCol1==iCol2 ){
  113510. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  113511. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  113512. sqlite3_int64 iPrev = 0;
  113513. int n = fts3PutColNumber(&p, iCol1);
  113514. p1 += n;
  113515. p2 += n;
  113516. /* At this point, both p1 and p2 point to the start of column-lists
  113517. ** for the same column (the column with index iCol1 and iCol2).
  113518. ** A column-list is a list of non-negative delta-encoded varints, each
  113519. ** incremented by 2 before being stored. Each list is terminated by a
  113520. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  113521. ** and writes the results to buffer p. p is left pointing to the byte
  113522. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  113523. ** written to the output.
  113524. */
  113525. fts3GetDeltaVarint(&p1, &i1);
  113526. fts3GetDeltaVarint(&p2, &i2);
  113527. do {
  113528. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  113529. iPrev -= 2;
  113530. if( i1==i2 ){
  113531. fts3ReadNextPos(&p1, &i1);
  113532. fts3ReadNextPos(&p2, &i2);
  113533. }else if( i1<i2 ){
  113534. fts3ReadNextPos(&p1, &i1);
  113535. }else{
  113536. fts3ReadNextPos(&p2, &i2);
  113537. }
  113538. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  113539. }else if( iCol1<iCol2 ){
  113540. p1 += fts3PutColNumber(&p, iCol1);
  113541. fts3ColumnlistCopy(&p, &p1);
  113542. }else{
  113543. p2 += fts3PutColNumber(&p, iCol2);
  113544. fts3ColumnlistCopy(&p, &p2);
  113545. }
  113546. }
  113547. *p++ = POS_END;
  113548. *pp = p;
  113549. *pp1 = p1 + 1;
  113550. *pp2 = p2 + 1;
  113551. }
  113552. /*
  113553. ** This function is used to merge two position lists into one. When it is
  113554. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  113555. ** the part of a doclist that follows each document id. For example, if a row
  113556. ** contains:
  113557. **
  113558. ** 'a b c'|'x y z'|'a b b a'
  113559. **
  113560. ** Then the position list for this row for token 'b' would consist of:
  113561. **
  113562. ** 0x02 0x01 0x02 0x03 0x03 0x00
  113563. **
  113564. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  113565. ** byte following the 0x00 terminator of their respective position lists.
  113566. **
  113567. ** If isSaveLeft is 0, an entry is added to the output position list for
  113568. ** each position in *pp2 for which there exists one or more positions in
  113569. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  113570. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  113571. ** slots before it.
  113572. **
  113573. ** e.g. nToken==1 searches for adjacent positions.
  113574. */
  113575. static int fts3PoslistPhraseMerge(
  113576. char **pp, /* IN/OUT: Preallocated output buffer */
  113577. int nToken, /* Maximum difference in token positions */
  113578. int isSaveLeft, /* Save the left position */
  113579. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  113580. char **pp1, /* IN/OUT: Left input list */
  113581. char **pp2 /* IN/OUT: Right input list */
  113582. ){
  113583. char *p = *pp;
  113584. char *p1 = *pp1;
  113585. char *p2 = *pp2;
  113586. int iCol1 = 0;
  113587. int iCol2 = 0;
  113588. /* Never set both isSaveLeft and isExact for the same invocation. */
  113589. assert( isSaveLeft==0 || isExact==0 );
  113590. assert( p!=0 && *p1!=0 && *p2!=0 );
  113591. if( *p1==POS_COLUMN ){
  113592. p1++;
  113593. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  113594. }
  113595. if( *p2==POS_COLUMN ){
  113596. p2++;
  113597. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  113598. }
  113599. while( 1 ){
  113600. if( iCol1==iCol2 ){
  113601. char *pSave = p;
  113602. sqlite3_int64 iPrev = 0;
  113603. sqlite3_int64 iPos1 = 0;
  113604. sqlite3_int64 iPos2 = 0;
  113605. if( iCol1 ){
  113606. *p++ = POS_COLUMN;
  113607. p += sqlite3Fts3PutVarint(p, iCol1);
  113608. }
  113609. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  113610. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  113611. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  113612. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  113613. while( 1 ){
  113614. if( iPos2==iPos1+nToken
  113615. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  113616. ){
  113617. sqlite3_int64 iSave;
  113618. iSave = isSaveLeft ? iPos1 : iPos2;
  113619. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  113620. pSave = 0;
  113621. assert( p );
  113622. }
  113623. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  113624. if( (*p2&0xFE)==0 ) break;
  113625. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  113626. }else{
  113627. if( (*p1&0xFE)==0 ) break;
  113628. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  113629. }
  113630. }
  113631. if( pSave ){
  113632. assert( pp && p );
  113633. p = pSave;
  113634. }
  113635. fts3ColumnlistCopy(0, &p1);
  113636. fts3ColumnlistCopy(0, &p2);
  113637. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  113638. if( 0==*p1 || 0==*p2 ) break;
  113639. p1++;
  113640. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  113641. p2++;
  113642. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  113643. }
  113644. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  113645. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  113646. ** end of the position list, or the 0x01 that precedes the next
  113647. ** column-number in the position list.
  113648. */
  113649. else if( iCol1<iCol2 ){
  113650. fts3ColumnlistCopy(0, &p1);
  113651. if( 0==*p1 ) break;
  113652. p1++;
  113653. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  113654. }else{
  113655. fts3ColumnlistCopy(0, &p2);
  113656. if( 0==*p2 ) break;
  113657. p2++;
  113658. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  113659. }
  113660. }
  113661. fts3PoslistCopy(0, &p2);
  113662. fts3PoslistCopy(0, &p1);
  113663. *pp1 = p1;
  113664. *pp2 = p2;
  113665. if( *pp==p ){
  113666. return 0;
  113667. }
  113668. *p++ = 0x00;
  113669. *pp = p;
  113670. return 1;
  113671. }
  113672. /*
  113673. ** Merge two position-lists as required by the NEAR operator. The argument
  113674. ** position lists correspond to the left and right phrases of an expression
  113675. ** like:
  113676. **
  113677. ** "phrase 1" NEAR "phrase number 2"
  113678. **
  113679. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  113680. ** expression and *pp2 to the right. As usual, the indexes in the position
  113681. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  113682. ** in the example above).
  113683. **
  113684. ** The output position list - written to *pp - is a copy of *pp2 with those
  113685. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  113686. */
  113687. static int fts3PoslistNearMerge(
  113688. char **pp, /* Output buffer */
  113689. char *aTmp, /* Temporary buffer space */
  113690. int nRight, /* Maximum difference in token positions */
  113691. int nLeft, /* Maximum difference in token positions */
  113692. char **pp1, /* IN/OUT: Left input list */
  113693. char **pp2 /* IN/OUT: Right input list */
  113694. ){
  113695. char *p1 = *pp1;
  113696. char *p2 = *pp2;
  113697. char *pTmp1 = aTmp;
  113698. char *pTmp2;
  113699. char *aTmp2;
  113700. int res = 1;
  113701. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  113702. aTmp2 = pTmp2 = pTmp1;
  113703. *pp1 = p1;
  113704. *pp2 = p2;
  113705. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  113706. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  113707. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  113708. }else if( pTmp1!=aTmp ){
  113709. fts3PoslistCopy(pp, &aTmp);
  113710. }else if( pTmp2!=aTmp2 ){
  113711. fts3PoslistCopy(pp, &aTmp2);
  113712. }else{
  113713. res = 0;
  113714. }
  113715. return res;
  113716. }
  113717. /*
  113718. ** An instance of this function is used to merge together the (potentially
  113719. ** large number of) doclists for each term that matches a prefix query.
  113720. ** See function fts3TermSelectMerge() for details.
  113721. */
  113722. typedef struct TermSelect TermSelect;
  113723. struct TermSelect {
  113724. char *aaOutput[16]; /* Malloc'd output buffers */
  113725. int anOutput[16]; /* Size each output buffer in bytes */
  113726. };
  113727. /*
  113728. ** This function is used to read a single varint from a buffer. Parameter
  113729. ** pEnd points 1 byte past the end of the buffer. When this function is
  113730. ** called, if *pp points to pEnd or greater, then the end of the buffer
  113731. ** has been reached. In this case *pp is set to 0 and the function returns.
  113732. **
  113733. ** If *pp does not point to or past pEnd, then a single varint is read
  113734. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  113735. **
  113736. ** If bDescIdx is false, the value read is added to *pVal before returning.
  113737. ** If it is true, the value read is subtracted from *pVal before this
  113738. ** function returns.
  113739. */
  113740. static void fts3GetDeltaVarint3(
  113741. char **pp, /* IN/OUT: Point to read varint from */
  113742. char *pEnd, /* End of buffer */
  113743. int bDescIdx, /* True if docids are descending */
  113744. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  113745. ){
  113746. if( *pp>=pEnd ){
  113747. *pp = 0;
  113748. }else{
  113749. sqlite3_int64 iVal;
  113750. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  113751. if( bDescIdx ){
  113752. *pVal -= iVal;
  113753. }else{
  113754. *pVal += iVal;
  113755. }
  113756. }
  113757. }
  113758. /*
  113759. ** This function is used to write a single varint to a buffer. The varint
  113760. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  113761. ** end of the value written.
  113762. **
  113763. ** If *pbFirst is zero when this function is called, the value written to
  113764. ** the buffer is that of parameter iVal.
  113765. **
  113766. ** If *pbFirst is non-zero when this function is called, then the value
  113767. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  113768. ** (if bDescIdx is non-zero).
  113769. **
  113770. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  113771. ** to the value of parameter iVal.
  113772. */
  113773. static void fts3PutDeltaVarint3(
  113774. char **pp, /* IN/OUT: Output pointer */
  113775. int bDescIdx, /* True for descending docids */
  113776. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  113777. int *pbFirst, /* IN/OUT: True after first int written */
  113778. sqlite3_int64 iVal /* Write this value to the list */
  113779. ){
  113780. sqlite3_int64 iWrite;
  113781. if( bDescIdx==0 || *pbFirst==0 ){
  113782. iWrite = iVal - *piPrev;
  113783. }else{
  113784. iWrite = *piPrev - iVal;
  113785. }
  113786. assert( *pbFirst || *piPrev==0 );
  113787. assert( *pbFirst==0 || iWrite>0 );
  113788. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  113789. *piPrev = iVal;
  113790. *pbFirst = 1;
  113791. }
  113792. /*
  113793. ** This macro is used by various functions that merge doclists. The two
  113794. ** arguments are 64-bit docid values. If the value of the stack variable
  113795. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  113796. ** Otherwise, (i2-i1).
  113797. **
  113798. ** Using this makes it easier to write code that can merge doclists that are
  113799. ** sorted in either ascending or descending order.
  113800. */
  113801. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  113802. /*
  113803. ** This function does an "OR" merge of two doclists (output contains all
  113804. ** positions contained in either argument doclist). If the docids in the
  113805. ** input doclists are sorted in ascending order, parameter bDescDoclist
  113806. ** should be false. If they are sorted in ascending order, it should be
  113807. ** passed a non-zero value.
  113808. **
  113809. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  113810. ** containing the output doclist and SQLITE_OK is returned. In this case
  113811. ** *pnOut is set to the number of bytes in the output doclist.
  113812. **
  113813. ** If an error occurs, an SQLite error code is returned. The output values
  113814. ** are undefined in this case.
  113815. */
  113816. static int fts3DoclistOrMerge(
  113817. int bDescDoclist, /* True if arguments are desc */
  113818. char *a1, int n1, /* First doclist */
  113819. char *a2, int n2, /* Second doclist */
  113820. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  113821. ){
  113822. sqlite3_int64 i1 = 0;
  113823. sqlite3_int64 i2 = 0;
  113824. sqlite3_int64 iPrev = 0;
  113825. char *pEnd1 = &a1[n1];
  113826. char *pEnd2 = &a2[n2];
  113827. char *p1 = a1;
  113828. char *p2 = a2;
  113829. char *p;
  113830. char *aOut;
  113831. int bFirstOut = 0;
  113832. *paOut = 0;
  113833. *pnOut = 0;
  113834. /* Allocate space for the output. Both the input and output doclists
  113835. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  113836. ** then the first docid in each list is simply encoded as a varint. For
  113837. ** each subsequent docid, the varint stored is the difference between the
  113838. ** current and previous docid (a positive number - since the list is in
  113839. ** ascending order).
  113840. **
  113841. ** The first docid written to the output is therefore encoded using the
  113842. ** same number of bytes as it is in whichever of the input lists it is
  113843. ** read from. And each subsequent docid read from the same input list
  113844. ** consumes either the same or less bytes as it did in the input (since
  113845. ** the difference between it and the previous value in the output must
  113846. ** be a positive value less than or equal to the delta value read from
  113847. ** the input list). The same argument applies to all but the first docid
  113848. ** read from the 'other' list. And to the contents of all position lists
  113849. ** that will be copied and merged from the input to the output.
  113850. **
  113851. ** However, if the first docid copied to the output is a negative number,
  113852. ** then the encoding of the first docid from the 'other' input list may
  113853. ** be larger in the output than it was in the input (since the delta value
  113854. ** may be a larger positive integer than the actual docid).
  113855. **
  113856. ** The space required to store the output is therefore the sum of the
  113857. ** sizes of the two inputs, plus enough space for exactly one of the input
  113858. ** docids to grow.
  113859. **
  113860. ** A symetric argument may be made if the doclists are in descending
  113861. ** order.
  113862. */
  113863. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  113864. if( !aOut ) return SQLITE_NOMEM;
  113865. p = aOut;
  113866. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  113867. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  113868. while( p1 || p2 ){
  113869. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  113870. if( p2 && p1 && iDiff==0 ){
  113871. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  113872. fts3PoslistMerge(&p, &p1, &p2);
  113873. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  113874. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  113875. }else if( !p2 || (p1 && iDiff<0) ){
  113876. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  113877. fts3PoslistCopy(&p, &p1);
  113878. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  113879. }else{
  113880. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  113881. fts3PoslistCopy(&p, &p2);
  113882. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  113883. }
  113884. }
  113885. *paOut = aOut;
  113886. *pnOut = (int)(p-aOut);
  113887. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  113888. return SQLITE_OK;
  113889. }
  113890. /*
  113891. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  113892. ** the output contains a copy of each position from the right-hand input
  113893. ** doclist for which there is a position in the left-hand input doclist
  113894. ** exactly nDist tokens before it.
  113895. **
  113896. ** If the docids in the input doclists are sorted in ascending order,
  113897. ** parameter bDescDoclist should be false. If they are sorted in ascending
  113898. ** order, it should be passed a non-zero value.
  113899. **
  113900. ** The right-hand input doclist is overwritten by this function.
  113901. */
  113902. static void fts3DoclistPhraseMerge(
  113903. int bDescDoclist, /* True if arguments are desc */
  113904. int nDist, /* Distance from left to right (1=adjacent) */
  113905. char *aLeft, int nLeft, /* Left doclist */
  113906. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  113907. ){
  113908. sqlite3_int64 i1 = 0;
  113909. sqlite3_int64 i2 = 0;
  113910. sqlite3_int64 iPrev = 0;
  113911. char *pEnd1 = &aLeft[nLeft];
  113912. char *pEnd2 = &aRight[*pnRight];
  113913. char *p1 = aLeft;
  113914. char *p2 = aRight;
  113915. char *p;
  113916. int bFirstOut = 0;
  113917. char *aOut = aRight;
  113918. assert( nDist>0 );
  113919. p = aOut;
  113920. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  113921. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  113922. while( p1 && p2 ){
  113923. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  113924. if( iDiff==0 ){
  113925. char *pSave = p;
  113926. sqlite3_int64 iPrevSave = iPrev;
  113927. int bFirstOutSave = bFirstOut;
  113928. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  113929. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  113930. p = pSave;
  113931. iPrev = iPrevSave;
  113932. bFirstOut = bFirstOutSave;
  113933. }
  113934. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  113935. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  113936. }else if( iDiff<0 ){
  113937. fts3PoslistCopy(0, &p1);
  113938. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  113939. }else{
  113940. fts3PoslistCopy(0, &p2);
  113941. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  113942. }
  113943. }
  113944. *pnRight = (int)(p - aOut);
  113945. }
  113946. /*
  113947. ** Argument pList points to a position list nList bytes in size. This
  113948. ** function checks to see if the position list contains any entries for
  113949. ** a token in position 0 (of any column). If so, it writes argument iDelta
  113950. ** to the output buffer pOut, followed by a position list consisting only
  113951. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  113952. ** The value returned is the number of bytes written to pOut (if any).
  113953. */
  113954. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  113955. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  113956. char *pList, /* Position list (no 0x00 term) */
  113957. int nList, /* Size of pList in bytes */
  113958. char *pOut /* Write output here */
  113959. ){
  113960. int nOut = 0;
  113961. int bWritten = 0; /* True once iDelta has been written */
  113962. char *p = pList;
  113963. char *pEnd = &pList[nList];
  113964. if( *p!=0x01 ){
  113965. if( *p==0x02 ){
  113966. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  113967. pOut[nOut++] = 0x02;
  113968. bWritten = 1;
  113969. }
  113970. fts3ColumnlistCopy(0, &p);
  113971. }
  113972. while( p<pEnd && *p==0x01 ){
  113973. sqlite3_int64 iCol;
  113974. p++;
  113975. p += sqlite3Fts3GetVarint(p, &iCol);
  113976. if( *p==0x02 ){
  113977. if( bWritten==0 ){
  113978. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  113979. bWritten = 1;
  113980. }
  113981. pOut[nOut++] = 0x01;
  113982. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  113983. pOut[nOut++] = 0x02;
  113984. }
  113985. fts3ColumnlistCopy(0, &p);
  113986. }
  113987. if( bWritten ){
  113988. pOut[nOut++] = 0x00;
  113989. }
  113990. return nOut;
  113991. }
  113992. /*
  113993. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  113994. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  113995. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  113996. **
  113997. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  113998. ** the responsibility of the caller to free any doclists left in the
  113999. ** TermSelect.aaOutput[] array.
  114000. */
  114001. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  114002. char *aOut = 0;
  114003. int nOut = 0;
  114004. int i;
  114005. /* Loop through the doclists in the aaOutput[] array. Merge them all
  114006. ** into a single doclist.
  114007. */
  114008. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  114009. if( pTS->aaOutput[i] ){
  114010. if( !aOut ){
  114011. aOut = pTS->aaOutput[i];
  114012. nOut = pTS->anOutput[i];
  114013. pTS->aaOutput[i] = 0;
  114014. }else{
  114015. int nNew;
  114016. char *aNew;
  114017. int rc = fts3DoclistOrMerge(p->bDescIdx,
  114018. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  114019. );
  114020. if( rc!=SQLITE_OK ){
  114021. sqlite3_free(aOut);
  114022. return rc;
  114023. }
  114024. sqlite3_free(pTS->aaOutput[i]);
  114025. sqlite3_free(aOut);
  114026. pTS->aaOutput[i] = 0;
  114027. aOut = aNew;
  114028. nOut = nNew;
  114029. }
  114030. }
  114031. }
  114032. pTS->aaOutput[0] = aOut;
  114033. pTS->anOutput[0] = nOut;
  114034. return SQLITE_OK;
  114035. }
  114036. /*
  114037. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  114038. ** as the first argument. The merge is an "OR" merge (see function
  114039. ** fts3DoclistOrMerge() for details).
  114040. **
  114041. ** This function is called with the doclist for each term that matches
  114042. ** a queried prefix. It merges all these doclists into one, the doclist
  114043. ** for the specified prefix. Since there can be a very large number of
  114044. ** doclists to merge, the merging is done pair-wise using the TermSelect
  114045. ** object.
  114046. **
  114047. ** This function returns SQLITE_OK if the merge is successful, or an
  114048. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  114049. */
  114050. static int fts3TermSelectMerge(
  114051. Fts3Table *p, /* FTS table handle */
  114052. TermSelect *pTS, /* TermSelect object to merge into */
  114053. char *aDoclist, /* Pointer to doclist */
  114054. int nDoclist /* Size of aDoclist in bytes */
  114055. ){
  114056. if( pTS->aaOutput[0]==0 ){
  114057. /* If this is the first term selected, copy the doclist to the output
  114058. ** buffer using memcpy(). */
  114059. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  114060. pTS->anOutput[0] = nDoclist;
  114061. if( pTS->aaOutput[0] ){
  114062. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  114063. }else{
  114064. return SQLITE_NOMEM;
  114065. }
  114066. }else{
  114067. char *aMerge = aDoclist;
  114068. int nMerge = nDoclist;
  114069. int iOut;
  114070. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  114071. if( pTS->aaOutput[iOut]==0 ){
  114072. assert( iOut>0 );
  114073. pTS->aaOutput[iOut] = aMerge;
  114074. pTS->anOutput[iOut] = nMerge;
  114075. break;
  114076. }else{
  114077. char *aNew;
  114078. int nNew;
  114079. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  114080. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  114081. );
  114082. if( rc!=SQLITE_OK ){
  114083. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  114084. return rc;
  114085. }
  114086. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  114087. sqlite3_free(pTS->aaOutput[iOut]);
  114088. pTS->aaOutput[iOut] = 0;
  114089. aMerge = aNew;
  114090. nMerge = nNew;
  114091. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  114092. pTS->aaOutput[iOut] = aMerge;
  114093. pTS->anOutput[iOut] = nMerge;
  114094. }
  114095. }
  114096. }
  114097. }
  114098. return SQLITE_OK;
  114099. }
  114100. /*
  114101. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  114102. */
  114103. static int fts3SegReaderCursorAppend(
  114104. Fts3MultiSegReader *pCsr,
  114105. Fts3SegReader *pNew
  114106. ){
  114107. if( (pCsr->nSegment%16)==0 ){
  114108. Fts3SegReader **apNew;
  114109. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  114110. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  114111. if( !apNew ){
  114112. sqlite3Fts3SegReaderFree(pNew);
  114113. return SQLITE_NOMEM;
  114114. }
  114115. pCsr->apSegment = apNew;
  114116. }
  114117. pCsr->apSegment[pCsr->nSegment++] = pNew;
  114118. return SQLITE_OK;
  114119. }
  114120. /*
  114121. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  114122. ** 8th argument.
  114123. **
  114124. ** This function returns SQLITE_OK if successful, or an SQLite error code
  114125. ** otherwise.
  114126. */
  114127. static int fts3SegReaderCursor(
  114128. Fts3Table *p, /* FTS3 table handle */
  114129. int iLangid, /* Language id */
  114130. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  114131. int iLevel, /* Level of segments to scan */
  114132. const char *zTerm, /* Term to query for */
  114133. int nTerm, /* Size of zTerm in bytes */
  114134. int isPrefix, /* True for a prefix search */
  114135. int isScan, /* True to scan from zTerm to EOF */
  114136. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  114137. ){
  114138. int rc = SQLITE_OK; /* Error code */
  114139. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  114140. int rc2; /* Result of sqlite3_reset() */
  114141. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  114142. ** for the pending-terms. If this is a scan, then this call must be being
  114143. ** made by an fts4aux module, not an FTS table. In this case calling
  114144. ** Fts3SegReaderPending might segfault, as the data structures used by
  114145. ** fts4aux are not completely populated. So it's easiest to filter these
  114146. ** calls out here. */
  114147. if( iLevel<0 && p->aIndex ){
  114148. Fts3SegReader *pSeg = 0;
  114149. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  114150. if( rc==SQLITE_OK && pSeg ){
  114151. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  114152. }
  114153. }
  114154. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  114155. if( rc==SQLITE_OK ){
  114156. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  114157. }
  114158. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  114159. Fts3SegReader *pSeg = 0;
  114160. /* Read the values returned by the SELECT into local variables. */
  114161. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  114162. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  114163. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  114164. int nRoot = sqlite3_column_bytes(pStmt, 4);
  114165. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  114166. /* If zTerm is not NULL, and this segment is not stored entirely on its
  114167. ** root node, the range of leaves scanned can be reduced. Do this. */
  114168. if( iStartBlock && zTerm ){
  114169. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  114170. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  114171. if( rc!=SQLITE_OK ) goto finished;
  114172. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  114173. }
  114174. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  114175. (isPrefix==0 && isScan==0),
  114176. iStartBlock, iLeavesEndBlock,
  114177. iEndBlock, zRoot, nRoot, &pSeg
  114178. );
  114179. if( rc!=SQLITE_OK ) goto finished;
  114180. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  114181. }
  114182. }
  114183. finished:
  114184. rc2 = sqlite3_reset(pStmt);
  114185. if( rc==SQLITE_DONE ) rc = rc2;
  114186. return rc;
  114187. }
  114188. /*
  114189. ** Set up a cursor object for iterating through a full-text index or a
  114190. ** single level therein.
  114191. */
  114192. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  114193. Fts3Table *p, /* FTS3 table handle */
  114194. int iLangid, /* Language-id to search */
  114195. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  114196. int iLevel, /* Level of segments to scan */
  114197. const char *zTerm, /* Term to query for */
  114198. int nTerm, /* Size of zTerm in bytes */
  114199. int isPrefix, /* True for a prefix search */
  114200. int isScan, /* True to scan from zTerm to EOF */
  114201. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  114202. ){
  114203. assert( iIndex>=0 && iIndex<p->nIndex );
  114204. assert( iLevel==FTS3_SEGCURSOR_ALL
  114205. || iLevel==FTS3_SEGCURSOR_PENDING
  114206. || iLevel>=0
  114207. );
  114208. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  114209. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  114210. assert( isPrefix==0 || isScan==0 );
  114211. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  114212. return fts3SegReaderCursor(
  114213. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  114214. );
  114215. }
  114216. /*
  114217. ** In addition to its current configuration, have the Fts3MultiSegReader
  114218. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  114219. **
  114220. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  114221. */
  114222. static int fts3SegReaderCursorAddZero(
  114223. Fts3Table *p, /* FTS virtual table handle */
  114224. int iLangid,
  114225. const char *zTerm, /* Term to scan doclist of */
  114226. int nTerm, /* Number of bytes in zTerm */
  114227. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  114228. ){
  114229. return fts3SegReaderCursor(p,
  114230. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  114231. );
  114232. }
  114233. /*
  114234. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  114235. ** if isPrefix is true, to scan the doclist for all terms for which
  114236. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  114237. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  114238. ** an SQLite error code.
  114239. **
  114240. ** It is the responsibility of the caller to free this object by eventually
  114241. ** passing it to fts3SegReaderCursorFree()
  114242. **
  114243. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  114244. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  114245. */
  114246. static int fts3TermSegReaderCursor(
  114247. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  114248. const char *zTerm, /* Term to query for */
  114249. int nTerm, /* Size of zTerm in bytes */
  114250. int isPrefix, /* True for a prefix search */
  114251. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  114252. ){
  114253. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  114254. int rc = SQLITE_NOMEM; /* Return code */
  114255. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  114256. if( pSegcsr ){
  114257. int i;
  114258. int bFound = 0; /* True once an index has been found */
  114259. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  114260. if( isPrefix ){
  114261. for(i=1; bFound==0 && i<p->nIndex; i++){
  114262. if( p->aIndex[i].nPrefix==nTerm ){
  114263. bFound = 1;
  114264. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  114265. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  114266. );
  114267. pSegcsr->bLookup = 1;
  114268. }
  114269. }
  114270. for(i=1; bFound==0 && i<p->nIndex; i++){
  114271. if( p->aIndex[i].nPrefix==nTerm+1 ){
  114272. bFound = 1;
  114273. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  114274. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  114275. );
  114276. if( rc==SQLITE_OK ){
  114277. rc = fts3SegReaderCursorAddZero(
  114278. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  114279. );
  114280. }
  114281. }
  114282. }
  114283. }
  114284. if( bFound==0 ){
  114285. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  114286. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  114287. );
  114288. pSegcsr->bLookup = !isPrefix;
  114289. }
  114290. }
  114291. *ppSegcsr = pSegcsr;
  114292. return rc;
  114293. }
  114294. /*
  114295. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  114296. */
  114297. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  114298. sqlite3Fts3SegReaderFinish(pSegcsr);
  114299. sqlite3_free(pSegcsr);
  114300. }
  114301. /*
  114302. ** This function retrieves the doclist for the specified term (or term
  114303. ** prefix) from the database.
  114304. */
  114305. static int fts3TermSelect(
  114306. Fts3Table *p, /* Virtual table handle */
  114307. Fts3PhraseToken *pTok, /* Token to query for */
  114308. int iColumn, /* Column to query (or -ve for all columns) */
  114309. int *pnOut, /* OUT: Size of buffer at *ppOut */
  114310. char **ppOut /* OUT: Malloced result buffer */
  114311. ){
  114312. int rc; /* Return code */
  114313. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  114314. TermSelect tsc; /* Object for pair-wise doclist merging */
  114315. Fts3SegFilter filter; /* Segment term filter configuration */
  114316. pSegcsr = pTok->pSegcsr;
  114317. memset(&tsc, 0, sizeof(TermSelect));
  114318. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  114319. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  114320. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  114321. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  114322. filter.iCol = iColumn;
  114323. filter.zTerm = pTok->z;
  114324. filter.nTerm = pTok->n;
  114325. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  114326. while( SQLITE_OK==rc
  114327. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  114328. ){
  114329. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  114330. }
  114331. if( rc==SQLITE_OK ){
  114332. rc = fts3TermSelectFinishMerge(p, &tsc);
  114333. }
  114334. if( rc==SQLITE_OK ){
  114335. *ppOut = tsc.aaOutput[0];
  114336. *pnOut = tsc.anOutput[0];
  114337. }else{
  114338. int i;
  114339. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  114340. sqlite3_free(tsc.aaOutput[i]);
  114341. }
  114342. }
  114343. fts3SegReaderCursorFree(pSegcsr);
  114344. pTok->pSegcsr = 0;
  114345. return rc;
  114346. }
  114347. /*
  114348. ** This function counts the total number of docids in the doclist stored
  114349. ** in buffer aList[], size nList bytes.
  114350. **
  114351. ** If the isPoslist argument is true, then it is assumed that the doclist
  114352. ** contains a position-list following each docid. Otherwise, it is assumed
  114353. ** that the doclist is simply a list of docids stored as delta encoded
  114354. ** varints.
  114355. */
  114356. static int fts3DoclistCountDocids(char *aList, int nList){
  114357. int nDoc = 0; /* Return value */
  114358. if( aList ){
  114359. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  114360. char *p = aList; /* Cursor */
  114361. while( p<aEnd ){
  114362. nDoc++;
  114363. while( (*p++)&0x80 ); /* Skip docid varint */
  114364. fts3PoslistCopy(0, &p); /* Skip over position list */
  114365. }
  114366. }
  114367. return nDoc;
  114368. }
  114369. /*
  114370. ** Advance the cursor to the next row in the %_content table that
  114371. ** matches the search criteria. For a MATCH search, this will be
  114372. ** the next row that matches. For a full-table scan, this will be
  114373. ** simply the next row in the %_content table. For a docid lookup,
  114374. ** this routine simply sets the EOF flag.
  114375. **
  114376. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  114377. ** even if we reach end-of-file. The fts3EofMethod() will be called
  114378. ** subsequently to determine whether or not an EOF was hit.
  114379. */
  114380. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  114381. int rc;
  114382. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  114383. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  114384. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  114385. pCsr->isEof = 1;
  114386. rc = sqlite3_reset(pCsr->pStmt);
  114387. }else{
  114388. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  114389. rc = SQLITE_OK;
  114390. }
  114391. }else{
  114392. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  114393. }
  114394. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  114395. return rc;
  114396. }
  114397. /*
  114398. ** This is the xFilter interface for the virtual table. See
  114399. ** the virtual table xFilter method documentation for additional
  114400. ** information.
  114401. **
  114402. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  114403. ** the %_content table.
  114404. **
  114405. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  114406. ** in the %_content table.
  114407. **
  114408. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  114409. ** column on the left-hand side of the MATCH operator is column
  114410. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  114411. ** side of the MATCH operator.
  114412. */
  114413. static int fts3FilterMethod(
  114414. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  114415. int idxNum, /* Strategy index */
  114416. const char *idxStr, /* Unused */
  114417. int nVal, /* Number of elements in apVal */
  114418. sqlite3_value **apVal /* Arguments for the indexing scheme */
  114419. ){
  114420. int rc;
  114421. char *zSql; /* SQL statement used to access %_content */
  114422. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  114423. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  114424. UNUSED_PARAMETER(idxStr);
  114425. UNUSED_PARAMETER(nVal);
  114426. assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  114427. assert( nVal==0 || nVal==1 || nVal==2 );
  114428. assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
  114429. assert( p->pSegments==0 );
  114430. /* In case the cursor has been used before, clear it now. */
  114431. sqlite3_finalize(pCsr->pStmt);
  114432. sqlite3_free(pCsr->aDoclist);
  114433. sqlite3Fts3ExprFree(pCsr->pExpr);
  114434. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  114435. if( idxStr ){
  114436. pCsr->bDesc = (idxStr[0]=='D');
  114437. }else{
  114438. pCsr->bDesc = p->bDescIdx;
  114439. }
  114440. pCsr->eSearch = (i16)idxNum;
  114441. if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
  114442. int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
  114443. const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
  114444. if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  114445. return SQLITE_NOMEM;
  114446. }
  114447. pCsr->iLangid = 0;
  114448. if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
  114449. assert( p->base.zErrMsg==0 );
  114450. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  114451. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  114452. &p->base.zErrMsg
  114453. );
  114454. if( rc!=SQLITE_OK ){
  114455. return rc;
  114456. }
  114457. rc = sqlite3Fts3ReadLock(p);
  114458. if( rc!=SQLITE_OK ) return rc;
  114459. rc = fts3EvalStart(pCsr);
  114460. sqlite3Fts3SegmentsClose(p);
  114461. if( rc!=SQLITE_OK ) return rc;
  114462. pCsr->pNextId = pCsr->aDoclist;
  114463. pCsr->iPrevId = 0;
  114464. }
  114465. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  114466. ** statement loops through all rows of the %_content table. For a
  114467. ** full-text query or docid lookup, the statement retrieves a single
  114468. ** row by docid.
  114469. */
  114470. if( idxNum==FTS3_FULLSCAN_SEARCH ){
  114471. zSql = sqlite3_mprintf(
  114472. "SELECT %s ORDER BY rowid %s",
  114473. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  114474. );
  114475. if( zSql ){
  114476. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  114477. sqlite3_free(zSql);
  114478. }else{
  114479. rc = SQLITE_NOMEM;
  114480. }
  114481. }else if( idxNum==FTS3_DOCID_SEARCH ){
  114482. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  114483. if( rc==SQLITE_OK ){
  114484. rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  114485. }
  114486. }
  114487. if( rc!=SQLITE_OK ) return rc;
  114488. return fts3NextMethod(pCursor);
  114489. }
  114490. /*
  114491. ** This is the xEof method of the virtual table. SQLite calls this
  114492. ** routine to find out if it has reached the end of a result set.
  114493. */
  114494. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  114495. return ((Fts3Cursor *)pCursor)->isEof;
  114496. }
  114497. /*
  114498. ** This is the xRowid method. The SQLite core calls this routine to
  114499. ** retrieve the rowid for the current row of the result set. fts3
  114500. ** exposes %_content.docid as the rowid for the virtual table. The
  114501. ** rowid should be written to *pRowid.
  114502. */
  114503. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  114504. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  114505. *pRowid = pCsr->iPrevId;
  114506. return SQLITE_OK;
  114507. }
  114508. /*
  114509. ** This is the xColumn method, called by SQLite to request a value from
  114510. ** the row that the supplied cursor currently points to.
  114511. **
  114512. ** If:
  114513. **
  114514. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  114515. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  114516. ** (iCol == p->nColumn+1) -> Docid column
  114517. ** (iCol == p->nColumn+2) -> Langid column
  114518. */
  114519. static int fts3ColumnMethod(
  114520. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  114521. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  114522. int iCol /* Index of column to read value from */
  114523. ){
  114524. int rc = SQLITE_OK; /* Return Code */
  114525. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  114526. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  114527. /* The column value supplied by SQLite must be in range. */
  114528. assert( iCol>=0 && iCol<=p->nColumn+2 );
  114529. if( iCol==p->nColumn+1 ){
  114530. /* This call is a request for the "docid" column. Since "docid" is an
  114531. ** alias for "rowid", use the xRowid() method to obtain the value.
  114532. */
  114533. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  114534. }else if( iCol==p->nColumn ){
  114535. /* The extra column whose name is the same as the table.
  114536. ** Return a blob which is a pointer to the cursor. */
  114537. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  114538. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  114539. sqlite3_result_int64(pCtx, pCsr->iLangid);
  114540. }else{
  114541. /* The requested column is either a user column (one that contains
  114542. ** indexed data), or the language-id column. */
  114543. rc = fts3CursorSeek(0, pCsr);
  114544. if( rc==SQLITE_OK ){
  114545. if( iCol==p->nColumn+2 ){
  114546. int iLangid = 0;
  114547. if( p->zLanguageid ){
  114548. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  114549. }
  114550. sqlite3_result_int(pCtx, iLangid);
  114551. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  114552. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  114553. }
  114554. }
  114555. }
  114556. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  114557. return rc;
  114558. }
  114559. /*
  114560. ** This function is the implementation of the xUpdate callback used by
  114561. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  114562. ** inserted, updated or deleted.
  114563. */
  114564. static int fts3UpdateMethod(
  114565. sqlite3_vtab *pVtab, /* Virtual table handle */
  114566. int nArg, /* Size of argument array */
  114567. sqlite3_value **apVal, /* Array of arguments */
  114568. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  114569. ){
  114570. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  114571. }
  114572. /*
  114573. ** Implementation of xSync() method. Flush the contents of the pending-terms
  114574. ** hash-table to the database.
  114575. */
  114576. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  114577. /* Following an incremental-merge operation, assuming that the input
  114578. ** segments are not completely consumed (the usual case), they are updated
  114579. ** in place to remove the entries that have already been merged. This
  114580. ** involves updating the leaf block that contains the smallest unmerged
  114581. ** entry and each block (if any) between the leaf and the root node. So
  114582. ** if the height of the input segment b-trees is N, and input segments
  114583. ** are merged eight at a time, updating the input segments at the end
  114584. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  114585. ** small - often between 0 and 2. So the overhead of the incremental
  114586. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  114587. ** dwarfing the actual productive work accomplished, the incremental merge
  114588. ** is only attempted if it will write at least 64 leaf blocks. Hence
  114589. ** nMinMerge.
  114590. **
  114591. ** Of course, updating the input segments also involves deleting a bunch
  114592. ** of blocks from the segments table. But this is not considered overhead
  114593. ** as it would also be required by a crisis-merge that used the same input
  114594. ** segments.
  114595. */
  114596. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  114597. Fts3Table *p = (Fts3Table*)pVtab;
  114598. int rc = sqlite3Fts3PendingTermsFlush(p);
  114599. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  114600. int mxLevel = 0; /* Maximum relative level value in db */
  114601. int A; /* Incr-merge parameter A */
  114602. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  114603. assert( rc==SQLITE_OK || mxLevel==0 );
  114604. A = p->nLeafAdd * mxLevel;
  114605. A += (A/2);
  114606. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  114607. }
  114608. sqlite3Fts3SegmentsClose(p);
  114609. return rc;
  114610. }
  114611. /*
  114612. ** Implementation of xBegin() method. This is a no-op.
  114613. */
  114614. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  114615. Fts3Table *p = (Fts3Table*)pVtab;
  114616. UNUSED_PARAMETER(pVtab);
  114617. assert( p->pSegments==0 );
  114618. assert( p->nPendingData==0 );
  114619. assert( p->inTransaction!=1 );
  114620. TESTONLY( p->inTransaction = 1 );
  114621. TESTONLY( p->mxSavepoint = -1; );
  114622. p->nLeafAdd = 0;
  114623. return SQLITE_OK;
  114624. }
  114625. /*
  114626. ** Implementation of xCommit() method. This is a no-op. The contents of
  114627. ** the pending-terms hash-table have already been flushed into the database
  114628. ** by fts3SyncMethod().
  114629. */
  114630. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  114631. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  114632. UNUSED_PARAMETER(pVtab);
  114633. assert( p->nPendingData==0 );
  114634. assert( p->inTransaction!=0 );
  114635. assert( p->pSegments==0 );
  114636. TESTONLY( p->inTransaction = 0 );
  114637. TESTONLY( p->mxSavepoint = -1; );
  114638. return SQLITE_OK;
  114639. }
  114640. /*
  114641. ** Implementation of xRollback(). Discard the contents of the pending-terms
  114642. ** hash-table. Any changes made to the database are reverted by SQLite.
  114643. */
  114644. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  114645. Fts3Table *p = (Fts3Table*)pVtab;
  114646. sqlite3Fts3PendingTermsClear(p);
  114647. assert( p->inTransaction!=0 );
  114648. TESTONLY( p->inTransaction = 0 );
  114649. TESTONLY( p->mxSavepoint = -1; );
  114650. return SQLITE_OK;
  114651. }
  114652. /*
  114653. ** When called, *ppPoslist must point to the byte immediately following the
  114654. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  114655. ** moves *ppPoslist so that it instead points to the first byte of the
  114656. ** same position list.
  114657. */
  114658. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  114659. char *p = &(*ppPoslist)[-2];
  114660. char c = 0;
  114661. while( p>pStart && (c=*p--)==0 );
  114662. while( p>pStart && (*p & 0x80) | c ){
  114663. c = *p--;
  114664. }
  114665. if( p>pStart ){ p = &p[2]; }
  114666. while( *p++&0x80 );
  114667. *ppPoslist = p;
  114668. }
  114669. /*
  114670. ** Helper function used by the implementation of the overloaded snippet(),
  114671. ** offsets() and optimize() SQL functions.
  114672. **
  114673. ** If the value passed as the third argument is a blob of size
  114674. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  114675. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  114676. ** message is written to context pContext and SQLITE_ERROR returned. The
  114677. ** string passed via zFunc is used as part of the error message.
  114678. */
  114679. static int fts3FunctionArg(
  114680. sqlite3_context *pContext, /* SQL function call context */
  114681. const char *zFunc, /* Function name */
  114682. sqlite3_value *pVal, /* argv[0] passed to function */
  114683. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  114684. ){
  114685. Fts3Cursor *pRet;
  114686. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  114687. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  114688. ){
  114689. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  114690. sqlite3_result_error(pContext, zErr, -1);
  114691. sqlite3_free(zErr);
  114692. return SQLITE_ERROR;
  114693. }
  114694. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  114695. *ppCsr = pRet;
  114696. return SQLITE_OK;
  114697. }
  114698. /*
  114699. ** Implementation of the snippet() function for FTS3
  114700. */
  114701. static void fts3SnippetFunc(
  114702. sqlite3_context *pContext, /* SQLite function call context */
  114703. int nVal, /* Size of apVal[] array */
  114704. sqlite3_value **apVal /* Array of arguments */
  114705. ){
  114706. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  114707. const char *zStart = "<b>";
  114708. const char *zEnd = "</b>";
  114709. const char *zEllipsis = "<b>...</b>";
  114710. int iCol = -1;
  114711. int nToken = 15; /* Default number of tokens in snippet */
  114712. /* There must be at least one argument passed to this function (otherwise
  114713. ** the non-overloaded version would have been called instead of this one).
  114714. */
  114715. assert( nVal>=1 );
  114716. if( nVal>6 ){
  114717. sqlite3_result_error(pContext,
  114718. "wrong number of arguments to function snippet()", -1);
  114719. return;
  114720. }
  114721. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  114722. switch( nVal ){
  114723. case 6: nToken = sqlite3_value_int(apVal[5]);
  114724. case 5: iCol = sqlite3_value_int(apVal[4]);
  114725. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  114726. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  114727. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  114728. }
  114729. if( !zEllipsis || !zEnd || !zStart ){
  114730. sqlite3_result_error_nomem(pContext);
  114731. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  114732. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  114733. }
  114734. }
  114735. /*
  114736. ** Implementation of the offsets() function for FTS3
  114737. */
  114738. static void fts3OffsetsFunc(
  114739. sqlite3_context *pContext, /* SQLite function call context */
  114740. int nVal, /* Size of argument array */
  114741. sqlite3_value **apVal /* Array of arguments */
  114742. ){
  114743. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  114744. UNUSED_PARAMETER(nVal);
  114745. assert( nVal==1 );
  114746. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  114747. assert( pCsr );
  114748. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  114749. sqlite3Fts3Offsets(pContext, pCsr);
  114750. }
  114751. }
  114752. /*
  114753. ** Implementation of the special optimize() function for FTS3. This
  114754. ** function merges all segments in the database to a single segment.
  114755. ** Example usage is:
  114756. **
  114757. ** SELECT optimize(t) FROM t LIMIT 1;
  114758. **
  114759. ** where 't' is the name of an FTS3 table.
  114760. */
  114761. static void fts3OptimizeFunc(
  114762. sqlite3_context *pContext, /* SQLite function call context */
  114763. int nVal, /* Size of argument array */
  114764. sqlite3_value **apVal /* Array of arguments */
  114765. ){
  114766. int rc; /* Return code */
  114767. Fts3Table *p; /* Virtual table handle */
  114768. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  114769. UNUSED_PARAMETER(nVal);
  114770. assert( nVal==1 );
  114771. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  114772. p = (Fts3Table *)pCursor->base.pVtab;
  114773. assert( p );
  114774. rc = sqlite3Fts3Optimize(p);
  114775. switch( rc ){
  114776. case SQLITE_OK:
  114777. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  114778. break;
  114779. case SQLITE_DONE:
  114780. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  114781. break;
  114782. default:
  114783. sqlite3_result_error_code(pContext, rc);
  114784. break;
  114785. }
  114786. }
  114787. /*
  114788. ** Implementation of the matchinfo() function for FTS3
  114789. */
  114790. static void fts3MatchinfoFunc(
  114791. sqlite3_context *pContext, /* SQLite function call context */
  114792. int nVal, /* Size of argument array */
  114793. sqlite3_value **apVal /* Array of arguments */
  114794. ){
  114795. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  114796. assert( nVal==1 || nVal==2 );
  114797. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  114798. const char *zArg = 0;
  114799. if( nVal>1 ){
  114800. zArg = (const char *)sqlite3_value_text(apVal[1]);
  114801. }
  114802. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  114803. }
  114804. }
  114805. /*
  114806. ** This routine implements the xFindFunction method for the FTS3
  114807. ** virtual table.
  114808. */
  114809. static int fts3FindFunctionMethod(
  114810. sqlite3_vtab *pVtab, /* Virtual table handle */
  114811. int nArg, /* Number of SQL function arguments */
  114812. const char *zName, /* Name of SQL function */
  114813. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  114814. void **ppArg /* Unused */
  114815. ){
  114816. struct Overloaded {
  114817. const char *zName;
  114818. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  114819. } aOverload[] = {
  114820. { "snippet", fts3SnippetFunc },
  114821. { "offsets", fts3OffsetsFunc },
  114822. { "optimize", fts3OptimizeFunc },
  114823. { "matchinfo", fts3MatchinfoFunc },
  114824. };
  114825. int i; /* Iterator variable */
  114826. UNUSED_PARAMETER(pVtab);
  114827. UNUSED_PARAMETER(nArg);
  114828. UNUSED_PARAMETER(ppArg);
  114829. for(i=0; i<SizeofArray(aOverload); i++){
  114830. if( strcmp(zName, aOverload[i].zName)==0 ){
  114831. *pxFunc = aOverload[i].xFunc;
  114832. return 1;
  114833. }
  114834. }
  114835. /* No function of the specified name was found. Return 0. */
  114836. return 0;
  114837. }
  114838. /*
  114839. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  114840. */
  114841. static int fts3RenameMethod(
  114842. sqlite3_vtab *pVtab, /* Virtual table handle */
  114843. const char *zName /* New name of table */
  114844. ){
  114845. Fts3Table *p = (Fts3Table *)pVtab;
  114846. sqlite3 *db = p->db; /* Database connection */
  114847. int rc; /* Return Code */
  114848. /* As it happens, the pending terms table is always empty here. This is
  114849. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  114850. ** always opens a savepoint transaction. And the xSavepoint() method
  114851. ** flushes the pending terms table. But leave the (no-op) call to
  114852. ** PendingTermsFlush() in in case that changes.
  114853. */
  114854. assert( p->nPendingData==0 );
  114855. rc = sqlite3Fts3PendingTermsFlush(p);
  114856. if( p->zContentTbl==0 ){
  114857. fts3DbExec(&rc, db,
  114858. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  114859. p->zDb, p->zName, zName
  114860. );
  114861. }
  114862. if( p->bHasDocsize ){
  114863. fts3DbExec(&rc, db,
  114864. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  114865. p->zDb, p->zName, zName
  114866. );
  114867. }
  114868. if( p->bHasStat ){
  114869. fts3DbExec(&rc, db,
  114870. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  114871. p->zDb, p->zName, zName
  114872. );
  114873. }
  114874. fts3DbExec(&rc, db,
  114875. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  114876. p->zDb, p->zName, zName
  114877. );
  114878. fts3DbExec(&rc, db,
  114879. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  114880. p->zDb, p->zName, zName
  114881. );
  114882. return rc;
  114883. }
  114884. /*
  114885. ** The xSavepoint() method.
  114886. **
  114887. ** Flush the contents of the pending-terms table to disk.
  114888. */
  114889. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  114890. int rc = SQLITE_OK;
  114891. UNUSED_PARAMETER(iSavepoint);
  114892. assert( ((Fts3Table *)pVtab)->inTransaction );
  114893. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  114894. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  114895. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  114896. rc = fts3SyncMethod(pVtab);
  114897. }
  114898. return rc;
  114899. }
  114900. /*
  114901. ** The xRelease() method.
  114902. **
  114903. ** This is a no-op.
  114904. */
  114905. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  114906. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  114907. UNUSED_PARAMETER(iSavepoint);
  114908. UNUSED_PARAMETER(pVtab);
  114909. assert( p->inTransaction );
  114910. assert( p->mxSavepoint >= iSavepoint );
  114911. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  114912. return SQLITE_OK;
  114913. }
  114914. /*
  114915. ** The xRollbackTo() method.
  114916. **
  114917. ** Discard the contents of the pending terms table.
  114918. */
  114919. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  114920. Fts3Table *p = (Fts3Table*)pVtab;
  114921. UNUSED_PARAMETER(iSavepoint);
  114922. assert( p->inTransaction );
  114923. assert( p->mxSavepoint >= iSavepoint );
  114924. TESTONLY( p->mxSavepoint = iSavepoint );
  114925. sqlite3Fts3PendingTermsClear(p);
  114926. return SQLITE_OK;
  114927. }
  114928. static const sqlite3_module fts3Module = {
  114929. /* iVersion */ 2,
  114930. /* xCreate */ fts3CreateMethod,
  114931. /* xConnect */ fts3ConnectMethod,
  114932. /* xBestIndex */ fts3BestIndexMethod,
  114933. /* xDisconnect */ fts3DisconnectMethod,
  114934. /* xDestroy */ fts3DestroyMethod,
  114935. /* xOpen */ fts3OpenMethod,
  114936. /* xClose */ fts3CloseMethod,
  114937. /* xFilter */ fts3FilterMethod,
  114938. /* xNext */ fts3NextMethod,
  114939. /* xEof */ fts3EofMethod,
  114940. /* xColumn */ fts3ColumnMethod,
  114941. /* xRowid */ fts3RowidMethod,
  114942. /* xUpdate */ fts3UpdateMethod,
  114943. /* xBegin */ fts3BeginMethod,
  114944. /* xSync */ fts3SyncMethod,
  114945. /* xCommit */ fts3CommitMethod,
  114946. /* xRollback */ fts3RollbackMethod,
  114947. /* xFindFunction */ fts3FindFunctionMethod,
  114948. /* xRename */ fts3RenameMethod,
  114949. /* xSavepoint */ fts3SavepointMethod,
  114950. /* xRelease */ fts3ReleaseMethod,
  114951. /* xRollbackTo */ fts3RollbackToMethod,
  114952. };
  114953. /*
  114954. ** This function is registered as the module destructor (called when an
  114955. ** FTS3 enabled database connection is closed). It frees the memory
  114956. ** allocated for the tokenizer hash table.
  114957. */
  114958. static void hashDestroy(void *p){
  114959. Fts3Hash *pHash = (Fts3Hash *)p;
  114960. sqlite3Fts3HashClear(pHash);
  114961. sqlite3_free(pHash);
  114962. }
  114963. /*
  114964. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  114965. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  114966. ** respectively. The following three forward declarations are for functions
  114967. ** declared in these files used to retrieve the respective implementations.
  114968. **
  114969. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  114970. ** to by the argument to point to the "simple" tokenizer implementation.
  114971. ** And so on.
  114972. */
  114973. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  114974. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  114975. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  114976. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  114977. #endif
  114978. #ifdef SQLITE_ENABLE_ICU
  114979. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  114980. #endif
  114981. /*
  114982. ** Initialize the fts3 extension. If this extension is built as part
  114983. ** of the sqlite library, then this function is called directly by
  114984. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  114985. ** function is called by the sqlite3_extension_init() entry point.
  114986. */
  114987. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  114988. int rc = SQLITE_OK;
  114989. Fts3Hash *pHash = 0;
  114990. const sqlite3_tokenizer_module *pSimple = 0;
  114991. const sqlite3_tokenizer_module *pPorter = 0;
  114992. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  114993. const sqlite3_tokenizer_module *pUnicode = 0;
  114994. #endif
  114995. #ifdef SQLITE_ENABLE_ICU
  114996. const sqlite3_tokenizer_module *pIcu = 0;
  114997. sqlite3Fts3IcuTokenizerModule(&pIcu);
  114998. #endif
  114999. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  115000. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  115001. #endif
  115002. #ifdef SQLITE_TEST
  115003. rc = sqlite3Fts3InitTerm(db);
  115004. if( rc!=SQLITE_OK ) return rc;
  115005. #endif
  115006. rc = sqlite3Fts3InitAux(db);
  115007. if( rc!=SQLITE_OK ) return rc;
  115008. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  115009. sqlite3Fts3PorterTokenizerModule(&pPorter);
  115010. /* Allocate and initialize the hash-table used to store tokenizers. */
  115011. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  115012. if( !pHash ){
  115013. rc = SQLITE_NOMEM;
  115014. }else{
  115015. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  115016. }
  115017. /* Load the built-in tokenizers into the hash table */
  115018. if( rc==SQLITE_OK ){
  115019. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  115020. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  115021. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  115022. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  115023. #endif
  115024. #ifdef SQLITE_ENABLE_ICU
  115025. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  115026. #endif
  115027. ){
  115028. rc = SQLITE_NOMEM;
  115029. }
  115030. }
  115031. #ifdef SQLITE_TEST
  115032. if( rc==SQLITE_OK ){
  115033. rc = sqlite3Fts3ExprInitTestInterface(db);
  115034. }
  115035. #endif
  115036. /* Create the virtual table wrapper around the hash-table and overload
  115037. ** the two scalar functions. If this is successful, register the
  115038. ** module with sqlite.
  115039. */
  115040. if( SQLITE_OK==rc
  115041. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  115042. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  115043. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  115044. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  115045. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  115046. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  115047. ){
  115048. rc = sqlite3_create_module_v2(
  115049. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  115050. );
  115051. if( rc==SQLITE_OK ){
  115052. rc = sqlite3_create_module_v2(
  115053. db, "fts4", &fts3Module, (void *)pHash, 0
  115054. );
  115055. }
  115056. if( rc==SQLITE_OK ){
  115057. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  115058. }
  115059. return rc;
  115060. }
  115061. /* An error has occurred. Delete the hash table and return the error code. */
  115062. assert( rc!=SQLITE_OK );
  115063. if( pHash ){
  115064. sqlite3Fts3HashClear(pHash);
  115065. sqlite3_free(pHash);
  115066. }
  115067. return rc;
  115068. }
  115069. /*
  115070. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  115071. ** by pExpr.
  115072. **
  115073. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  115074. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  115075. ** Fts3SegReader objects internally to provide an interface to seek or scan
  115076. ** within the union of all segments of a b-tree. Hence the name.
  115077. **
  115078. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  115079. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  115080. ** there exists prefix b-tree of the right length) then it may be traversed
  115081. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  115082. ** doclist and then traversed.
  115083. */
  115084. static void fts3EvalAllocateReaders(
  115085. Fts3Cursor *pCsr, /* FTS cursor handle */
  115086. Fts3Expr *pExpr, /* Allocate readers for this expression */
  115087. int *pnToken, /* OUT: Total number of tokens in phrase. */
  115088. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  115089. int *pRc /* IN/OUT: Error code */
  115090. ){
  115091. if( pExpr && SQLITE_OK==*pRc ){
  115092. if( pExpr->eType==FTSQUERY_PHRASE ){
  115093. int i;
  115094. int nToken = pExpr->pPhrase->nToken;
  115095. *pnToken += nToken;
  115096. for(i=0; i<nToken; i++){
  115097. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  115098. int rc = fts3TermSegReaderCursor(pCsr,
  115099. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  115100. );
  115101. if( rc!=SQLITE_OK ){
  115102. *pRc = rc;
  115103. return;
  115104. }
  115105. }
  115106. assert( pExpr->pPhrase->iDoclistToken==0 );
  115107. pExpr->pPhrase->iDoclistToken = -1;
  115108. }else{
  115109. *pnOr += (pExpr->eType==FTSQUERY_OR);
  115110. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  115111. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  115112. }
  115113. }
  115114. }
  115115. /*
  115116. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  115117. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  115118. **
  115119. ** This function assumes that pList points to a buffer allocated using
  115120. ** sqlite3_malloc(). This function takes responsibility for eventually
  115121. ** freeing the buffer.
  115122. */
  115123. static void fts3EvalPhraseMergeToken(
  115124. Fts3Table *pTab, /* FTS Table pointer */
  115125. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  115126. int iToken, /* Token pList/nList corresponds to */
  115127. char *pList, /* Pointer to doclist */
  115128. int nList /* Number of bytes in pList */
  115129. ){
  115130. assert( iToken!=p->iDoclistToken );
  115131. if( pList==0 ){
  115132. sqlite3_free(p->doclist.aAll);
  115133. p->doclist.aAll = 0;
  115134. p->doclist.nAll = 0;
  115135. }
  115136. else if( p->iDoclistToken<0 ){
  115137. p->doclist.aAll = pList;
  115138. p->doclist.nAll = nList;
  115139. }
  115140. else if( p->doclist.aAll==0 ){
  115141. sqlite3_free(pList);
  115142. }
  115143. else {
  115144. char *pLeft;
  115145. char *pRight;
  115146. int nLeft;
  115147. int nRight;
  115148. int nDiff;
  115149. if( p->iDoclistToken<iToken ){
  115150. pLeft = p->doclist.aAll;
  115151. nLeft = p->doclist.nAll;
  115152. pRight = pList;
  115153. nRight = nList;
  115154. nDiff = iToken - p->iDoclistToken;
  115155. }else{
  115156. pRight = p->doclist.aAll;
  115157. nRight = p->doclist.nAll;
  115158. pLeft = pList;
  115159. nLeft = nList;
  115160. nDiff = p->iDoclistToken - iToken;
  115161. }
  115162. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  115163. sqlite3_free(pLeft);
  115164. p->doclist.aAll = pRight;
  115165. p->doclist.nAll = nRight;
  115166. }
  115167. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  115168. }
  115169. /*
  115170. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  115171. ** does not take deferred tokens into account.
  115172. **
  115173. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  115174. */
  115175. static int fts3EvalPhraseLoad(
  115176. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115177. Fts3Phrase *p /* Phrase object */
  115178. ){
  115179. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  115180. int iToken;
  115181. int rc = SQLITE_OK;
  115182. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  115183. Fts3PhraseToken *pToken = &p->aToken[iToken];
  115184. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  115185. if( pToken->pSegcsr ){
  115186. int nThis = 0;
  115187. char *pThis = 0;
  115188. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  115189. if( rc==SQLITE_OK ){
  115190. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  115191. }
  115192. }
  115193. assert( pToken->pSegcsr==0 );
  115194. }
  115195. return rc;
  115196. }
  115197. /*
  115198. ** This function is called on each phrase after the position lists for
  115199. ** any deferred tokens have been loaded into memory. It updates the phrases
  115200. ** current position list to include only those positions that are really
  115201. ** instances of the phrase (after considering deferred tokens). If this
  115202. ** means that the phrase does not appear in the current row, doclist.pList
  115203. ** and doclist.nList are both zeroed.
  115204. **
  115205. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  115206. */
  115207. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  115208. int iToken; /* Used to iterate through phrase tokens */
  115209. char *aPoslist = 0; /* Position list for deferred tokens */
  115210. int nPoslist = 0; /* Number of bytes in aPoslist */
  115211. int iPrev = -1; /* Token number of previous deferred token */
  115212. assert( pPhrase->doclist.bFreeList==0 );
  115213. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  115214. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  115215. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  115216. if( pDeferred ){
  115217. char *pList;
  115218. int nList;
  115219. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  115220. if( rc!=SQLITE_OK ) return rc;
  115221. if( pList==0 ){
  115222. sqlite3_free(aPoslist);
  115223. pPhrase->doclist.pList = 0;
  115224. pPhrase->doclist.nList = 0;
  115225. return SQLITE_OK;
  115226. }else if( aPoslist==0 ){
  115227. aPoslist = pList;
  115228. nPoslist = nList;
  115229. }else{
  115230. char *aOut = pList;
  115231. char *p1 = aPoslist;
  115232. char *p2 = aOut;
  115233. assert( iPrev>=0 );
  115234. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  115235. sqlite3_free(aPoslist);
  115236. aPoslist = pList;
  115237. nPoslist = (int)(aOut - aPoslist);
  115238. if( nPoslist==0 ){
  115239. sqlite3_free(aPoslist);
  115240. pPhrase->doclist.pList = 0;
  115241. pPhrase->doclist.nList = 0;
  115242. return SQLITE_OK;
  115243. }
  115244. }
  115245. iPrev = iToken;
  115246. }
  115247. }
  115248. if( iPrev>=0 ){
  115249. int nMaxUndeferred = pPhrase->iDoclistToken;
  115250. if( nMaxUndeferred<0 ){
  115251. pPhrase->doclist.pList = aPoslist;
  115252. pPhrase->doclist.nList = nPoslist;
  115253. pPhrase->doclist.iDocid = pCsr->iPrevId;
  115254. pPhrase->doclist.bFreeList = 1;
  115255. }else{
  115256. int nDistance;
  115257. char *p1;
  115258. char *p2;
  115259. char *aOut;
  115260. if( nMaxUndeferred>iPrev ){
  115261. p1 = aPoslist;
  115262. p2 = pPhrase->doclist.pList;
  115263. nDistance = nMaxUndeferred - iPrev;
  115264. }else{
  115265. p1 = pPhrase->doclist.pList;
  115266. p2 = aPoslist;
  115267. nDistance = iPrev - nMaxUndeferred;
  115268. }
  115269. aOut = (char *)sqlite3_malloc(nPoslist+8);
  115270. if( !aOut ){
  115271. sqlite3_free(aPoslist);
  115272. return SQLITE_NOMEM;
  115273. }
  115274. pPhrase->doclist.pList = aOut;
  115275. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  115276. pPhrase->doclist.bFreeList = 1;
  115277. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  115278. }else{
  115279. sqlite3_free(aOut);
  115280. pPhrase->doclist.pList = 0;
  115281. pPhrase->doclist.nList = 0;
  115282. }
  115283. sqlite3_free(aPoslist);
  115284. }
  115285. }
  115286. return SQLITE_OK;
  115287. }
  115288. /*
  115289. ** This function is called for each Fts3Phrase in a full-text query
  115290. ** expression to initialize the mechanism for returning rows. Once this
  115291. ** function has been called successfully on an Fts3Phrase, it may be
  115292. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  115293. **
  115294. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  115295. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  115296. ** memory within this call.
  115297. **
  115298. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  115299. */
  115300. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  115301. int rc; /* Error code */
  115302. Fts3PhraseToken *pFirst = &p->aToken[0];
  115303. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  115304. if( pCsr->bDesc==pTab->bDescIdx
  115305. && bOptOk==1
  115306. && p->nToken==1
  115307. && pFirst->pSegcsr
  115308. && pFirst->pSegcsr->bLookup
  115309. && pFirst->bFirst==0
  115310. ){
  115311. /* Use the incremental approach. */
  115312. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  115313. rc = sqlite3Fts3MsrIncrStart(
  115314. pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
  115315. p->bIncr = 1;
  115316. }else{
  115317. /* Load the full doclist for the phrase into memory. */
  115318. rc = fts3EvalPhraseLoad(pCsr, p);
  115319. p->bIncr = 0;
  115320. }
  115321. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  115322. return rc;
  115323. }
  115324. /*
  115325. ** This function is used to iterate backwards (from the end to start)
  115326. ** through doclists. It is used by this module to iterate through phrase
  115327. ** doclists in reverse and by the fts3_write.c module to iterate through
  115328. ** pending-terms lists when writing to databases with "order=desc".
  115329. **
  115330. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  115331. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  115332. ** function iterates from the end of the doclist to the beginning.
  115333. */
  115334. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  115335. int bDescIdx, /* True if the doclist is desc */
  115336. char *aDoclist, /* Pointer to entire doclist */
  115337. int nDoclist, /* Length of aDoclist in bytes */
  115338. char **ppIter, /* IN/OUT: Iterator pointer */
  115339. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  115340. int *pnList, /* OUT: List length pointer */
  115341. u8 *pbEof /* OUT: End-of-file flag */
  115342. ){
  115343. char *p = *ppIter;
  115344. assert( nDoclist>0 );
  115345. assert( *pbEof==0 );
  115346. assert( p || *piDocid==0 );
  115347. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  115348. if( p==0 ){
  115349. sqlite3_int64 iDocid = 0;
  115350. char *pNext = 0;
  115351. char *pDocid = aDoclist;
  115352. char *pEnd = &aDoclist[nDoclist];
  115353. int iMul = 1;
  115354. while( pDocid<pEnd ){
  115355. sqlite3_int64 iDelta;
  115356. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  115357. iDocid += (iMul * iDelta);
  115358. pNext = pDocid;
  115359. fts3PoslistCopy(0, &pDocid);
  115360. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  115361. iMul = (bDescIdx ? -1 : 1);
  115362. }
  115363. *pnList = (int)(pEnd - pNext);
  115364. *ppIter = pNext;
  115365. *piDocid = iDocid;
  115366. }else{
  115367. int iMul = (bDescIdx ? -1 : 1);
  115368. sqlite3_int64 iDelta;
  115369. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  115370. *piDocid -= (iMul * iDelta);
  115371. if( p==aDoclist ){
  115372. *pbEof = 1;
  115373. }else{
  115374. char *pSave = p;
  115375. fts3ReversePoslist(aDoclist, &p);
  115376. *pnList = (int)(pSave - p);
  115377. }
  115378. *ppIter = p;
  115379. }
  115380. }
  115381. /*
  115382. ** Iterate forwards through a doclist.
  115383. */
  115384. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  115385. int bDescIdx, /* True if the doclist is desc */
  115386. char *aDoclist, /* Pointer to entire doclist */
  115387. int nDoclist, /* Length of aDoclist in bytes */
  115388. char **ppIter, /* IN/OUT: Iterator pointer */
  115389. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  115390. u8 *pbEof /* OUT: End-of-file flag */
  115391. ){
  115392. char *p = *ppIter;
  115393. assert( nDoclist>0 );
  115394. assert( *pbEof==0 );
  115395. assert( p || *piDocid==0 );
  115396. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  115397. if( p==0 ){
  115398. p = aDoclist;
  115399. p += sqlite3Fts3GetVarint(p, piDocid);
  115400. }else{
  115401. fts3PoslistCopy(0, &p);
  115402. if( p>=&aDoclist[nDoclist] ){
  115403. *pbEof = 1;
  115404. }else{
  115405. sqlite3_int64 iVar;
  115406. p += sqlite3Fts3GetVarint(p, &iVar);
  115407. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  115408. }
  115409. }
  115410. *ppIter = p;
  115411. }
  115412. /*
  115413. ** Attempt to move the phrase iterator to point to the next matching docid.
  115414. ** If an error occurs, return an SQLite error code. Otherwise, return
  115415. ** SQLITE_OK.
  115416. **
  115417. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  115418. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  115419. ** successfully advanced, *pbEof is set to 0.
  115420. */
  115421. static int fts3EvalPhraseNext(
  115422. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115423. Fts3Phrase *p, /* Phrase object to advance to next docid */
  115424. u8 *pbEof /* OUT: Set to 1 if EOF */
  115425. ){
  115426. int rc = SQLITE_OK;
  115427. Fts3Doclist *pDL = &p->doclist;
  115428. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  115429. if( p->bIncr ){
  115430. assert( p->nToken==1 );
  115431. assert( pDL->pNextDocid==0 );
  115432. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  115433. &pDL->iDocid, &pDL->pList, &pDL->nList
  115434. );
  115435. if( rc==SQLITE_OK && !pDL->pList ){
  115436. *pbEof = 1;
  115437. }
  115438. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  115439. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  115440. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  115441. );
  115442. pDL->pList = pDL->pNextDocid;
  115443. }else{
  115444. char *pIter; /* Used to iterate through aAll */
  115445. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  115446. if( pDL->pNextDocid ){
  115447. pIter = pDL->pNextDocid;
  115448. }else{
  115449. pIter = pDL->aAll;
  115450. }
  115451. if( pIter>=pEnd ){
  115452. /* We have already reached the end of this doclist. EOF. */
  115453. *pbEof = 1;
  115454. }else{
  115455. sqlite3_int64 iDelta;
  115456. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  115457. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  115458. pDL->iDocid += iDelta;
  115459. }else{
  115460. pDL->iDocid -= iDelta;
  115461. }
  115462. pDL->pList = pIter;
  115463. fts3PoslistCopy(0, &pIter);
  115464. pDL->nList = (int)(pIter - pDL->pList);
  115465. /* pIter now points just past the 0x00 that terminates the position-
  115466. ** list for document pDL->iDocid. However, if this position-list was
  115467. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  115468. ** point to the start of the next docid value. The following line deals
  115469. ** with this case by advancing pIter past the zero-padding added by
  115470. ** fts3EvalNearTrim(). */
  115471. while( pIter<pEnd && *pIter==0 ) pIter++;
  115472. pDL->pNextDocid = pIter;
  115473. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  115474. *pbEof = 0;
  115475. }
  115476. }
  115477. return rc;
  115478. }
  115479. /*
  115480. **
  115481. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  115482. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  115483. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  115484. ** expressions for which all descendent tokens are deferred.
  115485. **
  115486. ** If parameter bOptOk is zero, then it is guaranteed that the
  115487. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  115488. ** each phrase in the expression (subject to deferred token processing).
  115489. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  115490. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  115491. **
  115492. ** If an error occurs within this function, *pRc is set to an SQLite error
  115493. ** code before returning.
  115494. */
  115495. static void fts3EvalStartReaders(
  115496. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115497. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  115498. int bOptOk, /* True to enable incremental loading */
  115499. int *pRc /* IN/OUT: Error code */
  115500. ){
  115501. if( pExpr && SQLITE_OK==*pRc ){
  115502. if( pExpr->eType==FTSQUERY_PHRASE ){
  115503. int i;
  115504. int nToken = pExpr->pPhrase->nToken;
  115505. for(i=0; i<nToken; i++){
  115506. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  115507. }
  115508. pExpr->bDeferred = (i==nToken);
  115509. *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
  115510. }else{
  115511. fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
  115512. fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
  115513. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  115514. }
  115515. }
  115516. }
  115517. /*
  115518. ** An array of the following structures is assembled as part of the process
  115519. ** of selecting tokens to defer before the query starts executing (as part
  115520. ** of the xFilter() method). There is one element in the array for each
  115521. ** token in the FTS expression.
  115522. **
  115523. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  115524. ** to phrases that are connected only by AND and NEAR operators (not OR or
  115525. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  115526. ** separately. The root of a tokens AND/NEAR cluster is stored in
  115527. ** Fts3TokenAndCost.pRoot.
  115528. */
  115529. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  115530. struct Fts3TokenAndCost {
  115531. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  115532. int iToken; /* Position of token in phrase */
  115533. Fts3PhraseToken *pToken; /* The token itself */
  115534. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  115535. int nOvfl; /* Number of overflow pages to load doclist */
  115536. int iCol; /* The column the token must match */
  115537. };
  115538. /*
  115539. ** This function is used to populate an allocated Fts3TokenAndCost array.
  115540. **
  115541. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  115542. ** Otherwise, if an error occurs during execution, *pRc is set to an
  115543. ** SQLite error code.
  115544. */
  115545. static void fts3EvalTokenCosts(
  115546. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115547. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  115548. Fts3Expr *pExpr, /* Expression to consider */
  115549. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  115550. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  115551. int *pRc /* IN/OUT: Error code */
  115552. ){
  115553. if( *pRc==SQLITE_OK ){
  115554. if( pExpr->eType==FTSQUERY_PHRASE ){
  115555. Fts3Phrase *pPhrase = pExpr->pPhrase;
  115556. int i;
  115557. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  115558. Fts3TokenAndCost *pTC = (*ppTC)++;
  115559. pTC->pPhrase = pPhrase;
  115560. pTC->iToken = i;
  115561. pTC->pRoot = pRoot;
  115562. pTC->pToken = &pPhrase->aToken[i];
  115563. pTC->iCol = pPhrase->iColumn;
  115564. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  115565. }
  115566. }else if( pExpr->eType!=FTSQUERY_NOT ){
  115567. assert( pExpr->eType==FTSQUERY_OR
  115568. || pExpr->eType==FTSQUERY_AND
  115569. || pExpr->eType==FTSQUERY_NEAR
  115570. );
  115571. assert( pExpr->pLeft && pExpr->pRight );
  115572. if( pExpr->eType==FTSQUERY_OR ){
  115573. pRoot = pExpr->pLeft;
  115574. **ppOr = pRoot;
  115575. (*ppOr)++;
  115576. }
  115577. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  115578. if( pExpr->eType==FTSQUERY_OR ){
  115579. pRoot = pExpr->pRight;
  115580. **ppOr = pRoot;
  115581. (*ppOr)++;
  115582. }
  115583. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  115584. }
  115585. }
  115586. }
  115587. /*
  115588. ** Determine the average document (row) size in pages. If successful,
  115589. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  115590. ** an SQLite error code.
  115591. **
  115592. ** The average document size in pages is calculated by first calculating
  115593. ** determining the average size in bytes, B. If B is less than the amount
  115594. ** of data that will fit on a single leaf page of an intkey table in
  115595. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  115596. ** the number of overflow pages consumed by a record B bytes in size.
  115597. */
  115598. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  115599. if( pCsr->nRowAvg==0 ){
  115600. /* The average document size, which is required to calculate the cost
  115601. ** of each doclist, has not yet been determined. Read the required
  115602. ** data from the %_stat table to calculate it.
  115603. **
  115604. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  115605. ** varints, where nCol is the number of columns in the FTS3 table.
  115606. ** The first varint is the number of documents currently stored in
  115607. ** the table. The following nCol varints contain the total amount of
  115608. ** data stored in all rows of each column of the table, from left
  115609. ** to right.
  115610. */
  115611. int rc;
  115612. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  115613. sqlite3_stmt *pStmt;
  115614. sqlite3_int64 nDoc = 0;
  115615. sqlite3_int64 nByte = 0;
  115616. const char *pEnd;
  115617. const char *a;
  115618. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  115619. if( rc!=SQLITE_OK ) return rc;
  115620. a = sqlite3_column_blob(pStmt, 0);
  115621. assert( a );
  115622. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  115623. a += sqlite3Fts3GetVarint(a, &nDoc);
  115624. while( a<pEnd ){
  115625. a += sqlite3Fts3GetVarint(a, &nByte);
  115626. }
  115627. if( nDoc==0 || nByte==0 ){
  115628. sqlite3_reset(pStmt);
  115629. return FTS_CORRUPT_VTAB;
  115630. }
  115631. pCsr->nDoc = nDoc;
  115632. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  115633. assert( pCsr->nRowAvg>0 );
  115634. rc = sqlite3_reset(pStmt);
  115635. if( rc!=SQLITE_OK ) return rc;
  115636. }
  115637. *pnPage = pCsr->nRowAvg;
  115638. return SQLITE_OK;
  115639. }
  115640. /*
  115641. ** This function is called to select the tokens (if any) that will be
  115642. ** deferred. The array aTC[] has already been populated when this is
  115643. ** called.
  115644. **
  115645. ** This function is called once for each AND/NEAR cluster in the
  115646. ** expression. Each invocation determines which tokens to defer within
  115647. ** the cluster with root node pRoot. See comments above the definition
  115648. ** of struct Fts3TokenAndCost for more details.
  115649. **
  115650. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  115651. ** called on each token to defer. Otherwise, an SQLite error code is
  115652. ** returned.
  115653. */
  115654. static int fts3EvalSelectDeferred(
  115655. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115656. Fts3Expr *pRoot, /* Consider tokens with this root node */
  115657. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  115658. int nTC /* Number of entries in aTC[] */
  115659. ){
  115660. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  115661. int nDocSize = 0; /* Number of pages per doc loaded */
  115662. int rc = SQLITE_OK; /* Return code */
  115663. int ii; /* Iterator variable for various purposes */
  115664. int nOvfl = 0; /* Total overflow pages used by doclists */
  115665. int nToken = 0; /* Total number of tokens in cluster */
  115666. int nMinEst = 0; /* The minimum count for any phrase so far. */
  115667. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  115668. /* Tokens are never deferred for FTS tables created using the content=xxx
  115669. ** option. The reason being that it is not guaranteed that the content
  115670. ** table actually contains the same data as the index. To prevent this from
  115671. ** causing any problems, the deferred token optimization is completely
  115672. ** disabled for content=xxx tables. */
  115673. if( pTab->zContentTbl ){
  115674. return SQLITE_OK;
  115675. }
  115676. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  115677. ** associated with the tokens spill onto overflow pages, or if there is
  115678. ** only 1 token, exit early. No tokens to defer in this case. */
  115679. for(ii=0; ii<nTC; ii++){
  115680. if( aTC[ii].pRoot==pRoot ){
  115681. nOvfl += aTC[ii].nOvfl;
  115682. nToken++;
  115683. }
  115684. }
  115685. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  115686. /* Obtain the average docsize (in pages). */
  115687. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  115688. assert( rc!=SQLITE_OK || nDocSize>0 );
  115689. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  115690. ** of the number of overflow pages that will be loaded by the pager layer
  115691. ** to retrieve the entire doclist for the token from the full-text index.
  115692. ** Load the doclists for tokens that are either:
  115693. **
  115694. ** a. The cheapest token in the entire query (i.e. the one visited by the
  115695. ** first iteration of this loop), or
  115696. **
  115697. ** b. Part of a multi-token phrase.
  115698. **
  115699. ** After each token doclist is loaded, merge it with the others from the
  115700. ** same phrase and count the number of documents that the merged doclist
  115701. ** contains. Set variable "nMinEst" to the smallest number of documents in
  115702. ** any phrase doclist for which 1 or more token doclists have been loaded.
  115703. ** Let nOther be the number of other phrases for which it is certain that
  115704. ** one or more tokens will not be deferred.
  115705. **
  115706. ** Then, for each token, defer it if loading the doclist would result in
  115707. ** loading N or more overflow pages into memory, where N is computed as:
  115708. **
  115709. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  115710. */
  115711. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  115712. int iTC; /* Used to iterate through aTC[] array. */
  115713. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  115714. /* Set pTC to point to the cheapest remaining token. */
  115715. for(iTC=0; iTC<nTC; iTC++){
  115716. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  115717. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  115718. ){
  115719. pTC = &aTC[iTC];
  115720. }
  115721. }
  115722. assert( pTC );
  115723. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  115724. /* The number of overflow pages to load for this (and therefore all
  115725. ** subsequent) tokens is greater than the estimated number of pages
  115726. ** that will be loaded if all subsequent tokens are deferred.
  115727. */
  115728. Fts3PhraseToken *pToken = pTC->pToken;
  115729. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  115730. fts3SegReaderCursorFree(pToken->pSegcsr);
  115731. pToken->pSegcsr = 0;
  115732. }else{
  115733. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  115734. ** for-loop. Except, limit the value to 2^24 to prevent it from
  115735. ** overflowing the 32-bit integer it is stored in. */
  115736. if( ii<12 ) nLoad4 = nLoad4*4;
  115737. if( ii==0 || pTC->pPhrase->nToken>1 ){
  115738. /* Either this is the cheapest token in the entire query, or it is
  115739. ** part of a multi-token phrase. Either way, the entire doclist will
  115740. ** (eventually) be loaded into memory. It may as well be now. */
  115741. Fts3PhraseToken *pToken = pTC->pToken;
  115742. int nList = 0;
  115743. char *pList = 0;
  115744. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  115745. assert( rc==SQLITE_OK || pList==0 );
  115746. if( rc==SQLITE_OK ){
  115747. int nCount;
  115748. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  115749. nCount = fts3DoclistCountDocids(
  115750. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  115751. );
  115752. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  115753. }
  115754. }
  115755. }
  115756. pTC->pToken = 0;
  115757. }
  115758. return rc;
  115759. }
  115760. /*
  115761. ** This function is called from within the xFilter method. It initializes
  115762. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  115763. ** the results of a query, the caller does:
  115764. **
  115765. ** fts3EvalStart(pCsr);
  115766. ** while( 1 ){
  115767. ** fts3EvalNext(pCsr);
  115768. ** if( pCsr->bEof ) break;
  115769. ** ... return row pCsr->iPrevId to the caller ...
  115770. ** }
  115771. */
  115772. static int fts3EvalStart(Fts3Cursor *pCsr){
  115773. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  115774. int rc = SQLITE_OK;
  115775. int nToken = 0;
  115776. int nOr = 0;
  115777. /* Allocate a MultiSegReader for each token in the expression. */
  115778. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  115779. /* Determine which, if any, tokens in the expression should be deferred. */
  115780. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  115781. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  115782. Fts3TokenAndCost *aTC;
  115783. Fts3Expr **apOr;
  115784. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  115785. sizeof(Fts3TokenAndCost) * nToken
  115786. + sizeof(Fts3Expr *) * nOr * 2
  115787. );
  115788. apOr = (Fts3Expr **)&aTC[nToken];
  115789. if( !aTC ){
  115790. rc = SQLITE_NOMEM;
  115791. }else{
  115792. int ii;
  115793. Fts3TokenAndCost *pTC = aTC;
  115794. Fts3Expr **ppOr = apOr;
  115795. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  115796. nToken = (int)(pTC-aTC);
  115797. nOr = (int)(ppOr-apOr);
  115798. if( rc==SQLITE_OK ){
  115799. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  115800. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  115801. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  115802. }
  115803. }
  115804. sqlite3_free(aTC);
  115805. }
  115806. }
  115807. #endif
  115808. fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
  115809. return rc;
  115810. }
  115811. /*
  115812. ** Invalidate the current position list for phrase pPhrase.
  115813. */
  115814. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  115815. if( pPhrase->doclist.bFreeList ){
  115816. sqlite3_free(pPhrase->doclist.pList);
  115817. }
  115818. pPhrase->doclist.pList = 0;
  115819. pPhrase->doclist.nList = 0;
  115820. pPhrase->doclist.bFreeList = 0;
  115821. }
  115822. /*
  115823. ** This function is called to edit the position list associated with
  115824. ** the phrase object passed as the fifth argument according to a NEAR
  115825. ** condition. For example:
  115826. **
  115827. ** abc NEAR/5 "def ghi"
  115828. **
  115829. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  115830. ** the example above). When this function is called, *paPoslist points to
  115831. ** the position list, and *pnToken is the number of phrase tokens in, the
  115832. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  115833. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  115834. ** the position list associated with phrase "abc".
  115835. **
  115836. ** All positions in the pPhrase position list that are not sufficiently
  115837. ** close to a position in the *paPoslist position list are removed. If this
  115838. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  115839. **
  115840. ** Before returning, *paPoslist is set to point to the position lsit
  115841. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  115842. ** pPhrase.
  115843. */
  115844. static int fts3EvalNearTrim(
  115845. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  115846. char *aTmp, /* Temporary space to use */
  115847. char **paPoslist, /* IN/OUT: Position list */
  115848. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  115849. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  115850. ){
  115851. int nParam1 = nNear + pPhrase->nToken;
  115852. int nParam2 = nNear + *pnToken;
  115853. int nNew;
  115854. char *p2;
  115855. char *pOut;
  115856. int res;
  115857. assert( pPhrase->doclist.pList );
  115858. p2 = pOut = pPhrase->doclist.pList;
  115859. res = fts3PoslistNearMerge(
  115860. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  115861. );
  115862. if( res ){
  115863. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  115864. assert( pPhrase->doclist.pList[nNew]=='\0' );
  115865. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  115866. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  115867. pPhrase->doclist.nList = nNew;
  115868. *paPoslist = pPhrase->doclist.pList;
  115869. *pnToken = pPhrase->nToken;
  115870. }
  115871. return res;
  115872. }
  115873. /*
  115874. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  115875. ** Otherwise, it advances the expression passed as the second argument to
  115876. ** point to the next matching row in the database. Expressions iterate through
  115877. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  115878. ** or descending if it is non-zero.
  115879. **
  115880. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  115881. ** successful, the following variables in pExpr are set:
  115882. **
  115883. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  115884. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  115885. **
  115886. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  115887. ** at EOF, then the following variables are populated with the position list
  115888. ** for the phrase for the visited row:
  115889. **
  115890. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  115891. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  115892. **
  115893. ** It says above that this function advances the expression to the next
  115894. ** matching row. This is usually true, but there are the following exceptions:
  115895. **
  115896. ** 1. Deferred tokens are not taken into account. If a phrase consists
  115897. ** entirely of deferred tokens, it is assumed to match every row in
  115898. ** the db. In this case the position-list is not populated at all.
  115899. **
  115900. ** Or, if a phrase contains one or more deferred tokens and one or
  115901. ** more non-deferred tokens, then the expression is advanced to the
  115902. ** next possible match, considering only non-deferred tokens. In other
  115903. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  115904. ** is advanced to the next row that contains an instance of "A * C",
  115905. ** where "*" may match any single token. The position list in this case
  115906. ** is populated as for "A * C" before returning.
  115907. **
  115908. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  115909. ** advanced to point to the next row that matches "x AND y".
  115910. **
  115911. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  115912. ** really a match, taking into account deferred tokens and NEAR operators.
  115913. */
  115914. static void fts3EvalNextRow(
  115915. Fts3Cursor *pCsr, /* FTS Cursor handle */
  115916. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  115917. int *pRc /* IN/OUT: Error code */
  115918. ){
  115919. if( *pRc==SQLITE_OK ){
  115920. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  115921. assert( pExpr->bEof==0 );
  115922. pExpr->bStart = 1;
  115923. switch( pExpr->eType ){
  115924. case FTSQUERY_NEAR:
  115925. case FTSQUERY_AND: {
  115926. Fts3Expr *pLeft = pExpr->pLeft;
  115927. Fts3Expr *pRight = pExpr->pRight;
  115928. assert( !pLeft->bDeferred || !pRight->bDeferred );
  115929. if( pLeft->bDeferred ){
  115930. /* LHS is entirely deferred. So we assume it matches every row.
  115931. ** Advance the RHS iterator to find the next row visited. */
  115932. fts3EvalNextRow(pCsr, pRight, pRc);
  115933. pExpr->iDocid = pRight->iDocid;
  115934. pExpr->bEof = pRight->bEof;
  115935. }else if( pRight->bDeferred ){
  115936. /* RHS is entirely deferred. So we assume it matches every row.
  115937. ** Advance the LHS iterator to find the next row visited. */
  115938. fts3EvalNextRow(pCsr, pLeft, pRc);
  115939. pExpr->iDocid = pLeft->iDocid;
  115940. pExpr->bEof = pLeft->bEof;
  115941. }else{
  115942. /* Neither the RHS or LHS are deferred. */
  115943. fts3EvalNextRow(pCsr, pLeft, pRc);
  115944. fts3EvalNextRow(pCsr, pRight, pRc);
  115945. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  115946. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  115947. if( iDiff==0 ) break;
  115948. if( iDiff<0 ){
  115949. fts3EvalNextRow(pCsr, pLeft, pRc);
  115950. }else{
  115951. fts3EvalNextRow(pCsr, pRight, pRc);
  115952. }
  115953. }
  115954. pExpr->iDocid = pLeft->iDocid;
  115955. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  115956. }
  115957. break;
  115958. }
  115959. case FTSQUERY_OR: {
  115960. Fts3Expr *pLeft = pExpr->pLeft;
  115961. Fts3Expr *pRight = pExpr->pRight;
  115962. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  115963. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  115964. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  115965. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  115966. fts3EvalNextRow(pCsr, pLeft, pRc);
  115967. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  115968. fts3EvalNextRow(pCsr, pRight, pRc);
  115969. }else{
  115970. fts3EvalNextRow(pCsr, pLeft, pRc);
  115971. fts3EvalNextRow(pCsr, pRight, pRc);
  115972. }
  115973. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  115974. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  115975. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  115976. pExpr->iDocid = pLeft->iDocid;
  115977. }else{
  115978. pExpr->iDocid = pRight->iDocid;
  115979. }
  115980. break;
  115981. }
  115982. case FTSQUERY_NOT: {
  115983. Fts3Expr *pLeft = pExpr->pLeft;
  115984. Fts3Expr *pRight = pExpr->pRight;
  115985. if( pRight->bStart==0 ){
  115986. fts3EvalNextRow(pCsr, pRight, pRc);
  115987. assert( *pRc!=SQLITE_OK || pRight->bStart );
  115988. }
  115989. fts3EvalNextRow(pCsr, pLeft, pRc);
  115990. if( pLeft->bEof==0 ){
  115991. while( !*pRc
  115992. && !pRight->bEof
  115993. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  115994. ){
  115995. fts3EvalNextRow(pCsr, pRight, pRc);
  115996. }
  115997. }
  115998. pExpr->iDocid = pLeft->iDocid;
  115999. pExpr->bEof = pLeft->bEof;
  116000. break;
  116001. }
  116002. default: {
  116003. Fts3Phrase *pPhrase = pExpr->pPhrase;
  116004. fts3EvalInvalidatePoslist(pPhrase);
  116005. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  116006. pExpr->iDocid = pPhrase->doclist.iDocid;
  116007. break;
  116008. }
  116009. }
  116010. }
  116011. }
  116012. /*
  116013. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  116014. ** cluster, then this function returns 1 immediately.
  116015. **
  116016. ** Otherwise, it checks if the current row really does match the NEAR
  116017. ** expression, using the data currently stored in the position lists
  116018. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  116019. **
  116020. ** If the current row is a match, the position list associated with each
  116021. ** phrase in the NEAR expression is edited in place to contain only those
  116022. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  116023. ** constraints. In this case it returns 1. If the NEAR expression does not
  116024. ** match the current row, 0 is returned. The position lists may or may not
  116025. ** be edited if 0 is returned.
  116026. */
  116027. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  116028. int res = 1;
  116029. /* The following block runs if pExpr is the root of a NEAR query.
  116030. ** For example, the query:
  116031. **
  116032. ** "w" NEAR "x" NEAR "y" NEAR "z"
  116033. **
  116034. ** which is represented in tree form as:
  116035. **
  116036. ** |
  116037. ** +--NEAR--+ <-- root of NEAR query
  116038. ** | |
  116039. ** +--NEAR--+ "z"
  116040. ** | |
  116041. ** +--NEAR--+ "y"
  116042. ** | |
  116043. ** "w" "x"
  116044. **
  116045. ** The right-hand child of a NEAR node is always a phrase. The
  116046. ** left-hand child may be either a phrase or a NEAR node. There are
  116047. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  116048. */
  116049. if( *pRc==SQLITE_OK
  116050. && pExpr->eType==FTSQUERY_NEAR
  116051. && pExpr->bEof==0
  116052. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  116053. ){
  116054. Fts3Expr *p;
  116055. int nTmp = 0; /* Bytes of temp space */
  116056. char *aTmp; /* Temp space for PoslistNearMerge() */
  116057. /* Allocate temporary working space. */
  116058. for(p=pExpr; p->pLeft; p=p->pLeft){
  116059. nTmp += p->pRight->pPhrase->doclist.nList;
  116060. }
  116061. nTmp += p->pPhrase->doclist.nList;
  116062. if( nTmp==0 ){
  116063. res = 0;
  116064. }else{
  116065. aTmp = sqlite3_malloc(nTmp*2);
  116066. if( !aTmp ){
  116067. *pRc = SQLITE_NOMEM;
  116068. res = 0;
  116069. }else{
  116070. char *aPoslist = p->pPhrase->doclist.pList;
  116071. int nToken = p->pPhrase->nToken;
  116072. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  116073. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  116074. int nNear = p->nNear;
  116075. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  116076. }
  116077. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  116078. nToken = pExpr->pRight->pPhrase->nToken;
  116079. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  116080. int nNear;
  116081. Fts3Phrase *pPhrase;
  116082. assert( p->pParent && p->pParent->pLeft==p );
  116083. nNear = p->pParent->nNear;
  116084. pPhrase = (
  116085. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  116086. );
  116087. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  116088. }
  116089. }
  116090. sqlite3_free(aTmp);
  116091. }
  116092. }
  116093. return res;
  116094. }
  116095. /*
  116096. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  116097. ** Assuming no error occurs or has occurred, It returns non-zero if the
  116098. ** expression passed as the second argument matches the row that pCsr
  116099. ** currently points to, or zero if it does not.
  116100. **
  116101. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  116102. ** If an error occurs during execution of this function, *pRc is set to
  116103. ** the appropriate SQLite error code. In this case the returned value is
  116104. ** undefined.
  116105. */
  116106. static int fts3EvalTestExpr(
  116107. Fts3Cursor *pCsr, /* FTS cursor handle */
  116108. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  116109. int *pRc /* IN/OUT: Error code */
  116110. ){
  116111. int bHit = 1; /* Return value */
  116112. if( *pRc==SQLITE_OK ){
  116113. switch( pExpr->eType ){
  116114. case FTSQUERY_NEAR:
  116115. case FTSQUERY_AND:
  116116. bHit = (
  116117. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  116118. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  116119. && fts3EvalNearTest(pExpr, pRc)
  116120. );
  116121. /* If the NEAR expression does not match any rows, zero the doclist for
  116122. ** all phrases involved in the NEAR. This is because the snippet(),
  116123. ** offsets() and matchinfo() functions are not supposed to recognize
  116124. ** any instances of phrases that are part of unmatched NEAR queries.
  116125. ** For example if this expression:
  116126. **
  116127. ** ... MATCH 'a OR (b NEAR c)'
  116128. **
  116129. ** is matched against a row containing:
  116130. **
  116131. ** 'a b d e'
  116132. **
  116133. ** then any snippet() should ony highlight the "a" term, not the "b"
  116134. ** (as "b" is part of a non-matching NEAR clause).
  116135. */
  116136. if( bHit==0
  116137. && pExpr->eType==FTSQUERY_NEAR
  116138. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  116139. ){
  116140. Fts3Expr *p;
  116141. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  116142. if( p->pRight->iDocid==pCsr->iPrevId ){
  116143. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  116144. }
  116145. }
  116146. if( p->iDocid==pCsr->iPrevId ){
  116147. fts3EvalInvalidatePoslist(p->pPhrase);
  116148. }
  116149. }
  116150. break;
  116151. case FTSQUERY_OR: {
  116152. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  116153. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  116154. bHit = bHit1 || bHit2;
  116155. break;
  116156. }
  116157. case FTSQUERY_NOT:
  116158. bHit = (
  116159. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  116160. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  116161. );
  116162. break;
  116163. default: {
  116164. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  116165. if( pCsr->pDeferred
  116166. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  116167. ){
  116168. Fts3Phrase *pPhrase = pExpr->pPhrase;
  116169. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  116170. if( pExpr->bDeferred ){
  116171. fts3EvalInvalidatePoslist(pPhrase);
  116172. }
  116173. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  116174. bHit = (pPhrase->doclist.pList!=0);
  116175. pExpr->iDocid = pCsr->iPrevId;
  116176. }else
  116177. #endif
  116178. {
  116179. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  116180. }
  116181. break;
  116182. }
  116183. }
  116184. }
  116185. return bHit;
  116186. }
  116187. /*
  116188. ** This function is called as the second part of each xNext operation when
  116189. ** iterating through the results of a full-text query. At this point the
  116190. ** cursor points to a row that matches the query expression, with the
  116191. ** following caveats:
  116192. **
  116193. ** * Up until this point, "NEAR" operators in the expression have been
  116194. ** treated as "AND".
  116195. **
  116196. ** * Deferred tokens have not yet been considered.
  116197. **
  116198. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  116199. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  116200. ** operators and deferred tokens the current row is still a match for the
  116201. ** expression. It returns 1 if both of the following are true:
  116202. **
  116203. ** 1. *pRc is SQLITE_OK when this function returns, and
  116204. **
  116205. ** 2. After scanning the current FTS table row for the deferred tokens,
  116206. ** it is determined that the row does *not* match the query.
  116207. **
  116208. ** Or, if no error occurs and it seems the current row does match the FTS
  116209. ** query, return 0.
  116210. */
  116211. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  116212. int rc = *pRc;
  116213. int bMiss = 0;
  116214. if( rc==SQLITE_OK ){
  116215. /* If there are one or more deferred tokens, load the current row into
  116216. ** memory and scan it to determine the position list for each deferred
  116217. ** token. Then, see if this row is really a match, considering deferred
  116218. ** tokens and NEAR operators (neither of which were taken into account
  116219. ** earlier, by fts3EvalNextRow()).
  116220. */
  116221. if( pCsr->pDeferred ){
  116222. rc = fts3CursorSeek(0, pCsr);
  116223. if( rc==SQLITE_OK ){
  116224. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  116225. }
  116226. }
  116227. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  116228. /* Free the position-lists accumulated for each deferred token above. */
  116229. sqlite3Fts3FreeDeferredDoclists(pCsr);
  116230. *pRc = rc;
  116231. }
  116232. return (rc==SQLITE_OK && bMiss);
  116233. }
  116234. /*
  116235. ** Advance to the next document that matches the FTS expression in
  116236. ** Fts3Cursor.pExpr.
  116237. */
  116238. static int fts3EvalNext(Fts3Cursor *pCsr){
  116239. int rc = SQLITE_OK; /* Return Code */
  116240. Fts3Expr *pExpr = pCsr->pExpr;
  116241. assert( pCsr->isEof==0 );
  116242. if( pExpr==0 ){
  116243. pCsr->isEof = 1;
  116244. }else{
  116245. do {
  116246. if( pCsr->isRequireSeek==0 ){
  116247. sqlite3_reset(pCsr->pStmt);
  116248. }
  116249. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  116250. fts3EvalNextRow(pCsr, pExpr, &rc);
  116251. pCsr->isEof = pExpr->bEof;
  116252. pCsr->isRequireSeek = 1;
  116253. pCsr->isMatchinfoNeeded = 1;
  116254. pCsr->iPrevId = pExpr->iDocid;
  116255. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  116256. }
  116257. return rc;
  116258. }
  116259. /*
  116260. ** Restart interation for expression pExpr so that the next call to
  116261. ** fts3EvalNext() visits the first row. Do not allow incremental
  116262. ** loading or merging of phrase doclists for this iteration.
  116263. **
  116264. ** If *pRc is other than SQLITE_OK when this function is called, it is
  116265. ** a no-op. If an error occurs within this function, *pRc is set to an
  116266. ** SQLite error code before returning.
  116267. */
  116268. static void fts3EvalRestart(
  116269. Fts3Cursor *pCsr,
  116270. Fts3Expr *pExpr,
  116271. int *pRc
  116272. ){
  116273. if( pExpr && *pRc==SQLITE_OK ){
  116274. Fts3Phrase *pPhrase = pExpr->pPhrase;
  116275. if( pPhrase ){
  116276. fts3EvalInvalidatePoslist(pPhrase);
  116277. if( pPhrase->bIncr ){
  116278. assert( pPhrase->nToken==1 );
  116279. assert( pPhrase->aToken[0].pSegcsr );
  116280. sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
  116281. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  116282. }
  116283. pPhrase->doclist.pNextDocid = 0;
  116284. pPhrase->doclist.iDocid = 0;
  116285. }
  116286. pExpr->iDocid = 0;
  116287. pExpr->bEof = 0;
  116288. pExpr->bStart = 0;
  116289. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  116290. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  116291. }
  116292. }
  116293. /*
  116294. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  116295. ** expression rooted at pExpr, the cursor iterates through all rows matched
  116296. ** by pExpr, calling this function for each row. This function increments
  116297. ** the values in Fts3Expr.aMI[] according to the position-list currently
  116298. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  116299. ** expression nodes.
  116300. */
  116301. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  116302. if( pExpr ){
  116303. Fts3Phrase *pPhrase = pExpr->pPhrase;
  116304. if( pPhrase && pPhrase->doclist.pList ){
  116305. int iCol = 0;
  116306. char *p = pPhrase->doclist.pList;
  116307. assert( *p );
  116308. while( 1 ){
  116309. u8 c = 0;
  116310. int iCnt = 0;
  116311. while( 0xFE & (*p | c) ){
  116312. if( (c&0x80)==0 ) iCnt++;
  116313. c = *p++ & 0x80;
  116314. }
  116315. /* aMI[iCol*3 + 1] = Number of occurrences
  116316. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  116317. */
  116318. pExpr->aMI[iCol*3 + 1] += iCnt;
  116319. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  116320. if( *p==0x00 ) break;
  116321. p++;
  116322. p += sqlite3Fts3GetVarint32(p, &iCol);
  116323. }
  116324. }
  116325. fts3EvalUpdateCounts(pExpr->pLeft);
  116326. fts3EvalUpdateCounts(pExpr->pRight);
  116327. }
  116328. }
  116329. /*
  116330. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  116331. **
  116332. ** If it is not already allocated and populated, this function allocates and
  116333. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  116334. ** of a NEAR expression, then it also allocates and populates the same array
  116335. ** for all other phrases that are part of the NEAR expression.
  116336. **
  116337. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  116338. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  116339. */
  116340. static int fts3EvalGatherStats(
  116341. Fts3Cursor *pCsr, /* Cursor object */
  116342. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  116343. ){
  116344. int rc = SQLITE_OK; /* Return code */
  116345. assert( pExpr->eType==FTSQUERY_PHRASE );
  116346. if( pExpr->aMI==0 ){
  116347. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  116348. Fts3Expr *pRoot; /* Root of NEAR expression */
  116349. Fts3Expr *p; /* Iterator used for several purposes */
  116350. sqlite3_int64 iPrevId = pCsr->iPrevId;
  116351. sqlite3_int64 iDocid;
  116352. u8 bEof;
  116353. /* Find the root of the NEAR expression */
  116354. pRoot = pExpr;
  116355. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  116356. pRoot = pRoot->pParent;
  116357. }
  116358. iDocid = pRoot->iDocid;
  116359. bEof = pRoot->bEof;
  116360. assert( pRoot->bStart );
  116361. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  116362. for(p=pRoot; p; p=p->pLeft){
  116363. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  116364. assert( pE->aMI==0 );
  116365. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  116366. if( !pE->aMI ) return SQLITE_NOMEM;
  116367. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  116368. }
  116369. fts3EvalRestart(pCsr, pRoot, &rc);
  116370. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  116371. do {
  116372. /* Ensure the %_content statement is reset. */
  116373. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  116374. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  116375. /* Advance to the next document */
  116376. fts3EvalNextRow(pCsr, pRoot, &rc);
  116377. pCsr->isEof = pRoot->bEof;
  116378. pCsr->isRequireSeek = 1;
  116379. pCsr->isMatchinfoNeeded = 1;
  116380. pCsr->iPrevId = pRoot->iDocid;
  116381. }while( pCsr->isEof==0
  116382. && pRoot->eType==FTSQUERY_NEAR
  116383. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  116384. );
  116385. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  116386. fts3EvalUpdateCounts(pRoot);
  116387. }
  116388. }
  116389. pCsr->isEof = 0;
  116390. pCsr->iPrevId = iPrevId;
  116391. if( bEof ){
  116392. pRoot->bEof = bEof;
  116393. }else{
  116394. /* Caution: pRoot may iterate through docids in ascending or descending
  116395. ** order. For this reason, even though it seems more defensive, the
  116396. ** do loop can not be written:
  116397. **
  116398. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  116399. */
  116400. fts3EvalRestart(pCsr, pRoot, &rc);
  116401. do {
  116402. fts3EvalNextRow(pCsr, pRoot, &rc);
  116403. assert( pRoot->bEof==0 );
  116404. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  116405. fts3EvalTestDeferredAndNear(pCsr, &rc);
  116406. }
  116407. }
  116408. return rc;
  116409. }
  116410. /*
  116411. ** This function is used by the matchinfo() module to query a phrase
  116412. ** expression node for the following information:
  116413. **
  116414. ** 1. The total number of occurrences of the phrase in each column of
  116415. ** the FTS table (considering all rows), and
  116416. **
  116417. ** 2. For each column, the number of rows in the table for which the
  116418. ** column contains at least one instance of the phrase.
  116419. **
  116420. ** If no error occurs, SQLITE_OK is returned and the values for each column
  116421. ** written into the array aiOut as follows:
  116422. **
  116423. ** aiOut[iCol*3 + 1] = Number of occurrences
  116424. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  116425. **
  116426. ** Caveats:
  116427. **
  116428. ** * If a phrase consists entirely of deferred tokens, then all output
  116429. ** values are set to the number of documents in the table. In other
  116430. ** words we assume that very common tokens occur exactly once in each
  116431. ** column of each row of the table.
  116432. **
  116433. ** * If a phrase contains some deferred tokens (and some non-deferred
  116434. ** tokens), count the potential occurrence identified by considering
  116435. ** the non-deferred tokens instead of actual phrase occurrences.
  116436. **
  116437. ** * If the phrase is part of a NEAR expression, then only phrase instances
  116438. ** that meet the NEAR constraint are included in the counts.
  116439. */
  116440. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  116441. Fts3Cursor *pCsr, /* FTS cursor handle */
  116442. Fts3Expr *pExpr, /* Phrase expression */
  116443. u32 *aiOut /* Array to write results into (see above) */
  116444. ){
  116445. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  116446. int rc = SQLITE_OK;
  116447. int iCol;
  116448. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  116449. assert( pCsr->nDoc>0 );
  116450. for(iCol=0; iCol<pTab->nColumn; iCol++){
  116451. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  116452. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  116453. }
  116454. }else{
  116455. rc = fts3EvalGatherStats(pCsr, pExpr);
  116456. if( rc==SQLITE_OK ){
  116457. assert( pExpr->aMI );
  116458. for(iCol=0; iCol<pTab->nColumn; iCol++){
  116459. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  116460. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  116461. }
  116462. }
  116463. }
  116464. return rc;
  116465. }
  116466. /*
  116467. ** The expression pExpr passed as the second argument to this function
  116468. ** must be of type FTSQUERY_PHRASE.
  116469. **
  116470. ** The returned value is either NULL or a pointer to a buffer containing
  116471. ** a position-list indicating the occurrences of the phrase in column iCol
  116472. ** of the current row.
  116473. **
  116474. ** More specifically, the returned buffer contains 1 varint for each
  116475. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  116476. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  116477. ** if the requested column contains "a b X c d X X" and the position-list
  116478. ** for 'X' is requested, the buffer returned may contain:
  116479. **
  116480. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  116481. **
  116482. ** This function works regardless of whether or not the phrase is deferred,
  116483. ** incremental, or neither.
  116484. */
  116485. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  116486. Fts3Cursor *pCsr, /* FTS3 cursor object */
  116487. Fts3Expr *pExpr, /* Phrase to return doclist for */
  116488. int iCol, /* Column to return position list for */
  116489. char **ppOut /* OUT: Pointer to position list */
  116490. ){
  116491. Fts3Phrase *pPhrase = pExpr->pPhrase;
  116492. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  116493. char *pIter;
  116494. int iThis;
  116495. sqlite3_int64 iDocid;
  116496. /* If this phrase is applies specifically to some column other than
  116497. ** column iCol, return a NULL pointer. */
  116498. *ppOut = 0;
  116499. assert( iCol>=0 && iCol<pTab->nColumn );
  116500. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  116501. return SQLITE_OK;
  116502. }
  116503. iDocid = pExpr->iDocid;
  116504. pIter = pPhrase->doclist.pList;
  116505. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  116506. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  116507. int bOr = 0;
  116508. u8 bEof = 0;
  116509. Fts3Expr *p;
  116510. /* Check if this phrase descends from an OR expression node. If not,
  116511. ** return NULL. Otherwise, the entry that corresponds to docid
  116512. ** pCsr->iPrevId may lie earlier in the doclist buffer. */
  116513. for(p=pExpr->pParent; p; p=p->pParent){
  116514. if( p->eType==FTSQUERY_OR ) bOr = 1;
  116515. }
  116516. if( bOr==0 ) return SQLITE_OK;
  116517. /* This is the descendent of an OR node. In this case we cannot use
  116518. ** an incremental phrase. Load the entire doclist for the phrase
  116519. ** into memory in this case. */
  116520. if( pPhrase->bIncr ){
  116521. int rc = SQLITE_OK;
  116522. int bEofSave = pExpr->bEof;
  116523. fts3EvalRestart(pCsr, pExpr, &rc);
  116524. while( rc==SQLITE_OK && !pExpr->bEof ){
  116525. fts3EvalNextRow(pCsr, pExpr, &rc);
  116526. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  116527. }
  116528. pIter = pPhrase->doclist.pList;
  116529. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  116530. if( rc!=SQLITE_OK ) return rc;
  116531. }
  116532. if( pExpr->bEof ){
  116533. pIter = 0;
  116534. iDocid = 0;
  116535. }
  116536. bEof = (pPhrase->doclist.nAll==0);
  116537. assert( bDescDoclist==0 || bDescDoclist==1 );
  116538. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  116539. if( pCsr->bDesc==bDescDoclist ){
  116540. int dummy;
  116541. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  116542. sqlite3Fts3DoclistPrev(
  116543. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  116544. &pIter, &iDocid, &dummy, &bEof
  116545. );
  116546. }
  116547. }else{
  116548. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  116549. sqlite3Fts3DoclistNext(
  116550. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  116551. &pIter, &iDocid, &bEof
  116552. );
  116553. }
  116554. }
  116555. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  116556. }
  116557. if( pIter==0 ) return SQLITE_OK;
  116558. if( *pIter==0x01 ){
  116559. pIter++;
  116560. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  116561. }else{
  116562. iThis = 0;
  116563. }
  116564. while( iThis<iCol ){
  116565. fts3ColumnlistCopy(0, &pIter);
  116566. if( *pIter==0x00 ) return 0;
  116567. pIter++;
  116568. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  116569. }
  116570. *ppOut = ((iCol==iThis)?pIter:0);
  116571. return SQLITE_OK;
  116572. }
  116573. /*
  116574. ** Free all components of the Fts3Phrase structure that were allocated by
  116575. ** the eval module. Specifically, this means to free:
  116576. **
  116577. ** * the contents of pPhrase->doclist, and
  116578. ** * any Fts3MultiSegReader objects held by phrase tokens.
  116579. */
  116580. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  116581. if( pPhrase ){
  116582. int i;
  116583. sqlite3_free(pPhrase->doclist.aAll);
  116584. fts3EvalInvalidatePoslist(pPhrase);
  116585. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  116586. for(i=0; i<pPhrase->nToken; i++){
  116587. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  116588. pPhrase->aToken[i].pSegcsr = 0;
  116589. }
  116590. }
  116591. }
  116592. /*
  116593. ** Return SQLITE_CORRUPT_VTAB.
  116594. */
  116595. #ifdef SQLITE_DEBUG
  116596. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  116597. return SQLITE_CORRUPT_VTAB;
  116598. }
  116599. #endif
  116600. #if !SQLITE_CORE
  116601. /*
  116602. ** Initialize API pointer table, if required.
  116603. */
  116604. SQLITE_API int sqlite3_extension_init(
  116605. sqlite3 *db,
  116606. char **pzErrMsg,
  116607. const sqlite3_api_routines *pApi
  116608. ){
  116609. SQLITE_EXTENSION_INIT2(pApi)
  116610. return sqlite3Fts3Init(db);
  116611. }
  116612. #endif
  116613. #endif
  116614. /************** End of fts3.c ************************************************/
  116615. /************** Begin file fts3_aux.c ****************************************/
  116616. /*
  116617. ** 2011 Jan 27
  116618. **
  116619. ** The author disclaims copyright to this source code. In place of
  116620. ** a legal notice, here is a blessing:
  116621. **
  116622. ** May you do good and not evil.
  116623. ** May you find forgiveness for yourself and forgive others.
  116624. ** May you share freely, never taking more than you give.
  116625. **
  116626. ******************************************************************************
  116627. **
  116628. */
  116629. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  116630. /* #include <string.h> */
  116631. /* #include <assert.h> */
  116632. typedef struct Fts3auxTable Fts3auxTable;
  116633. typedef struct Fts3auxCursor Fts3auxCursor;
  116634. struct Fts3auxTable {
  116635. sqlite3_vtab base; /* Base class used by SQLite core */
  116636. Fts3Table *pFts3Tab;
  116637. };
  116638. struct Fts3auxCursor {
  116639. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  116640. Fts3MultiSegReader csr; /* Must be right after "base" */
  116641. Fts3SegFilter filter;
  116642. char *zStop;
  116643. int nStop; /* Byte-length of string zStop */
  116644. int isEof; /* True if cursor is at EOF */
  116645. sqlite3_int64 iRowid; /* Current rowid */
  116646. int iCol; /* Current value of 'col' column */
  116647. int nStat; /* Size of aStat[] array */
  116648. struct Fts3auxColstats {
  116649. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  116650. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  116651. } *aStat;
  116652. };
  116653. /*
  116654. ** Schema of the terms table.
  116655. */
  116656. #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
  116657. /*
  116658. ** This function does all the work for both the xConnect and xCreate methods.
  116659. ** These tables have no persistent representation of their own, so xConnect
  116660. ** and xCreate are identical operations.
  116661. */
  116662. static int fts3auxConnectMethod(
  116663. sqlite3 *db, /* Database connection */
  116664. void *pUnused, /* Unused */
  116665. int argc, /* Number of elements in argv array */
  116666. const char * const *argv, /* xCreate/xConnect argument array */
  116667. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  116668. char **pzErr /* OUT: sqlite3_malloc'd error message */
  116669. ){
  116670. char const *zDb; /* Name of database (e.g. "main") */
  116671. char const *zFts3; /* Name of fts3 table */
  116672. int nDb; /* Result of strlen(zDb) */
  116673. int nFts3; /* Result of strlen(zFts3) */
  116674. int nByte; /* Bytes of space to allocate here */
  116675. int rc; /* value returned by declare_vtab() */
  116676. Fts3auxTable *p; /* Virtual table object to return */
  116677. UNUSED_PARAMETER(pUnused);
  116678. /* The user should invoke this in one of two forms:
  116679. **
  116680. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  116681. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  116682. */
  116683. if( argc!=4 && argc!=5 ) goto bad_args;
  116684. zDb = argv[1];
  116685. nDb = (int)strlen(zDb);
  116686. if( argc==5 ){
  116687. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  116688. zDb = argv[3];
  116689. nDb = (int)strlen(zDb);
  116690. zFts3 = argv[4];
  116691. }else{
  116692. goto bad_args;
  116693. }
  116694. }else{
  116695. zFts3 = argv[3];
  116696. }
  116697. nFts3 = (int)strlen(zFts3);
  116698. rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
  116699. if( rc!=SQLITE_OK ) return rc;
  116700. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  116701. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  116702. if( !p ) return SQLITE_NOMEM;
  116703. memset(p, 0, nByte);
  116704. p->pFts3Tab = (Fts3Table *)&p[1];
  116705. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  116706. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  116707. p->pFts3Tab->db = db;
  116708. p->pFts3Tab->nIndex = 1;
  116709. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  116710. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  116711. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  116712. *ppVtab = (sqlite3_vtab *)p;
  116713. return SQLITE_OK;
  116714. bad_args:
  116715. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  116716. return SQLITE_ERROR;
  116717. }
  116718. /*
  116719. ** This function does the work for both the xDisconnect and xDestroy methods.
  116720. ** These tables have no persistent representation of their own, so xDisconnect
  116721. ** and xDestroy are identical operations.
  116722. */
  116723. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  116724. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  116725. Fts3Table *pFts3 = p->pFts3Tab;
  116726. int i;
  116727. /* Free any prepared statements held */
  116728. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  116729. sqlite3_finalize(pFts3->aStmt[i]);
  116730. }
  116731. sqlite3_free(pFts3->zSegmentsTbl);
  116732. sqlite3_free(p);
  116733. return SQLITE_OK;
  116734. }
  116735. #define FTS4AUX_EQ_CONSTRAINT 1
  116736. #define FTS4AUX_GE_CONSTRAINT 2
  116737. #define FTS4AUX_LE_CONSTRAINT 4
  116738. /*
  116739. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  116740. */
  116741. static int fts3auxBestIndexMethod(
  116742. sqlite3_vtab *pVTab,
  116743. sqlite3_index_info *pInfo
  116744. ){
  116745. int i;
  116746. int iEq = -1;
  116747. int iGe = -1;
  116748. int iLe = -1;
  116749. UNUSED_PARAMETER(pVTab);
  116750. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  116751. if( pInfo->nOrderBy==1
  116752. && pInfo->aOrderBy[0].iColumn==0
  116753. && pInfo->aOrderBy[0].desc==0
  116754. ){
  116755. pInfo->orderByConsumed = 1;
  116756. }
  116757. /* Search for equality and range constraints on the "term" column. */
  116758. for(i=0; i<pInfo->nConstraint; i++){
  116759. if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
  116760. int op = pInfo->aConstraint[i].op;
  116761. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  116762. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  116763. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  116764. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  116765. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  116766. }
  116767. }
  116768. if( iEq>=0 ){
  116769. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  116770. pInfo->aConstraintUsage[iEq].argvIndex = 1;
  116771. pInfo->estimatedCost = 5;
  116772. }else{
  116773. pInfo->idxNum = 0;
  116774. pInfo->estimatedCost = 20000;
  116775. if( iGe>=0 ){
  116776. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  116777. pInfo->aConstraintUsage[iGe].argvIndex = 1;
  116778. pInfo->estimatedCost /= 2;
  116779. }
  116780. if( iLe>=0 ){
  116781. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  116782. pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
  116783. pInfo->estimatedCost /= 2;
  116784. }
  116785. }
  116786. return SQLITE_OK;
  116787. }
  116788. /*
  116789. ** xOpen - Open a cursor.
  116790. */
  116791. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  116792. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  116793. UNUSED_PARAMETER(pVTab);
  116794. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  116795. if( !pCsr ) return SQLITE_NOMEM;
  116796. memset(pCsr, 0, sizeof(Fts3auxCursor));
  116797. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  116798. return SQLITE_OK;
  116799. }
  116800. /*
  116801. ** xClose - Close a cursor.
  116802. */
  116803. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  116804. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  116805. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  116806. sqlite3Fts3SegmentsClose(pFts3);
  116807. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  116808. sqlite3_free((void *)pCsr->filter.zTerm);
  116809. sqlite3_free(pCsr->zStop);
  116810. sqlite3_free(pCsr->aStat);
  116811. sqlite3_free(pCsr);
  116812. return SQLITE_OK;
  116813. }
  116814. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  116815. if( nSize>pCsr->nStat ){
  116816. struct Fts3auxColstats *aNew;
  116817. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  116818. sizeof(struct Fts3auxColstats) * nSize
  116819. );
  116820. if( aNew==0 ) return SQLITE_NOMEM;
  116821. memset(&aNew[pCsr->nStat], 0,
  116822. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  116823. );
  116824. pCsr->aStat = aNew;
  116825. pCsr->nStat = nSize;
  116826. }
  116827. return SQLITE_OK;
  116828. }
  116829. /*
  116830. ** xNext - Advance the cursor to the next row, if any.
  116831. */
  116832. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  116833. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  116834. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  116835. int rc;
  116836. /* Increment our pretend rowid value. */
  116837. pCsr->iRowid++;
  116838. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  116839. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  116840. }
  116841. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  116842. if( rc==SQLITE_ROW ){
  116843. int i = 0;
  116844. int nDoclist = pCsr->csr.nDoclist;
  116845. char *aDoclist = pCsr->csr.aDoclist;
  116846. int iCol;
  116847. int eState = 0;
  116848. if( pCsr->zStop ){
  116849. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  116850. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  116851. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  116852. pCsr->isEof = 1;
  116853. return SQLITE_OK;
  116854. }
  116855. }
  116856. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  116857. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  116858. iCol = 0;
  116859. while( i<nDoclist ){
  116860. sqlite3_int64 v = 0;
  116861. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  116862. switch( eState ){
  116863. /* State 0. In this state the integer just read was a docid. */
  116864. case 0:
  116865. pCsr->aStat[0].nDoc++;
  116866. eState = 1;
  116867. iCol = 0;
  116868. break;
  116869. /* State 1. In this state we are expecting either a 1, indicating
  116870. ** that the following integer will be a column number, or the
  116871. ** start of a position list for column 0.
  116872. **
  116873. ** The only difference between state 1 and state 2 is that if the
  116874. ** integer encountered in state 1 is not 0 or 1, then we need to
  116875. ** increment the column 0 "nDoc" count for this term.
  116876. */
  116877. case 1:
  116878. assert( iCol==0 );
  116879. if( v>1 ){
  116880. pCsr->aStat[1].nDoc++;
  116881. }
  116882. eState = 2;
  116883. /* fall through */
  116884. case 2:
  116885. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  116886. eState = 0;
  116887. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  116888. eState = 3;
  116889. }else{ /* 2 or greater. A position. */
  116890. pCsr->aStat[iCol+1].nOcc++;
  116891. pCsr->aStat[0].nOcc++;
  116892. }
  116893. break;
  116894. /* State 3. The integer just read is a column number. */
  116895. default: assert( eState==3 );
  116896. iCol = (int)v;
  116897. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  116898. pCsr->aStat[iCol+1].nDoc++;
  116899. eState = 2;
  116900. break;
  116901. }
  116902. }
  116903. pCsr->iCol = 0;
  116904. rc = SQLITE_OK;
  116905. }else{
  116906. pCsr->isEof = 1;
  116907. }
  116908. return rc;
  116909. }
  116910. /*
  116911. ** xFilter - Initialize a cursor to point at the start of its data.
  116912. */
  116913. static int fts3auxFilterMethod(
  116914. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  116915. int idxNum, /* Strategy index */
  116916. const char *idxStr, /* Unused */
  116917. int nVal, /* Number of elements in apVal */
  116918. sqlite3_value **apVal /* Arguments for the indexing scheme */
  116919. ){
  116920. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  116921. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  116922. int rc;
  116923. int isScan;
  116924. UNUSED_PARAMETER(nVal);
  116925. UNUSED_PARAMETER(idxStr);
  116926. assert( idxStr==0 );
  116927. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  116928. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  116929. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  116930. );
  116931. isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
  116932. /* In case this cursor is being reused, close and zero it. */
  116933. testcase(pCsr->filter.zTerm);
  116934. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  116935. sqlite3_free((void *)pCsr->filter.zTerm);
  116936. sqlite3_free(pCsr->aStat);
  116937. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  116938. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  116939. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  116940. if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
  116941. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  116942. if( zStr ){
  116943. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  116944. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  116945. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  116946. }
  116947. }
  116948. if( idxNum&FTS4AUX_LE_CONSTRAINT ){
  116949. int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
  116950. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
  116951. pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
  116952. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  116953. }
  116954. rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
  116955. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  116956. );
  116957. if( rc==SQLITE_OK ){
  116958. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  116959. }
  116960. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  116961. return rc;
  116962. }
  116963. /*
  116964. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  116965. */
  116966. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  116967. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  116968. return pCsr->isEof;
  116969. }
  116970. /*
  116971. ** xColumn - Return a column value.
  116972. */
  116973. static int fts3auxColumnMethod(
  116974. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  116975. sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
  116976. int iCol /* Index of column to read value from */
  116977. ){
  116978. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  116979. assert( p->isEof==0 );
  116980. if( iCol==0 ){ /* Column "term" */
  116981. sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  116982. }else if( iCol==1 ){ /* Column "col" */
  116983. if( p->iCol ){
  116984. sqlite3_result_int(pContext, p->iCol-1);
  116985. }else{
  116986. sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
  116987. }
  116988. }else if( iCol==2 ){ /* Column "documents" */
  116989. sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
  116990. }else{ /* Column "occurrences" */
  116991. sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
  116992. }
  116993. return SQLITE_OK;
  116994. }
  116995. /*
  116996. ** xRowid - Return the current rowid for the cursor.
  116997. */
  116998. static int fts3auxRowidMethod(
  116999. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  117000. sqlite_int64 *pRowid /* OUT: Rowid value */
  117001. ){
  117002. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  117003. *pRowid = pCsr->iRowid;
  117004. return SQLITE_OK;
  117005. }
  117006. /*
  117007. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  117008. ** if successful or an error code if sqlite3_create_module() fails.
  117009. */
  117010. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  117011. static const sqlite3_module fts3aux_module = {
  117012. 0, /* iVersion */
  117013. fts3auxConnectMethod, /* xCreate */
  117014. fts3auxConnectMethod, /* xConnect */
  117015. fts3auxBestIndexMethod, /* xBestIndex */
  117016. fts3auxDisconnectMethod, /* xDisconnect */
  117017. fts3auxDisconnectMethod, /* xDestroy */
  117018. fts3auxOpenMethod, /* xOpen */
  117019. fts3auxCloseMethod, /* xClose */
  117020. fts3auxFilterMethod, /* xFilter */
  117021. fts3auxNextMethod, /* xNext */
  117022. fts3auxEofMethod, /* xEof */
  117023. fts3auxColumnMethod, /* xColumn */
  117024. fts3auxRowidMethod, /* xRowid */
  117025. 0, /* xUpdate */
  117026. 0, /* xBegin */
  117027. 0, /* xSync */
  117028. 0, /* xCommit */
  117029. 0, /* xRollback */
  117030. 0, /* xFindFunction */
  117031. 0, /* xRename */
  117032. 0, /* xSavepoint */
  117033. 0, /* xRelease */
  117034. 0 /* xRollbackTo */
  117035. };
  117036. int rc; /* Return code */
  117037. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  117038. return rc;
  117039. }
  117040. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  117041. /************** End of fts3_aux.c ********************************************/
  117042. /************** Begin file fts3_expr.c ***************************************/
  117043. /*
  117044. ** 2008 Nov 28
  117045. **
  117046. ** The author disclaims copyright to this source code. In place of
  117047. ** a legal notice, here is a blessing:
  117048. **
  117049. ** May you do good and not evil.
  117050. ** May you find forgiveness for yourself and forgive others.
  117051. ** May you share freely, never taking more than you give.
  117052. **
  117053. ******************************************************************************
  117054. **
  117055. ** This module contains code that implements a parser for fts3 query strings
  117056. ** (the right-hand argument to the MATCH operator). Because the supported
  117057. ** syntax is relatively simple, the whole tokenizer/parser system is
  117058. ** hand-coded.
  117059. */
  117060. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117061. /*
  117062. ** By default, this module parses the legacy syntax that has been
  117063. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  117064. ** is defined, then it uses the new syntax. The differences between
  117065. ** the new and the old syntaxes are:
  117066. **
  117067. ** a) The new syntax supports parenthesis. The old does not.
  117068. **
  117069. ** b) The new syntax supports the AND and NOT operators. The old does not.
  117070. **
  117071. ** c) The old syntax supports the "-" token qualifier. This is not
  117072. ** supported by the new syntax (it is replaced by the NOT operator).
  117073. **
  117074. ** d) When using the old syntax, the OR operator has a greater precedence
  117075. ** than an implicit AND. When using the new, both implicity and explicit
  117076. ** AND operators have a higher precedence than OR.
  117077. **
  117078. ** If compiled with SQLITE_TEST defined, then this module exports the
  117079. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  117080. ** to zero causes the module to use the old syntax. If it is set to
  117081. ** non-zero the new syntax is activated. This is so both syntaxes can
  117082. ** be tested using a single build of testfixture.
  117083. **
  117084. ** The following describes the syntax supported by the fts3 MATCH
  117085. ** operator in a similar format to that used by the lemon parser
  117086. ** generator. This module does not use actually lemon, it uses a
  117087. ** custom parser.
  117088. **
  117089. ** query ::= andexpr (OR andexpr)*.
  117090. **
  117091. ** andexpr ::= notexpr (AND? notexpr)*.
  117092. **
  117093. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  117094. ** notexpr ::= LP query RP.
  117095. **
  117096. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  117097. **
  117098. ** distance_opt ::= .
  117099. ** distance_opt ::= / INTEGER.
  117100. **
  117101. ** phrase ::= TOKEN.
  117102. ** phrase ::= COLUMN:TOKEN.
  117103. ** phrase ::= "TOKEN TOKEN TOKEN...".
  117104. */
  117105. #ifdef SQLITE_TEST
  117106. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  117107. #else
  117108. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  117109. # define sqlite3_fts3_enable_parentheses 1
  117110. # else
  117111. # define sqlite3_fts3_enable_parentheses 0
  117112. # endif
  117113. #endif
  117114. /*
  117115. ** Default span for NEAR operators.
  117116. */
  117117. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  117118. /* #include <string.h> */
  117119. /* #include <assert.h> */
  117120. /*
  117121. ** isNot:
  117122. ** This variable is used by function getNextNode(). When getNextNode() is
  117123. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  117124. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  117125. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  117126. ** zero.
  117127. */
  117128. typedef struct ParseContext ParseContext;
  117129. struct ParseContext {
  117130. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  117131. int iLangid; /* Language id used with tokenizer */
  117132. const char **azCol; /* Array of column names for fts3 table */
  117133. int bFts4; /* True to allow FTS4-only syntax */
  117134. int nCol; /* Number of entries in azCol[] */
  117135. int iDefaultCol; /* Default column to query */
  117136. int isNot; /* True if getNextNode() sees a unary - */
  117137. sqlite3_context *pCtx; /* Write error message here */
  117138. int nNest; /* Number of nested brackets */
  117139. };
  117140. /*
  117141. ** This function is equivalent to the standard isspace() function.
  117142. **
  117143. ** The standard isspace() can be awkward to use safely, because although it
  117144. ** is defined to accept an argument of type int, its behavior when passed
  117145. ** an integer that falls outside of the range of the unsigned char type
  117146. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  117147. ** is defined to accept an argument of type char, and always returns 0 for
  117148. ** any values that fall outside of the range of the unsigned char type (i.e.
  117149. ** negative values).
  117150. */
  117151. static int fts3isspace(char c){
  117152. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  117153. }
  117154. /*
  117155. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  117156. ** zero the memory before returning a pointer to it. If unsuccessful,
  117157. ** return NULL.
  117158. */
  117159. static void *fts3MallocZero(int nByte){
  117160. void *pRet = sqlite3_malloc(nByte);
  117161. if( pRet ) memset(pRet, 0, nByte);
  117162. return pRet;
  117163. }
  117164. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  117165. sqlite3_tokenizer *pTokenizer,
  117166. int iLangid,
  117167. const char *z,
  117168. int n,
  117169. sqlite3_tokenizer_cursor **ppCsr
  117170. ){
  117171. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  117172. sqlite3_tokenizer_cursor *pCsr = 0;
  117173. int rc;
  117174. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  117175. assert( rc==SQLITE_OK || pCsr==0 );
  117176. if( rc==SQLITE_OK ){
  117177. pCsr->pTokenizer = pTokenizer;
  117178. if( pModule->iVersion>=1 ){
  117179. rc = pModule->xLanguageid(pCsr, iLangid);
  117180. if( rc!=SQLITE_OK ){
  117181. pModule->xClose(pCsr);
  117182. pCsr = 0;
  117183. }
  117184. }
  117185. }
  117186. *ppCsr = pCsr;
  117187. return rc;
  117188. }
  117189. /*
  117190. ** Extract the next token from buffer z (length n) using the tokenizer
  117191. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  117192. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  117193. ** single token and set *ppExpr to point to it. If the end of the buffer is
  117194. ** reached before a token is found, set *ppExpr to zero. It is the
  117195. ** responsibility of the caller to eventually deallocate the allocated
  117196. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  117197. **
  117198. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  117199. ** fails.
  117200. */
  117201. static int getNextToken(
  117202. ParseContext *pParse, /* fts3 query parse context */
  117203. int iCol, /* Value for Fts3Phrase.iColumn */
  117204. const char *z, int n, /* Input string */
  117205. Fts3Expr **ppExpr, /* OUT: expression */
  117206. int *pnConsumed /* OUT: Number of bytes consumed */
  117207. ){
  117208. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  117209. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  117210. int rc;
  117211. sqlite3_tokenizer_cursor *pCursor;
  117212. Fts3Expr *pRet = 0;
  117213. int nConsumed = 0;
  117214. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  117215. if( rc==SQLITE_OK ){
  117216. const char *zToken;
  117217. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  117218. int nByte; /* total space to allocate */
  117219. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  117220. if( rc==SQLITE_OK ){
  117221. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  117222. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  117223. if( !pRet ){
  117224. rc = SQLITE_NOMEM;
  117225. }else{
  117226. pRet->eType = FTSQUERY_PHRASE;
  117227. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  117228. pRet->pPhrase->nToken = 1;
  117229. pRet->pPhrase->iColumn = iCol;
  117230. pRet->pPhrase->aToken[0].n = nToken;
  117231. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  117232. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  117233. if( iEnd<n && z[iEnd]=='*' ){
  117234. pRet->pPhrase->aToken[0].isPrefix = 1;
  117235. iEnd++;
  117236. }
  117237. while( 1 ){
  117238. if( !sqlite3_fts3_enable_parentheses
  117239. && iStart>0 && z[iStart-1]=='-'
  117240. ){
  117241. pParse->isNot = 1;
  117242. iStart--;
  117243. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  117244. pRet->pPhrase->aToken[0].bFirst = 1;
  117245. iStart--;
  117246. }else{
  117247. break;
  117248. }
  117249. }
  117250. }
  117251. nConsumed = iEnd;
  117252. }
  117253. pModule->xClose(pCursor);
  117254. }
  117255. *pnConsumed = nConsumed;
  117256. *ppExpr = pRet;
  117257. return rc;
  117258. }
  117259. /*
  117260. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  117261. ** then free the old allocation.
  117262. */
  117263. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  117264. void *pRet = sqlite3_realloc(pOrig, nNew);
  117265. if( !pRet ){
  117266. sqlite3_free(pOrig);
  117267. }
  117268. return pRet;
  117269. }
  117270. /*
  117271. ** Buffer zInput, length nInput, contains the contents of a quoted string
  117272. ** that appeared as part of an fts3 query expression. Neither quote character
  117273. ** is included in the buffer. This function attempts to tokenize the entire
  117274. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  117275. ** containing the results.
  117276. **
  117277. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  117278. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  117279. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  117280. ** to 0.
  117281. */
  117282. static int getNextString(
  117283. ParseContext *pParse, /* fts3 query parse context */
  117284. const char *zInput, int nInput, /* Input string */
  117285. Fts3Expr **ppExpr /* OUT: expression */
  117286. ){
  117287. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  117288. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  117289. int rc;
  117290. Fts3Expr *p = 0;
  117291. sqlite3_tokenizer_cursor *pCursor = 0;
  117292. char *zTemp = 0;
  117293. int nTemp = 0;
  117294. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  117295. int nToken = 0;
  117296. /* The final Fts3Expr data structure, including the Fts3Phrase,
  117297. ** Fts3PhraseToken structures token buffers are all stored as a single
  117298. ** allocation so that the expression can be freed with a single call to
  117299. ** sqlite3_free(). Setting this up requires a two pass approach.
  117300. **
  117301. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  117302. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  117303. ** to assemble data in two dynamic buffers:
  117304. **
  117305. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  117306. ** structure, followed by the array of Fts3PhraseToken
  117307. ** structures. This pass only populates the Fts3PhraseToken array.
  117308. **
  117309. ** Buffer zTemp: Contains copies of all tokens.
  117310. **
  117311. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  117312. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  117313. ** structures.
  117314. */
  117315. rc = sqlite3Fts3OpenTokenizer(
  117316. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  117317. if( rc==SQLITE_OK ){
  117318. int ii;
  117319. for(ii=0; rc==SQLITE_OK; ii++){
  117320. const char *zByte;
  117321. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  117322. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  117323. if( rc==SQLITE_OK ){
  117324. Fts3PhraseToken *pToken;
  117325. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  117326. if( !p ) goto no_mem;
  117327. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  117328. if( !zTemp ) goto no_mem;
  117329. assert( nToken==ii );
  117330. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  117331. memset(pToken, 0, sizeof(Fts3PhraseToken));
  117332. memcpy(&zTemp[nTemp], zByte, nByte);
  117333. nTemp += nByte;
  117334. pToken->n = nByte;
  117335. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  117336. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  117337. nToken = ii+1;
  117338. }
  117339. }
  117340. pModule->xClose(pCursor);
  117341. pCursor = 0;
  117342. }
  117343. if( rc==SQLITE_DONE ){
  117344. int jj;
  117345. char *zBuf = 0;
  117346. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  117347. if( !p ) goto no_mem;
  117348. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  117349. p->eType = FTSQUERY_PHRASE;
  117350. p->pPhrase = (Fts3Phrase *)&p[1];
  117351. p->pPhrase->iColumn = pParse->iDefaultCol;
  117352. p->pPhrase->nToken = nToken;
  117353. zBuf = (char *)&p->pPhrase->aToken[nToken];
  117354. if( zTemp ){
  117355. memcpy(zBuf, zTemp, nTemp);
  117356. sqlite3_free(zTemp);
  117357. }else{
  117358. assert( nTemp==0 );
  117359. }
  117360. for(jj=0; jj<p->pPhrase->nToken; jj++){
  117361. p->pPhrase->aToken[jj].z = zBuf;
  117362. zBuf += p->pPhrase->aToken[jj].n;
  117363. }
  117364. rc = SQLITE_OK;
  117365. }
  117366. *ppExpr = p;
  117367. return rc;
  117368. no_mem:
  117369. if( pCursor ){
  117370. pModule->xClose(pCursor);
  117371. }
  117372. sqlite3_free(zTemp);
  117373. sqlite3_free(p);
  117374. *ppExpr = 0;
  117375. return SQLITE_NOMEM;
  117376. }
  117377. /*
  117378. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  117379. ** call fts3ExprParse(). So this forward declaration is required.
  117380. */
  117381. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  117382. /*
  117383. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  117384. ** structure, or set to 0 if the end of the input buffer is reached.
  117385. **
  117386. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  117387. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  117388. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  117389. */
  117390. static int getNextNode(
  117391. ParseContext *pParse, /* fts3 query parse context */
  117392. const char *z, int n, /* Input string */
  117393. Fts3Expr **ppExpr, /* OUT: expression */
  117394. int *pnConsumed /* OUT: Number of bytes consumed */
  117395. ){
  117396. static const struct Fts3Keyword {
  117397. char *z; /* Keyword text */
  117398. unsigned char n; /* Length of the keyword */
  117399. unsigned char parenOnly; /* Only valid in paren mode */
  117400. unsigned char eType; /* Keyword code */
  117401. } aKeyword[] = {
  117402. { "OR" , 2, 0, FTSQUERY_OR },
  117403. { "AND", 3, 1, FTSQUERY_AND },
  117404. { "NOT", 3, 1, FTSQUERY_NOT },
  117405. { "NEAR", 4, 0, FTSQUERY_NEAR }
  117406. };
  117407. int ii;
  117408. int iCol;
  117409. int iColLen;
  117410. int rc;
  117411. Fts3Expr *pRet = 0;
  117412. const char *zInput = z;
  117413. int nInput = n;
  117414. pParse->isNot = 0;
  117415. /* Skip over any whitespace before checking for a keyword, an open or
  117416. ** close bracket, or a quoted string.
  117417. */
  117418. while( nInput>0 && fts3isspace(*zInput) ){
  117419. nInput--;
  117420. zInput++;
  117421. }
  117422. if( nInput==0 ){
  117423. return SQLITE_DONE;
  117424. }
  117425. /* See if we are dealing with a keyword. */
  117426. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  117427. const struct Fts3Keyword *pKey = &aKeyword[ii];
  117428. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  117429. continue;
  117430. }
  117431. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  117432. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  117433. int nKey = pKey->n;
  117434. char cNext;
  117435. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  117436. if( pKey->eType==FTSQUERY_NEAR ){
  117437. assert( nKey==4 );
  117438. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  117439. nNear = 0;
  117440. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  117441. nNear = nNear * 10 + (zInput[nKey] - '0');
  117442. }
  117443. }
  117444. }
  117445. /* At this point this is probably a keyword. But for that to be true,
  117446. ** the next byte must contain either whitespace, an open or close
  117447. ** parenthesis, a quote character, or EOF.
  117448. */
  117449. cNext = zInput[nKey];
  117450. if( fts3isspace(cNext)
  117451. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  117452. ){
  117453. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  117454. if( !pRet ){
  117455. return SQLITE_NOMEM;
  117456. }
  117457. pRet->eType = pKey->eType;
  117458. pRet->nNear = nNear;
  117459. *ppExpr = pRet;
  117460. *pnConsumed = (int)((zInput - z) + nKey);
  117461. return SQLITE_OK;
  117462. }
  117463. /* Turns out that wasn't a keyword after all. This happens if the
  117464. ** user has supplied a token such as "ORacle". Continue.
  117465. */
  117466. }
  117467. }
  117468. /* Check for an open bracket. */
  117469. if( sqlite3_fts3_enable_parentheses ){
  117470. if( *zInput=='(' ){
  117471. int nConsumed;
  117472. pParse->nNest++;
  117473. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  117474. if( rc==SQLITE_OK && !*ppExpr ){
  117475. rc = SQLITE_DONE;
  117476. }
  117477. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  117478. return rc;
  117479. }
  117480. /* Check for a close bracket. */
  117481. if( *zInput==')' ){
  117482. pParse->nNest--;
  117483. *pnConsumed = (int)((zInput - z) + 1);
  117484. return SQLITE_DONE;
  117485. }
  117486. }
  117487. /* See if we are dealing with a quoted phrase. If this is the case, then
  117488. ** search for the closing quote and pass the whole string to getNextString()
  117489. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  117490. ** a quote character embedded in a string.
  117491. */
  117492. if( *zInput=='"' ){
  117493. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  117494. *pnConsumed = (int)((zInput - z) + ii + 1);
  117495. if( ii==nInput ){
  117496. return SQLITE_ERROR;
  117497. }
  117498. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  117499. }
  117500. /* If control flows to this point, this must be a regular token, or
  117501. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  117502. ** interface. Before doing so, figure out if there is an explicit
  117503. ** column specifier for the token.
  117504. **
  117505. ** TODO: Strangely, it is not possible to associate a column specifier
  117506. ** with a quoted phrase, only with a single token. Not sure if this was
  117507. ** an implementation artifact or an intentional decision when fts3 was
  117508. ** first implemented. Whichever it was, this module duplicates the
  117509. ** limitation.
  117510. */
  117511. iCol = pParse->iDefaultCol;
  117512. iColLen = 0;
  117513. for(ii=0; ii<pParse->nCol; ii++){
  117514. const char *zStr = pParse->azCol[ii];
  117515. int nStr = (int)strlen(zStr);
  117516. if( nInput>nStr && zInput[nStr]==':'
  117517. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  117518. ){
  117519. iCol = ii;
  117520. iColLen = (int)((zInput - z) + nStr + 1);
  117521. break;
  117522. }
  117523. }
  117524. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  117525. *pnConsumed += iColLen;
  117526. return rc;
  117527. }
  117528. /*
  117529. ** The argument is an Fts3Expr structure for a binary operator (any type
  117530. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  117531. ** precedence of the operator. Lower values have a higher precedence (i.e.
  117532. ** group more tightly). For example, in the C language, the == operator
  117533. ** groups more tightly than ||, and would therefore have a higher precedence.
  117534. **
  117535. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  117536. ** is defined), the order of the operators in precedence from highest to
  117537. ** lowest is:
  117538. **
  117539. ** NEAR
  117540. ** NOT
  117541. ** AND (including implicit ANDs)
  117542. ** OR
  117543. **
  117544. ** Note that when using the old query syntax, the OR operator has a higher
  117545. ** precedence than the AND operator.
  117546. */
  117547. static int opPrecedence(Fts3Expr *p){
  117548. assert( p->eType!=FTSQUERY_PHRASE );
  117549. if( sqlite3_fts3_enable_parentheses ){
  117550. return p->eType;
  117551. }else if( p->eType==FTSQUERY_NEAR ){
  117552. return 1;
  117553. }else if( p->eType==FTSQUERY_OR ){
  117554. return 2;
  117555. }
  117556. assert( p->eType==FTSQUERY_AND );
  117557. return 3;
  117558. }
  117559. /*
  117560. ** Argument ppHead contains a pointer to the current head of a query
  117561. ** expression tree being parsed. pPrev is the expression node most recently
  117562. ** inserted into the tree. This function adds pNew, which is always a binary
  117563. ** operator node, into the expression tree based on the relative precedence
  117564. ** of pNew and the existing nodes of the tree. This may result in the head
  117565. ** of the tree changing, in which case *ppHead is set to the new root node.
  117566. */
  117567. static void insertBinaryOperator(
  117568. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  117569. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  117570. Fts3Expr *pNew /* New binary node to insert into expression tree */
  117571. ){
  117572. Fts3Expr *pSplit = pPrev;
  117573. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  117574. pSplit = pSplit->pParent;
  117575. }
  117576. if( pSplit->pParent ){
  117577. assert( pSplit->pParent->pRight==pSplit );
  117578. pSplit->pParent->pRight = pNew;
  117579. pNew->pParent = pSplit->pParent;
  117580. }else{
  117581. *ppHead = pNew;
  117582. }
  117583. pNew->pLeft = pSplit;
  117584. pSplit->pParent = pNew;
  117585. }
  117586. /*
  117587. ** Parse the fts3 query expression found in buffer z, length n. This function
  117588. ** returns either when the end of the buffer is reached or an unmatched
  117589. ** closing bracket - ')' - is encountered.
  117590. **
  117591. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  117592. ** parsed form of the expression and *pnConsumed is set to the number of
  117593. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  117594. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  117595. */
  117596. static int fts3ExprParse(
  117597. ParseContext *pParse, /* fts3 query parse context */
  117598. const char *z, int n, /* Text of MATCH query */
  117599. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  117600. int *pnConsumed /* OUT: Number of bytes consumed */
  117601. ){
  117602. Fts3Expr *pRet = 0;
  117603. Fts3Expr *pPrev = 0;
  117604. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  117605. int nIn = n;
  117606. const char *zIn = z;
  117607. int rc = SQLITE_OK;
  117608. int isRequirePhrase = 1;
  117609. while( rc==SQLITE_OK ){
  117610. Fts3Expr *p = 0;
  117611. int nByte = 0;
  117612. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  117613. if( rc==SQLITE_OK ){
  117614. int isPhrase;
  117615. if( !sqlite3_fts3_enable_parentheses
  117616. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  117617. ){
  117618. /* Create an implicit NOT operator. */
  117619. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  117620. if( !pNot ){
  117621. sqlite3Fts3ExprFree(p);
  117622. rc = SQLITE_NOMEM;
  117623. goto exprparse_out;
  117624. }
  117625. pNot->eType = FTSQUERY_NOT;
  117626. pNot->pRight = p;
  117627. p->pParent = pNot;
  117628. if( pNotBranch ){
  117629. pNot->pLeft = pNotBranch;
  117630. pNotBranch->pParent = pNot;
  117631. }
  117632. pNotBranch = pNot;
  117633. p = pPrev;
  117634. }else{
  117635. int eType = p->eType;
  117636. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  117637. /* The isRequirePhrase variable is set to true if a phrase or
  117638. ** an expression contained in parenthesis is required. If a
  117639. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  117640. ** isRequirePhrase is set, this is a syntax error.
  117641. */
  117642. if( !isPhrase && isRequirePhrase ){
  117643. sqlite3Fts3ExprFree(p);
  117644. rc = SQLITE_ERROR;
  117645. goto exprparse_out;
  117646. }
  117647. if( isPhrase && !isRequirePhrase ){
  117648. /* Insert an implicit AND operator. */
  117649. Fts3Expr *pAnd;
  117650. assert( pRet && pPrev );
  117651. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  117652. if( !pAnd ){
  117653. sqlite3Fts3ExprFree(p);
  117654. rc = SQLITE_NOMEM;
  117655. goto exprparse_out;
  117656. }
  117657. pAnd->eType = FTSQUERY_AND;
  117658. insertBinaryOperator(&pRet, pPrev, pAnd);
  117659. pPrev = pAnd;
  117660. }
  117661. /* This test catches attempts to make either operand of a NEAR
  117662. ** operator something other than a phrase. For example, either of
  117663. ** the following:
  117664. **
  117665. ** (bracketed expression) NEAR phrase
  117666. ** phrase NEAR (bracketed expression)
  117667. **
  117668. ** Return an error in either case.
  117669. */
  117670. if( pPrev && (
  117671. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  117672. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  117673. )){
  117674. sqlite3Fts3ExprFree(p);
  117675. rc = SQLITE_ERROR;
  117676. goto exprparse_out;
  117677. }
  117678. if( isPhrase ){
  117679. if( pRet ){
  117680. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  117681. pPrev->pRight = p;
  117682. p->pParent = pPrev;
  117683. }else{
  117684. pRet = p;
  117685. }
  117686. }else{
  117687. insertBinaryOperator(&pRet, pPrev, p);
  117688. }
  117689. isRequirePhrase = !isPhrase;
  117690. }
  117691. assert( nByte>0 );
  117692. }
  117693. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  117694. nIn -= nByte;
  117695. zIn += nByte;
  117696. pPrev = p;
  117697. }
  117698. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  117699. rc = SQLITE_ERROR;
  117700. }
  117701. if( rc==SQLITE_DONE ){
  117702. rc = SQLITE_OK;
  117703. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  117704. if( !pRet ){
  117705. rc = SQLITE_ERROR;
  117706. }else{
  117707. Fts3Expr *pIter = pNotBranch;
  117708. while( pIter->pLeft ){
  117709. pIter = pIter->pLeft;
  117710. }
  117711. pIter->pLeft = pRet;
  117712. pRet->pParent = pIter;
  117713. pRet = pNotBranch;
  117714. }
  117715. }
  117716. }
  117717. *pnConsumed = n - nIn;
  117718. exprparse_out:
  117719. if( rc!=SQLITE_OK ){
  117720. sqlite3Fts3ExprFree(pRet);
  117721. sqlite3Fts3ExprFree(pNotBranch);
  117722. pRet = 0;
  117723. }
  117724. *ppExpr = pRet;
  117725. return rc;
  117726. }
  117727. /*
  117728. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  117729. ** as the only argument is more than nMaxDepth.
  117730. */
  117731. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  117732. int rc = SQLITE_OK;
  117733. if( p ){
  117734. if( nMaxDepth<0 ){
  117735. rc = SQLITE_TOOBIG;
  117736. }else{
  117737. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  117738. if( rc==SQLITE_OK ){
  117739. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  117740. }
  117741. }
  117742. }
  117743. return rc;
  117744. }
  117745. /*
  117746. ** This function attempts to transform the expression tree at (*pp) to
  117747. ** an equivalent but more balanced form. The tree is modified in place.
  117748. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  117749. ** new root expression node.
  117750. **
  117751. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  117752. **
  117753. ** Otherwise, if an error occurs, an SQLite error code is returned and
  117754. ** expression (*pp) freed.
  117755. */
  117756. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  117757. int rc = SQLITE_OK; /* Return code */
  117758. Fts3Expr *pRoot = *pp; /* Initial root node */
  117759. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  117760. int eType = pRoot->eType; /* Type of node in this tree */
  117761. if( nMaxDepth==0 ){
  117762. rc = SQLITE_ERROR;
  117763. }
  117764. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  117765. Fts3Expr **apLeaf;
  117766. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  117767. if( 0==apLeaf ){
  117768. rc = SQLITE_NOMEM;
  117769. }else{
  117770. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  117771. }
  117772. if( rc==SQLITE_OK ){
  117773. int i;
  117774. Fts3Expr *p;
  117775. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  117776. for(p=pRoot; p->eType==eType; p=p->pLeft){
  117777. assert( p->pParent==0 || p->pParent->pLeft==p );
  117778. assert( p->pLeft && p->pRight );
  117779. }
  117780. /* This loop runs once for each leaf in the tree of eType nodes. */
  117781. while( 1 ){
  117782. int iLvl;
  117783. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  117784. assert( pParent==0 || pParent->pLeft==p );
  117785. p->pParent = 0;
  117786. if( pParent ){
  117787. pParent->pLeft = 0;
  117788. }else{
  117789. pRoot = 0;
  117790. }
  117791. rc = fts3ExprBalance(&p, nMaxDepth-1);
  117792. if( rc!=SQLITE_OK ) break;
  117793. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  117794. if( apLeaf[iLvl]==0 ){
  117795. apLeaf[iLvl] = p;
  117796. p = 0;
  117797. }else{
  117798. assert( pFree );
  117799. pFree->pLeft = apLeaf[iLvl];
  117800. pFree->pRight = p;
  117801. pFree->pLeft->pParent = pFree;
  117802. pFree->pRight->pParent = pFree;
  117803. p = pFree;
  117804. pFree = pFree->pParent;
  117805. p->pParent = 0;
  117806. apLeaf[iLvl] = 0;
  117807. }
  117808. }
  117809. if( p ){
  117810. sqlite3Fts3ExprFree(p);
  117811. rc = SQLITE_TOOBIG;
  117812. break;
  117813. }
  117814. /* If that was the last leaf node, break out of the loop */
  117815. if( pParent==0 ) break;
  117816. /* Set $p to point to the next leaf in the tree of eType nodes */
  117817. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  117818. /* Remove pParent from the original tree. */
  117819. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  117820. pParent->pRight->pParent = pParent->pParent;
  117821. if( pParent->pParent ){
  117822. pParent->pParent->pLeft = pParent->pRight;
  117823. }else{
  117824. assert( pParent==pRoot );
  117825. pRoot = pParent->pRight;
  117826. }
  117827. /* Link pParent into the free node list. It will be used as an
  117828. ** internal node of the new tree. */
  117829. pParent->pParent = pFree;
  117830. pFree = pParent;
  117831. }
  117832. if( rc==SQLITE_OK ){
  117833. p = 0;
  117834. for(i=0; i<nMaxDepth; i++){
  117835. if( apLeaf[i] ){
  117836. if( p==0 ){
  117837. p = apLeaf[i];
  117838. p->pParent = 0;
  117839. }else{
  117840. assert( pFree!=0 );
  117841. pFree->pRight = p;
  117842. pFree->pLeft = apLeaf[i];
  117843. pFree->pLeft->pParent = pFree;
  117844. pFree->pRight->pParent = pFree;
  117845. p = pFree;
  117846. pFree = pFree->pParent;
  117847. p->pParent = 0;
  117848. }
  117849. }
  117850. }
  117851. pRoot = p;
  117852. }else{
  117853. /* An error occurred. Delete the contents of the apLeaf[] array
  117854. ** and pFree list. Everything else is cleaned up by the call to
  117855. ** sqlite3Fts3ExprFree(pRoot) below. */
  117856. Fts3Expr *pDel;
  117857. for(i=0; i<nMaxDepth; i++){
  117858. sqlite3Fts3ExprFree(apLeaf[i]);
  117859. }
  117860. while( (pDel=pFree)!=0 ){
  117861. pFree = pDel->pParent;
  117862. sqlite3_free(pDel);
  117863. }
  117864. }
  117865. assert( pFree==0 );
  117866. sqlite3_free( apLeaf );
  117867. }
  117868. }
  117869. if( rc!=SQLITE_OK ){
  117870. sqlite3Fts3ExprFree(pRoot);
  117871. pRoot = 0;
  117872. }
  117873. *pp = pRoot;
  117874. return rc;
  117875. }
  117876. /*
  117877. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  117878. ** differences:
  117879. **
  117880. ** 1. It does not do expression rebalancing.
  117881. ** 2. It does not check that the expression does not exceed the
  117882. ** maximum allowable depth.
  117883. ** 3. Even if it fails, *ppExpr may still be set to point to an
  117884. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  117885. ** in this case.
  117886. */
  117887. static int fts3ExprParseUnbalanced(
  117888. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  117889. int iLangid, /* Language id for tokenizer */
  117890. char **azCol, /* Array of column names for fts3 table */
  117891. int bFts4, /* True to allow FTS4-only syntax */
  117892. int nCol, /* Number of entries in azCol[] */
  117893. int iDefaultCol, /* Default column to query */
  117894. const char *z, int n, /* Text of MATCH query */
  117895. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  117896. ){
  117897. int nParsed;
  117898. int rc;
  117899. ParseContext sParse;
  117900. memset(&sParse, 0, sizeof(ParseContext));
  117901. sParse.pTokenizer = pTokenizer;
  117902. sParse.iLangid = iLangid;
  117903. sParse.azCol = (const char **)azCol;
  117904. sParse.nCol = nCol;
  117905. sParse.iDefaultCol = iDefaultCol;
  117906. sParse.bFts4 = bFts4;
  117907. if( z==0 ){
  117908. *ppExpr = 0;
  117909. return SQLITE_OK;
  117910. }
  117911. if( n<0 ){
  117912. n = (int)strlen(z);
  117913. }
  117914. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  117915. assert( rc==SQLITE_OK || *ppExpr==0 );
  117916. /* Check for mismatched parenthesis */
  117917. if( rc==SQLITE_OK && sParse.nNest ){
  117918. rc = SQLITE_ERROR;
  117919. }
  117920. return rc;
  117921. }
  117922. /*
  117923. ** Parameters z and n contain a pointer to and length of a buffer containing
  117924. ** an fts3 query expression, respectively. This function attempts to parse the
  117925. ** query expression and create a tree of Fts3Expr structures representing the
  117926. ** parsed expression. If successful, *ppExpr is set to point to the head
  117927. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  117928. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  117929. ** error) is returned and *ppExpr is set to 0.
  117930. **
  117931. ** If parameter n is a negative number, then z is assumed to point to a
  117932. ** nul-terminated string and the length is determined using strlen().
  117933. **
  117934. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  117935. ** use to normalize query tokens while parsing the expression. The azCol[]
  117936. ** array, which is assumed to contain nCol entries, should contain the names
  117937. ** of each column in the target fts3 table, in order from left to right.
  117938. ** Column names must be nul-terminated strings.
  117939. **
  117940. ** The iDefaultCol parameter should be passed the index of the table column
  117941. ** that appears on the left-hand-side of the MATCH operator (the default
  117942. ** column to match against for tokens for which a column name is not explicitly
  117943. ** specified as part of the query string), or -1 if tokens may by default
  117944. ** match any table column.
  117945. */
  117946. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  117947. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  117948. int iLangid, /* Language id for tokenizer */
  117949. char **azCol, /* Array of column names for fts3 table */
  117950. int bFts4, /* True to allow FTS4-only syntax */
  117951. int nCol, /* Number of entries in azCol[] */
  117952. int iDefaultCol, /* Default column to query */
  117953. const char *z, int n, /* Text of MATCH query */
  117954. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  117955. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  117956. ){
  117957. static const int MAX_EXPR_DEPTH = 12;
  117958. int rc = fts3ExprParseUnbalanced(
  117959. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  117960. );
  117961. /* Rebalance the expression. And check that its depth does not exceed
  117962. ** MAX_EXPR_DEPTH. */
  117963. if( rc==SQLITE_OK && *ppExpr ){
  117964. rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
  117965. if( rc==SQLITE_OK ){
  117966. rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
  117967. }
  117968. }
  117969. if( rc!=SQLITE_OK ){
  117970. sqlite3Fts3ExprFree(*ppExpr);
  117971. *ppExpr = 0;
  117972. if( rc==SQLITE_TOOBIG ){
  117973. *pzErr = sqlite3_mprintf(
  117974. "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
  117975. );
  117976. rc = SQLITE_ERROR;
  117977. }else if( rc==SQLITE_ERROR ){
  117978. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  117979. }
  117980. }
  117981. return rc;
  117982. }
  117983. /*
  117984. ** Free a single node of an expression tree.
  117985. */
  117986. static void fts3FreeExprNode(Fts3Expr *p){
  117987. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  117988. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  117989. sqlite3_free(p->aMI);
  117990. sqlite3_free(p);
  117991. }
  117992. /*
  117993. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  117994. **
  117995. ** This function would be simpler if it recursively called itself. But
  117996. ** that would mean passing a sufficiently large expression to ExprParse()
  117997. ** could cause a stack overflow.
  117998. */
  117999. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  118000. Fts3Expr *p;
  118001. assert( pDel==0 || pDel->pParent==0 );
  118002. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  118003. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  118004. }
  118005. while( p ){
  118006. Fts3Expr *pParent = p->pParent;
  118007. fts3FreeExprNode(p);
  118008. if( pParent && p==pParent->pLeft && pParent->pRight ){
  118009. p = pParent->pRight;
  118010. while( p && (p->pLeft || p->pRight) ){
  118011. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  118012. p = (p->pLeft ? p->pLeft : p->pRight);
  118013. }
  118014. }else{
  118015. p = pParent;
  118016. }
  118017. }
  118018. }
  118019. /****************************************************************************
  118020. *****************************************************************************
  118021. ** Everything after this point is just test code.
  118022. */
  118023. #ifdef SQLITE_TEST
  118024. /* #include <stdio.h> */
  118025. /*
  118026. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  118027. */
  118028. static int queryTestTokenizer(
  118029. sqlite3 *db,
  118030. const char *zName,
  118031. const sqlite3_tokenizer_module **pp
  118032. ){
  118033. int rc;
  118034. sqlite3_stmt *pStmt;
  118035. const char zSql[] = "SELECT fts3_tokenizer(?)";
  118036. *pp = 0;
  118037. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  118038. if( rc!=SQLITE_OK ){
  118039. return rc;
  118040. }
  118041. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  118042. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  118043. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  118044. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  118045. }
  118046. }
  118047. return sqlite3_finalize(pStmt);
  118048. }
  118049. /*
  118050. ** Return a pointer to a buffer containing a text representation of the
  118051. ** expression passed as the first argument. The buffer is obtained from
  118052. ** sqlite3_malloc(). It is the responsibility of the caller to use
  118053. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  118054. ** NULL is returned.
  118055. **
  118056. ** If the second argument is not NULL, then its contents are prepended to
  118057. ** the returned expression text and then freed using sqlite3_free().
  118058. */
  118059. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  118060. if( pExpr==0 ){
  118061. return sqlite3_mprintf("");
  118062. }
  118063. switch( pExpr->eType ){
  118064. case FTSQUERY_PHRASE: {
  118065. Fts3Phrase *pPhrase = pExpr->pPhrase;
  118066. int i;
  118067. zBuf = sqlite3_mprintf(
  118068. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  118069. for(i=0; zBuf && i<pPhrase->nToken; i++){
  118070. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  118071. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  118072. (pPhrase->aToken[i].isPrefix?"+":"")
  118073. );
  118074. }
  118075. return zBuf;
  118076. }
  118077. case FTSQUERY_NEAR:
  118078. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  118079. break;
  118080. case FTSQUERY_NOT:
  118081. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  118082. break;
  118083. case FTSQUERY_AND:
  118084. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  118085. break;
  118086. case FTSQUERY_OR:
  118087. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  118088. break;
  118089. }
  118090. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  118091. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  118092. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  118093. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  118094. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  118095. return zBuf;
  118096. }
  118097. /*
  118098. ** This is the implementation of a scalar SQL function used to test the
  118099. ** expression parser. It should be called as follows:
  118100. **
  118101. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  118102. **
  118103. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  118104. ** to parse the query expression (see README.tokenizers). The second argument
  118105. ** is the query expression to parse. Each subsequent argument is the name
  118106. ** of a column of the fts3 table that the query expression may refer to.
  118107. ** For example:
  118108. **
  118109. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  118110. */
  118111. static void fts3ExprTest(
  118112. sqlite3_context *context,
  118113. int argc,
  118114. sqlite3_value **argv
  118115. ){
  118116. sqlite3_tokenizer_module const *pModule = 0;
  118117. sqlite3_tokenizer *pTokenizer = 0;
  118118. int rc;
  118119. char **azCol = 0;
  118120. const char *zExpr;
  118121. int nExpr;
  118122. int nCol;
  118123. int ii;
  118124. Fts3Expr *pExpr;
  118125. char *zBuf = 0;
  118126. sqlite3 *db = sqlite3_context_db_handle(context);
  118127. if( argc<3 ){
  118128. sqlite3_result_error(context,
  118129. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  118130. );
  118131. return;
  118132. }
  118133. rc = queryTestTokenizer(db,
  118134. (const char *)sqlite3_value_text(argv[0]), &pModule);
  118135. if( rc==SQLITE_NOMEM ){
  118136. sqlite3_result_error_nomem(context);
  118137. goto exprtest_out;
  118138. }else if( !pModule ){
  118139. sqlite3_result_error(context, "No such tokenizer module", -1);
  118140. goto exprtest_out;
  118141. }
  118142. rc = pModule->xCreate(0, 0, &pTokenizer);
  118143. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  118144. if( rc==SQLITE_NOMEM ){
  118145. sqlite3_result_error_nomem(context);
  118146. goto exprtest_out;
  118147. }
  118148. pTokenizer->pModule = pModule;
  118149. zExpr = (const char *)sqlite3_value_text(argv[1]);
  118150. nExpr = sqlite3_value_bytes(argv[1]);
  118151. nCol = argc-2;
  118152. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  118153. if( !azCol ){
  118154. sqlite3_result_error_nomem(context);
  118155. goto exprtest_out;
  118156. }
  118157. for(ii=0; ii<nCol; ii++){
  118158. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  118159. }
  118160. if( sqlite3_user_data(context) ){
  118161. char *zDummy = 0;
  118162. rc = sqlite3Fts3ExprParse(
  118163. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  118164. );
  118165. assert( rc==SQLITE_OK || pExpr==0 );
  118166. sqlite3_free(zDummy);
  118167. }else{
  118168. rc = fts3ExprParseUnbalanced(
  118169. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  118170. );
  118171. }
  118172. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  118173. sqlite3Fts3ExprFree(pExpr);
  118174. sqlite3_result_error(context, "Error parsing expression", -1);
  118175. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  118176. sqlite3_result_error_nomem(context);
  118177. }else{
  118178. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  118179. sqlite3_free(zBuf);
  118180. }
  118181. sqlite3Fts3ExprFree(pExpr);
  118182. exprtest_out:
  118183. if( pModule && pTokenizer ){
  118184. rc = pModule->xDestroy(pTokenizer);
  118185. }
  118186. sqlite3_free(azCol);
  118187. }
  118188. /*
  118189. ** Register the query expression parser test function fts3_exprtest()
  118190. ** with database connection db.
  118191. */
  118192. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  118193. int rc = sqlite3_create_function(
  118194. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  118195. );
  118196. if( rc==SQLITE_OK ){
  118197. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  118198. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  118199. );
  118200. }
  118201. return rc;
  118202. }
  118203. #endif
  118204. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  118205. /************** End of fts3_expr.c *******************************************/
  118206. /************** Begin file fts3_hash.c ***************************************/
  118207. /*
  118208. ** 2001 September 22
  118209. **
  118210. ** The author disclaims copyright to this source code. In place of
  118211. ** a legal notice, here is a blessing:
  118212. **
  118213. ** May you do good and not evil.
  118214. ** May you find forgiveness for yourself and forgive others.
  118215. ** May you share freely, never taking more than you give.
  118216. **
  118217. *************************************************************************
  118218. ** This is the implementation of generic hash-tables used in SQLite.
  118219. ** We've modified it slightly to serve as a standalone hash table
  118220. ** implementation for the full-text indexing module.
  118221. */
  118222. /*
  118223. ** The code in this file is only compiled if:
  118224. **
  118225. ** * The FTS3 module is being built as an extension
  118226. ** (in which case SQLITE_CORE is not defined), or
  118227. **
  118228. ** * The FTS3 module is being built into the core of
  118229. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  118230. */
  118231. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  118232. /* #include <assert.h> */
  118233. /* #include <stdlib.h> */
  118234. /* #include <string.h> */
  118235. /*
  118236. ** Malloc and Free functions
  118237. */
  118238. static void *fts3HashMalloc(int n){
  118239. void *p = sqlite3_malloc(n);
  118240. if( p ){
  118241. memset(p, 0, n);
  118242. }
  118243. return p;
  118244. }
  118245. static void fts3HashFree(void *p){
  118246. sqlite3_free(p);
  118247. }
  118248. /* Turn bulk memory into a hash table object by initializing the
  118249. ** fields of the Hash structure.
  118250. **
  118251. ** "pNew" is a pointer to the hash table that is to be initialized.
  118252. ** keyClass is one of the constants
  118253. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  118254. ** determines what kind of key the hash table will use. "copyKey" is
  118255. ** true if the hash table should make its own private copy of keys and
  118256. ** false if it should just use the supplied pointer.
  118257. */
  118258. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  118259. assert( pNew!=0 );
  118260. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  118261. pNew->keyClass = keyClass;
  118262. pNew->copyKey = copyKey;
  118263. pNew->first = 0;
  118264. pNew->count = 0;
  118265. pNew->htsize = 0;
  118266. pNew->ht = 0;
  118267. }
  118268. /* Remove all entries from a hash table. Reclaim all memory.
  118269. ** Call this routine to delete a hash table or to reset a hash table
  118270. ** to the empty state.
  118271. */
  118272. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  118273. Fts3HashElem *elem; /* For looping over all elements of the table */
  118274. assert( pH!=0 );
  118275. elem = pH->first;
  118276. pH->first = 0;
  118277. fts3HashFree(pH->ht);
  118278. pH->ht = 0;
  118279. pH->htsize = 0;
  118280. while( elem ){
  118281. Fts3HashElem *next_elem = elem->next;
  118282. if( pH->copyKey && elem->pKey ){
  118283. fts3HashFree(elem->pKey);
  118284. }
  118285. fts3HashFree(elem);
  118286. elem = next_elem;
  118287. }
  118288. pH->count = 0;
  118289. }
  118290. /*
  118291. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  118292. */
  118293. static int fts3StrHash(const void *pKey, int nKey){
  118294. const char *z = (const char *)pKey;
  118295. int h = 0;
  118296. if( nKey<=0 ) nKey = (int) strlen(z);
  118297. while( nKey > 0 ){
  118298. h = (h<<3) ^ h ^ *z++;
  118299. nKey--;
  118300. }
  118301. return h & 0x7fffffff;
  118302. }
  118303. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  118304. if( n1!=n2 ) return 1;
  118305. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  118306. }
  118307. /*
  118308. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  118309. */
  118310. static int fts3BinHash(const void *pKey, int nKey){
  118311. int h = 0;
  118312. const char *z = (const char *)pKey;
  118313. while( nKey-- > 0 ){
  118314. h = (h<<3) ^ h ^ *(z++);
  118315. }
  118316. return h & 0x7fffffff;
  118317. }
  118318. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  118319. if( n1!=n2 ) return 1;
  118320. return memcmp(pKey1,pKey2,n1);
  118321. }
  118322. /*
  118323. ** Return a pointer to the appropriate hash function given the key class.
  118324. **
  118325. ** The C syntax in this function definition may be unfamilar to some
  118326. ** programmers, so we provide the following additional explanation:
  118327. **
  118328. ** The name of the function is "ftsHashFunction". The function takes a
  118329. ** single parameter "keyClass". The return value of ftsHashFunction()
  118330. ** is a pointer to another function. Specifically, the return value
  118331. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  118332. ** with types "const void*" and "int" and returns an "int".
  118333. */
  118334. static int (*ftsHashFunction(int keyClass))(const void*,int){
  118335. if( keyClass==FTS3_HASH_STRING ){
  118336. return &fts3StrHash;
  118337. }else{
  118338. assert( keyClass==FTS3_HASH_BINARY );
  118339. return &fts3BinHash;
  118340. }
  118341. }
  118342. /*
  118343. ** Return a pointer to the appropriate hash function given the key class.
  118344. **
  118345. ** For help in interpreted the obscure C code in the function definition,
  118346. ** see the header comment on the previous function.
  118347. */
  118348. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  118349. if( keyClass==FTS3_HASH_STRING ){
  118350. return &fts3StrCompare;
  118351. }else{
  118352. assert( keyClass==FTS3_HASH_BINARY );
  118353. return &fts3BinCompare;
  118354. }
  118355. }
  118356. /* Link an element into the hash table
  118357. */
  118358. static void fts3HashInsertElement(
  118359. Fts3Hash *pH, /* The complete hash table */
  118360. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  118361. Fts3HashElem *pNew /* The element to be inserted */
  118362. ){
  118363. Fts3HashElem *pHead; /* First element already in pEntry */
  118364. pHead = pEntry->chain;
  118365. if( pHead ){
  118366. pNew->next = pHead;
  118367. pNew->prev = pHead->prev;
  118368. if( pHead->prev ){ pHead->prev->next = pNew; }
  118369. else { pH->first = pNew; }
  118370. pHead->prev = pNew;
  118371. }else{
  118372. pNew->next = pH->first;
  118373. if( pH->first ){ pH->first->prev = pNew; }
  118374. pNew->prev = 0;
  118375. pH->first = pNew;
  118376. }
  118377. pEntry->count++;
  118378. pEntry->chain = pNew;
  118379. }
  118380. /* Resize the hash table so that it cantains "new_size" buckets.
  118381. ** "new_size" must be a power of 2. The hash table might fail
  118382. ** to resize if sqliteMalloc() fails.
  118383. **
  118384. ** Return non-zero if a memory allocation error occurs.
  118385. */
  118386. static int fts3Rehash(Fts3Hash *pH, int new_size){
  118387. struct _fts3ht *new_ht; /* The new hash table */
  118388. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  118389. int (*xHash)(const void*,int); /* The hash function */
  118390. assert( (new_size & (new_size-1))==0 );
  118391. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  118392. if( new_ht==0 ) return 1;
  118393. fts3HashFree(pH->ht);
  118394. pH->ht = new_ht;
  118395. pH->htsize = new_size;
  118396. xHash = ftsHashFunction(pH->keyClass);
  118397. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  118398. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  118399. next_elem = elem->next;
  118400. fts3HashInsertElement(pH, &new_ht[h], elem);
  118401. }
  118402. return 0;
  118403. }
  118404. /* This function (for internal use only) locates an element in an
  118405. ** hash table that matches the given key. The hash for this key has
  118406. ** already been computed and is passed as the 4th parameter.
  118407. */
  118408. static Fts3HashElem *fts3FindElementByHash(
  118409. const Fts3Hash *pH, /* The pH to be searched */
  118410. const void *pKey, /* The key we are searching for */
  118411. int nKey,
  118412. int h /* The hash for this key. */
  118413. ){
  118414. Fts3HashElem *elem; /* Used to loop thru the element list */
  118415. int count; /* Number of elements left to test */
  118416. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  118417. if( pH->ht ){
  118418. struct _fts3ht *pEntry = &pH->ht[h];
  118419. elem = pEntry->chain;
  118420. count = pEntry->count;
  118421. xCompare = ftsCompareFunction(pH->keyClass);
  118422. while( count-- && elem ){
  118423. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  118424. return elem;
  118425. }
  118426. elem = elem->next;
  118427. }
  118428. }
  118429. return 0;
  118430. }
  118431. /* Remove a single entry from the hash table given a pointer to that
  118432. ** element and a hash on the element's key.
  118433. */
  118434. static void fts3RemoveElementByHash(
  118435. Fts3Hash *pH, /* The pH containing "elem" */
  118436. Fts3HashElem* elem, /* The element to be removed from the pH */
  118437. int h /* Hash value for the element */
  118438. ){
  118439. struct _fts3ht *pEntry;
  118440. if( elem->prev ){
  118441. elem->prev->next = elem->next;
  118442. }else{
  118443. pH->first = elem->next;
  118444. }
  118445. if( elem->next ){
  118446. elem->next->prev = elem->prev;
  118447. }
  118448. pEntry = &pH->ht[h];
  118449. if( pEntry->chain==elem ){
  118450. pEntry->chain = elem->next;
  118451. }
  118452. pEntry->count--;
  118453. if( pEntry->count<=0 ){
  118454. pEntry->chain = 0;
  118455. }
  118456. if( pH->copyKey && elem->pKey ){
  118457. fts3HashFree(elem->pKey);
  118458. }
  118459. fts3HashFree( elem );
  118460. pH->count--;
  118461. if( pH->count<=0 ){
  118462. assert( pH->first==0 );
  118463. assert( pH->count==0 );
  118464. fts3HashClear(pH);
  118465. }
  118466. }
  118467. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  118468. const Fts3Hash *pH,
  118469. const void *pKey,
  118470. int nKey
  118471. ){
  118472. int h; /* A hash on key */
  118473. int (*xHash)(const void*,int); /* The hash function */
  118474. if( pH==0 || pH->ht==0 ) return 0;
  118475. xHash = ftsHashFunction(pH->keyClass);
  118476. assert( xHash!=0 );
  118477. h = (*xHash)(pKey,nKey);
  118478. assert( (pH->htsize & (pH->htsize-1))==0 );
  118479. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  118480. }
  118481. /*
  118482. ** Attempt to locate an element of the hash table pH with a key
  118483. ** that matches pKey,nKey. Return the data for this element if it is
  118484. ** found, or NULL if there is no match.
  118485. */
  118486. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  118487. Fts3HashElem *pElem; /* The element that matches key (if any) */
  118488. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  118489. return pElem ? pElem->data : 0;
  118490. }
  118491. /* Insert an element into the hash table pH. The key is pKey,nKey
  118492. ** and the data is "data".
  118493. **
  118494. ** If no element exists with a matching key, then a new
  118495. ** element is created. A copy of the key is made if the copyKey
  118496. ** flag is set. NULL is returned.
  118497. **
  118498. ** If another element already exists with the same key, then the
  118499. ** new data replaces the old data and the old data is returned.
  118500. ** The key is not copied in this instance. If a malloc fails, then
  118501. ** the new data is returned and the hash table is unchanged.
  118502. **
  118503. ** If the "data" parameter to this function is NULL, then the
  118504. ** element corresponding to "key" is removed from the hash table.
  118505. */
  118506. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  118507. Fts3Hash *pH, /* The hash table to insert into */
  118508. const void *pKey, /* The key */
  118509. int nKey, /* Number of bytes in the key */
  118510. void *data /* The data */
  118511. ){
  118512. int hraw; /* Raw hash value of the key */
  118513. int h; /* the hash of the key modulo hash table size */
  118514. Fts3HashElem *elem; /* Used to loop thru the element list */
  118515. Fts3HashElem *new_elem; /* New element added to the pH */
  118516. int (*xHash)(const void*,int); /* The hash function */
  118517. assert( pH!=0 );
  118518. xHash = ftsHashFunction(pH->keyClass);
  118519. assert( xHash!=0 );
  118520. hraw = (*xHash)(pKey, nKey);
  118521. assert( (pH->htsize & (pH->htsize-1))==0 );
  118522. h = hraw & (pH->htsize-1);
  118523. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  118524. if( elem ){
  118525. void *old_data = elem->data;
  118526. if( data==0 ){
  118527. fts3RemoveElementByHash(pH,elem,h);
  118528. }else{
  118529. elem->data = data;
  118530. }
  118531. return old_data;
  118532. }
  118533. if( data==0 ) return 0;
  118534. if( (pH->htsize==0 && fts3Rehash(pH,8))
  118535. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  118536. ){
  118537. pH->count = 0;
  118538. return data;
  118539. }
  118540. assert( pH->htsize>0 );
  118541. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  118542. if( new_elem==0 ) return data;
  118543. if( pH->copyKey && pKey!=0 ){
  118544. new_elem->pKey = fts3HashMalloc( nKey );
  118545. if( new_elem->pKey==0 ){
  118546. fts3HashFree(new_elem);
  118547. return data;
  118548. }
  118549. memcpy((void*)new_elem->pKey, pKey, nKey);
  118550. }else{
  118551. new_elem->pKey = (void*)pKey;
  118552. }
  118553. new_elem->nKey = nKey;
  118554. pH->count++;
  118555. assert( pH->htsize>0 );
  118556. assert( (pH->htsize & (pH->htsize-1))==0 );
  118557. h = hraw & (pH->htsize-1);
  118558. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  118559. new_elem->data = data;
  118560. return 0;
  118561. }
  118562. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  118563. /************** End of fts3_hash.c *******************************************/
  118564. /************** Begin file fts3_porter.c *************************************/
  118565. /*
  118566. ** 2006 September 30
  118567. **
  118568. ** The author disclaims copyright to this source code. In place of
  118569. ** a legal notice, here is a blessing:
  118570. **
  118571. ** May you do good and not evil.
  118572. ** May you find forgiveness for yourself and forgive others.
  118573. ** May you share freely, never taking more than you give.
  118574. **
  118575. *************************************************************************
  118576. ** Implementation of the full-text-search tokenizer that implements
  118577. ** a Porter stemmer.
  118578. */
  118579. /*
  118580. ** The code in this file is only compiled if:
  118581. **
  118582. ** * The FTS3 module is being built as an extension
  118583. ** (in which case SQLITE_CORE is not defined), or
  118584. **
  118585. ** * The FTS3 module is being built into the core of
  118586. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  118587. */
  118588. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  118589. /* #include <assert.h> */
  118590. /* #include <stdlib.h> */
  118591. /* #include <stdio.h> */
  118592. /* #include <string.h> */
  118593. /*
  118594. ** Class derived from sqlite3_tokenizer
  118595. */
  118596. typedef struct porter_tokenizer {
  118597. sqlite3_tokenizer base; /* Base class */
  118598. } porter_tokenizer;
  118599. /*
  118600. ** Class derived from sqlite3_tokenizer_cursor
  118601. */
  118602. typedef struct porter_tokenizer_cursor {
  118603. sqlite3_tokenizer_cursor base;
  118604. const char *zInput; /* input we are tokenizing */
  118605. int nInput; /* size of the input */
  118606. int iOffset; /* current position in zInput */
  118607. int iToken; /* index of next token to be returned */
  118608. char *zToken; /* storage for current token */
  118609. int nAllocated; /* space allocated to zToken buffer */
  118610. } porter_tokenizer_cursor;
  118611. /*
  118612. ** Create a new tokenizer instance.
  118613. */
  118614. static int porterCreate(
  118615. int argc, const char * const *argv,
  118616. sqlite3_tokenizer **ppTokenizer
  118617. ){
  118618. porter_tokenizer *t;
  118619. UNUSED_PARAMETER(argc);
  118620. UNUSED_PARAMETER(argv);
  118621. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  118622. if( t==NULL ) return SQLITE_NOMEM;
  118623. memset(t, 0, sizeof(*t));
  118624. *ppTokenizer = &t->base;
  118625. return SQLITE_OK;
  118626. }
  118627. /*
  118628. ** Destroy a tokenizer
  118629. */
  118630. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  118631. sqlite3_free(pTokenizer);
  118632. return SQLITE_OK;
  118633. }
  118634. /*
  118635. ** Prepare to begin tokenizing a particular string. The input
  118636. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  118637. ** used to incrementally tokenize this string is returned in
  118638. ** *ppCursor.
  118639. */
  118640. static int porterOpen(
  118641. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  118642. const char *zInput, int nInput, /* String to be tokenized */
  118643. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  118644. ){
  118645. porter_tokenizer_cursor *c;
  118646. UNUSED_PARAMETER(pTokenizer);
  118647. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  118648. if( c==NULL ) return SQLITE_NOMEM;
  118649. c->zInput = zInput;
  118650. if( zInput==0 ){
  118651. c->nInput = 0;
  118652. }else if( nInput<0 ){
  118653. c->nInput = (int)strlen(zInput);
  118654. }else{
  118655. c->nInput = nInput;
  118656. }
  118657. c->iOffset = 0; /* start tokenizing at the beginning */
  118658. c->iToken = 0;
  118659. c->zToken = NULL; /* no space allocated, yet. */
  118660. c->nAllocated = 0;
  118661. *ppCursor = &c->base;
  118662. return SQLITE_OK;
  118663. }
  118664. /*
  118665. ** Close a tokenization cursor previously opened by a call to
  118666. ** porterOpen() above.
  118667. */
  118668. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  118669. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  118670. sqlite3_free(c->zToken);
  118671. sqlite3_free(c);
  118672. return SQLITE_OK;
  118673. }
  118674. /*
  118675. ** Vowel or consonant
  118676. */
  118677. static const char cType[] = {
  118678. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  118679. 1, 1, 1, 2, 1
  118680. };
  118681. /*
  118682. ** isConsonant() and isVowel() determine if their first character in
  118683. ** the string they point to is a consonant or a vowel, according
  118684. ** to Porter ruls.
  118685. **
  118686. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  118687. ** 'Y' is a consonant unless it follows another consonant,
  118688. ** in which case it is a vowel.
  118689. **
  118690. ** In these routine, the letters are in reverse order. So the 'y' rule
  118691. ** is that 'y' is a consonant unless it is followed by another
  118692. ** consonent.
  118693. */
  118694. static int isVowel(const char*);
  118695. static int isConsonant(const char *z){
  118696. int j;
  118697. char x = *z;
  118698. if( x==0 ) return 0;
  118699. assert( x>='a' && x<='z' );
  118700. j = cType[x-'a'];
  118701. if( j<2 ) return j;
  118702. return z[1]==0 || isVowel(z + 1);
  118703. }
  118704. static int isVowel(const char *z){
  118705. int j;
  118706. char x = *z;
  118707. if( x==0 ) return 0;
  118708. assert( x>='a' && x<='z' );
  118709. j = cType[x-'a'];
  118710. if( j<2 ) return 1-j;
  118711. return isConsonant(z + 1);
  118712. }
  118713. /*
  118714. ** Let any sequence of one or more vowels be represented by V and let
  118715. ** C be sequence of one or more consonants. Then every word can be
  118716. ** represented as:
  118717. **
  118718. ** [C] (VC){m} [V]
  118719. **
  118720. ** In prose: A word is an optional consonant followed by zero or
  118721. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  118722. ** number of vowel consonant pairs. This routine computes the value
  118723. ** of m for the first i bytes of a word.
  118724. **
  118725. ** Return true if the m-value for z is 1 or more. In other words,
  118726. ** return true if z contains at least one vowel that is followed
  118727. ** by a consonant.
  118728. **
  118729. ** In this routine z[] is in reverse order. So we are really looking
  118730. ** for an instance of of a consonant followed by a vowel.
  118731. */
  118732. static int m_gt_0(const char *z){
  118733. while( isVowel(z) ){ z++; }
  118734. if( *z==0 ) return 0;
  118735. while( isConsonant(z) ){ z++; }
  118736. return *z!=0;
  118737. }
  118738. /* Like mgt0 above except we are looking for a value of m which is
  118739. ** exactly 1
  118740. */
  118741. static int m_eq_1(const char *z){
  118742. while( isVowel(z) ){ z++; }
  118743. if( *z==0 ) return 0;
  118744. while( isConsonant(z) ){ z++; }
  118745. if( *z==0 ) return 0;
  118746. while( isVowel(z) ){ z++; }
  118747. if( *z==0 ) return 1;
  118748. while( isConsonant(z) ){ z++; }
  118749. return *z==0;
  118750. }
  118751. /* Like mgt0 above except we are looking for a value of m>1 instead
  118752. ** or m>0
  118753. */
  118754. static int m_gt_1(const char *z){
  118755. while( isVowel(z) ){ z++; }
  118756. if( *z==0 ) return 0;
  118757. while( isConsonant(z) ){ z++; }
  118758. if( *z==0 ) return 0;
  118759. while( isVowel(z) ){ z++; }
  118760. if( *z==0 ) return 0;
  118761. while( isConsonant(z) ){ z++; }
  118762. return *z!=0;
  118763. }
  118764. /*
  118765. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  118766. */
  118767. static int hasVowel(const char *z){
  118768. while( isConsonant(z) ){ z++; }
  118769. return *z!=0;
  118770. }
  118771. /*
  118772. ** Return TRUE if the word ends in a double consonant.
  118773. **
  118774. ** The text is reversed here. So we are really looking at
  118775. ** the first two characters of z[].
  118776. */
  118777. static int doubleConsonant(const char *z){
  118778. return isConsonant(z) && z[0]==z[1];
  118779. }
  118780. /*
  118781. ** Return TRUE if the word ends with three letters which
  118782. ** are consonant-vowel-consonent and where the final consonant
  118783. ** is not 'w', 'x', or 'y'.
  118784. **
  118785. ** The word is reversed here. So we are really checking the
  118786. ** first three letters and the first one cannot be in [wxy].
  118787. */
  118788. static int star_oh(const char *z){
  118789. return
  118790. isConsonant(z) &&
  118791. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  118792. isVowel(z+1) &&
  118793. isConsonant(z+2);
  118794. }
  118795. /*
  118796. ** If the word ends with zFrom and xCond() is true for the stem
  118797. ** of the word that preceeds the zFrom ending, then change the
  118798. ** ending to zTo.
  118799. **
  118800. ** The input word *pz and zFrom are both in reverse order. zTo
  118801. ** is in normal order.
  118802. **
  118803. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  118804. ** match. Not that TRUE is returned even if xCond() fails and
  118805. ** no substitution occurs.
  118806. */
  118807. static int stem(
  118808. char **pz, /* The word being stemmed (Reversed) */
  118809. const char *zFrom, /* If the ending matches this... (Reversed) */
  118810. const char *zTo, /* ... change the ending to this (not reversed) */
  118811. int (*xCond)(const char*) /* Condition that must be true */
  118812. ){
  118813. char *z = *pz;
  118814. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  118815. if( *zFrom!=0 ) return 0;
  118816. if( xCond && !xCond(z) ) return 1;
  118817. while( *zTo ){
  118818. *(--z) = *(zTo++);
  118819. }
  118820. *pz = z;
  118821. return 1;
  118822. }
  118823. /*
  118824. ** This is the fallback stemmer used when the porter stemmer is
  118825. ** inappropriate. The input word is copied into the output with
  118826. ** US-ASCII case folding. If the input word is too long (more
  118827. ** than 20 bytes if it contains no digits or more than 6 bytes if
  118828. ** it contains digits) then word is truncated to 20 or 6 bytes
  118829. ** by taking 10 or 3 bytes from the beginning and end.
  118830. */
  118831. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  118832. int i, mx, j;
  118833. int hasDigit = 0;
  118834. for(i=0; i<nIn; i++){
  118835. char c = zIn[i];
  118836. if( c>='A' && c<='Z' ){
  118837. zOut[i] = c - 'A' + 'a';
  118838. }else{
  118839. if( c>='0' && c<='9' ) hasDigit = 1;
  118840. zOut[i] = c;
  118841. }
  118842. }
  118843. mx = hasDigit ? 3 : 10;
  118844. if( nIn>mx*2 ){
  118845. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  118846. zOut[j] = zOut[i];
  118847. }
  118848. i = j;
  118849. }
  118850. zOut[i] = 0;
  118851. *pnOut = i;
  118852. }
  118853. /*
  118854. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  118855. ** zOut is at least big enough to hold nIn bytes. Write the actual
  118856. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  118857. **
  118858. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  118859. ** are converted to lower case. Upper-case UTF characters are
  118860. ** unchanged.
  118861. **
  118862. ** Words that are longer than about 20 bytes are stemmed by retaining
  118863. ** a few bytes from the beginning and the end of the word. If the
  118864. ** word contains digits, 3 bytes are taken from the beginning and
  118865. ** 3 bytes from the end. For long words without digits, 10 bytes
  118866. ** are taken from each end. US-ASCII case folding still applies.
  118867. **
  118868. ** If the input word contains not digits but does characters not
  118869. ** in [a-zA-Z] then no stemming is attempted and this routine just
  118870. ** copies the input into the input into the output with US-ASCII
  118871. ** case folding.
  118872. **
  118873. ** Stemming never increases the length of the word. So there is
  118874. ** no chance of overflowing the zOut buffer.
  118875. */
  118876. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  118877. int i, j;
  118878. char zReverse[28];
  118879. char *z, *z2;
  118880. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  118881. /* The word is too big or too small for the porter stemmer.
  118882. ** Fallback to the copy stemmer */
  118883. copy_stemmer(zIn, nIn, zOut, pnOut);
  118884. return;
  118885. }
  118886. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  118887. char c = zIn[i];
  118888. if( c>='A' && c<='Z' ){
  118889. zReverse[j] = c + 'a' - 'A';
  118890. }else if( c>='a' && c<='z' ){
  118891. zReverse[j] = c;
  118892. }else{
  118893. /* The use of a character not in [a-zA-Z] means that we fallback
  118894. ** to the copy stemmer */
  118895. copy_stemmer(zIn, nIn, zOut, pnOut);
  118896. return;
  118897. }
  118898. }
  118899. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  118900. z = &zReverse[j+1];
  118901. /* Step 1a */
  118902. if( z[0]=='s' ){
  118903. if(
  118904. !stem(&z, "sess", "ss", 0) &&
  118905. !stem(&z, "sei", "i", 0) &&
  118906. !stem(&z, "ss", "ss", 0)
  118907. ){
  118908. z++;
  118909. }
  118910. }
  118911. /* Step 1b */
  118912. z2 = z;
  118913. if( stem(&z, "dee", "ee", m_gt_0) ){
  118914. /* Do nothing. The work was all in the test */
  118915. }else if(
  118916. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  118917. && z!=z2
  118918. ){
  118919. if( stem(&z, "ta", "ate", 0) ||
  118920. stem(&z, "lb", "ble", 0) ||
  118921. stem(&z, "zi", "ize", 0) ){
  118922. /* Do nothing. The work was all in the test */
  118923. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  118924. z++;
  118925. }else if( m_eq_1(z) && star_oh(z) ){
  118926. *(--z) = 'e';
  118927. }
  118928. }
  118929. /* Step 1c */
  118930. if( z[0]=='y' && hasVowel(z+1) ){
  118931. z[0] = 'i';
  118932. }
  118933. /* Step 2 */
  118934. switch( z[1] ){
  118935. case 'a':
  118936. stem(&z, "lanoita", "ate", m_gt_0) ||
  118937. stem(&z, "lanoit", "tion", m_gt_0);
  118938. break;
  118939. case 'c':
  118940. stem(&z, "icne", "ence", m_gt_0) ||
  118941. stem(&z, "icna", "ance", m_gt_0);
  118942. break;
  118943. case 'e':
  118944. stem(&z, "rezi", "ize", m_gt_0);
  118945. break;
  118946. case 'g':
  118947. stem(&z, "igol", "log", m_gt_0);
  118948. break;
  118949. case 'l':
  118950. stem(&z, "ilb", "ble", m_gt_0) ||
  118951. stem(&z, "illa", "al", m_gt_0) ||
  118952. stem(&z, "iltne", "ent", m_gt_0) ||
  118953. stem(&z, "ile", "e", m_gt_0) ||
  118954. stem(&z, "ilsuo", "ous", m_gt_0);
  118955. break;
  118956. case 'o':
  118957. stem(&z, "noitazi", "ize", m_gt_0) ||
  118958. stem(&z, "noita", "ate", m_gt_0) ||
  118959. stem(&z, "rota", "ate", m_gt_0);
  118960. break;
  118961. case 's':
  118962. stem(&z, "msila", "al", m_gt_0) ||
  118963. stem(&z, "ssenevi", "ive", m_gt_0) ||
  118964. stem(&z, "ssenluf", "ful", m_gt_0) ||
  118965. stem(&z, "ssensuo", "ous", m_gt_0);
  118966. break;
  118967. case 't':
  118968. stem(&z, "itila", "al", m_gt_0) ||
  118969. stem(&z, "itivi", "ive", m_gt_0) ||
  118970. stem(&z, "itilib", "ble", m_gt_0);
  118971. break;
  118972. }
  118973. /* Step 3 */
  118974. switch( z[0] ){
  118975. case 'e':
  118976. stem(&z, "etaci", "ic", m_gt_0) ||
  118977. stem(&z, "evita", "", m_gt_0) ||
  118978. stem(&z, "ezila", "al", m_gt_0);
  118979. break;
  118980. case 'i':
  118981. stem(&z, "itici", "ic", m_gt_0);
  118982. break;
  118983. case 'l':
  118984. stem(&z, "laci", "ic", m_gt_0) ||
  118985. stem(&z, "luf", "", m_gt_0);
  118986. break;
  118987. case 's':
  118988. stem(&z, "ssen", "", m_gt_0);
  118989. break;
  118990. }
  118991. /* Step 4 */
  118992. switch( z[1] ){
  118993. case 'a':
  118994. if( z[0]=='l' && m_gt_1(z+2) ){
  118995. z += 2;
  118996. }
  118997. break;
  118998. case 'c':
  118999. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  119000. z += 4;
  119001. }
  119002. break;
  119003. case 'e':
  119004. if( z[0]=='r' && m_gt_1(z+2) ){
  119005. z += 2;
  119006. }
  119007. break;
  119008. case 'i':
  119009. if( z[0]=='c' && m_gt_1(z+2) ){
  119010. z += 2;
  119011. }
  119012. break;
  119013. case 'l':
  119014. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  119015. z += 4;
  119016. }
  119017. break;
  119018. case 'n':
  119019. if( z[0]=='t' ){
  119020. if( z[2]=='a' ){
  119021. if( m_gt_1(z+3) ){
  119022. z += 3;
  119023. }
  119024. }else if( z[2]=='e' ){
  119025. stem(&z, "tneme", "", m_gt_1) ||
  119026. stem(&z, "tnem", "", m_gt_1) ||
  119027. stem(&z, "tne", "", m_gt_1);
  119028. }
  119029. }
  119030. break;
  119031. case 'o':
  119032. if( z[0]=='u' ){
  119033. if( m_gt_1(z+2) ){
  119034. z += 2;
  119035. }
  119036. }else if( z[3]=='s' || z[3]=='t' ){
  119037. stem(&z, "noi", "", m_gt_1);
  119038. }
  119039. break;
  119040. case 's':
  119041. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  119042. z += 3;
  119043. }
  119044. break;
  119045. case 't':
  119046. stem(&z, "eta", "", m_gt_1) ||
  119047. stem(&z, "iti", "", m_gt_1);
  119048. break;
  119049. case 'u':
  119050. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  119051. z += 3;
  119052. }
  119053. break;
  119054. case 'v':
  119055. case 'z':
  119056. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  119057. z += 3;
  119058. }
  119059. break;
  119060. }
  119061. /* Step 5a */
  119062. if( z[0]=='e' ){
  119063. if( m_gt_1(z+1) ){
  119064. z++;
  119065. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  119066. z++;
  119067. }
  119068. }
  119069. /* Step 5b */
  119070. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  119071. z++;
  119072. }
  119073. /* z[] is now the stemmed word in reverse order. Flip it back
  119074. ** around into forward order and return.
  119075. */
  119076. *pnOut = i = (int)strlen(z);
  119077. zOut[i] = 0;
  119078. while( *z ){
  119079. zOut[--i] = *(z++);
  119080. }
  119081. }
  119082. /*
  119083. ** Characters that can be part of a token. We assume any character
  119084. ** whose value is greater than 0x80 (any UTF character) can be
  119085. ** part of a token. In other words, delimiters all must have
  119086. ** values of 0x7f or lower.
  119087. */
  119088. static const char porterIdChar[] = {
  119089. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  119090. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  119091. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  119092. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  119093. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  119094. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  119095. };
  119096. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  119097. /*
  119098. ** Extract the next token from a tokenization cursor. The cursor must
  119099. ** have been opened by a prior call to porterOpen().
  119100. */
  119101. static int porterNext(
  119102. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  119103. const char **pzToken, /* OUT: *pzToken is the token text */
  119104. int *pnBytes, /* OUT: Number of bytes in token */
  119105. int *piStartOffset, /* OUT: Starting offset of token */
  119106. int *piEndOffset, /* OUT: Ending offset of token */
  119107. int *piPosition /* OUT: Position integer of token */
  119108. ){
  119109. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  119110. const char *z = c->zInput;
  119111. while( c->iOffset<c->nInput ){
  119112. int iStartOffset, ch;
  119113. /* Scan past delimiter characters */
  119114. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  119115. c->iOffset++;
  119116. }
  119117. /* Count non-delimiter characters. */
  119118. iStartOffset = c->iOffset;
  119119. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  119120. c->iOffset++;
  119121. }
  119122. if( c->iOffset>iStartOffset ){
  119123. int n = c->iOffset-iStartOffset;
  119124. if( n>c->nAllocated ){
  119125. char *pNew;
  119126. c->nAllocated = n+20;
  119127. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  119128. if( !pNew ) return SQLITE_NOMEM;
  119129. c->zToken = pNew;
  119130. }
  119131. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  119132. *pzToken = c->zToken;
  119133. *piStartOffset = iStartOffset;
  119134. *piEndOffset = c->iOffset;
  119135. *piPosition = c->iToken++;
  119136. return SQLITE_OK;
  119137. }
  119138. }
  119139. return SQLITE_DONE;
  119140. }
  119141. /*
  119142. ** The set of routines that implement the porter-stemmer tokenizer
  119143. */
  119144. static const sqlite3_tokenizer_module porterTokenizerModule = {
  119145. 0,
  119146. porterCreate,
  119147. porterDestroy,
  119148. porterOpen,
  119149. porterClose,
  119150. porterNext,
  119151. 0
  119152. };
  119153. /*
  119154. ** Allocate a new porter tokenizer. Return a pointer to the new
  119155. ** tokenizer in *ppModule
  119156. */
  119157. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  119158. sqlite3_tokenizer_module const**ppModule
  119159. ){
  119160. *ppModule = &porterTokenizerModule;
  119161. }
  119162. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  119163. /************** End of fts3_porter.c *****************************************/
  119164. /************** Begin file fts3_tokenizer.c **********************************/
  119165. /*
  119166. ** 2007 June 22
  119167. **
  119168. ** The author disclaims copyright to this source code. In place of
  119169. ** a legal notice, here is a blessing:
  119170. **
  119171. ** May you do good and not evil.
  119172. ** May you find forgiveness for yourself and forgive others.
  119173. ** May you share freely, never taking more than you give.
  119174. **
  119175. ******************************************************************************
  119176. **
  119177. ** This is part of an SQLite module implementing full-text search.
  119178. ** This particular file implements the generic tokenizer interface.
  119179. */
  119180. /*
  119181. ** The code in this file is only compiled if:
  119182. **
  119183. ** * The FTS3 module is being built as an extension
  119184. ** (in which case SQLITE_CORE is not defined), or
  119185. **
  119186. ** * The FTS3 module is being built into the core of
  119187. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  119188. */
  119189. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119190. /* #include <assert.h> */
  119191. /* #include <string.h> */
  119192. /*
  119193. ** Implementation of the SQL scalar function for accessing the underlying
  119194. ** hash table. This function may be called as follows:
  119195. **
  119196. ** SELECT <function-name>(<key-name>);
  119197. ** SELECT <function-name>(<key-name>, <pointer>);
  119198. **
  119199. ** where <function-name> is the name passed as the second argument
  119200. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  119201. **
  119202. ** If the <pointer> argument is specified, it must be a blob value
  119203. ** containing a pointer to be stored as the hash data corresponding
  119204. ** to the string <key-name>. If <pointer> is not specified, then
  119205. ** the string <key-name> must already exist in the has table. Otherwise,
  119206. ** an error is returned.
  119207. **
  119208. ** Whether or not the <pointer> argument is specified, the value returned
  119209. ** is a blob containing the pointer stored as the hash data corresponding
  119210. ** to string <key-name> (after the hash-table is updated, if applicable).
  119211. */
  119212. static void scalarFunc(
  119213. sqlite3_context *context,
  119214. int argc,
  119215. sqlite3_value **argv
  119216. ){
  119217. Fts3Hash *pHash;
  119218. void *pPtr = 0;
  119219. const unsigned char *zName;
  119220. int nName;
  119221. assert( argc==1 || argc==2 );
  119222. pHash = (Fts3Hash *)sqlite3_user_data(context);
  119223. zName = sqlite3_value_text(argv[0]);
  119224. nName = sqlite3_value_bytes(argv[0])+1;
  119225. if( argc==2 ){
  119226. void *pOld;
  119227. int n = sqlite3_value_bytes(argv[1]);
  119228. if( n!=sizeof(pPtr) ){
  119229. sqlite3_result_error(context, "argument type mismatch", -1);
  119230. return;
  119231. }
  119232. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  119233. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  119234. if( pOld==pPtr ){
  119235. sqlite3_result_error(context, "out of memory", -1);
  119236. return;
  119237. }
  119238. }else{
  119239. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  119240. if( !pPtr ){
  119241. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  119242. sqlite3_result_error(context, zErr, -1);
  119243. sqlite3_free(zErr);
  119244. return;
  119245. }
  119246. }
  119247. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  119248. }
  119249. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  119250. static const char isFtsIdChar[] = {
  119251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  119252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  119253. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  119254. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  119255. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  119256. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  119257. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  119258. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  119259. };
  119260. return (c&0x80 || isFtsIdChar[(int)(c)]);
  119261. }
  119262. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  119263. const char *z1;
  119264. const char *z2 = 0;
  119265. /* Find the start of the next token. */
  119266. z1 = zStr;
  119267. while( z2==0 ){
  119268. char c = *z1;
  119269. switch( c ){
  119270. case '\0': return 0; /* No more tokens here */
  119271. case '\'':
  119272. case '"':
  119273. case '`': {
  119274. z2 = z1;
  119275. while( *++z2 && (*z2!=c || *++z2==c) );
  119276. break;
  119277. }
  119278. case '[':
  119279. z2 = &z1[1];
  119280. while( *z2 && z2[0]!=']' ) z2++;
  119281. if( *z2 ) z2++;
  119282. break;
  119283. default:
  119284. if( sqlite3Fts3IsIdChar(*z1) ){
  119285. z2 = &z1[1];
  119286. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  119287. }else{
  119288. z1++;
  119289. }
  119290. }
  119291. }
  119292. *pn = (int)(z2-z1);
  119293. return z1;
  119294. }
  119295. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  119296. Fts3Hash *pHash, /* Tokenizer hash table */
  119297. const char *zArg, /* Tokenizer name */
  119298. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  119299. char **pzErr /* OUT: Set to malloced error message */
  119300. ){
  119301. int rc;
  119302. char *z = (char *)zArg;
  119303. int n = 0;
  119304. char *zCopy;
  119305. char *zEnd; /* Pointer to nul-term of zCopy */
  119306. sqlite3_tokenizer_module *m;
  119307. zCopy = sqlite3_mprintf("%s", zArg);
  119308. if( !zCopy ) return SQLITE_NOMEM;
  119309. zEnd = &zCopy[strlen(zCopy)];
  119310. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  119311. z[n] = '\0';
  119312. sqlite3Fts3Dequote(z);
  119313. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  119314. if( !m ){
  119315. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  119316. rc = SQLITE_ERROR;
  119317. }else{
  119318. char const **aArg = 0;
  119319. int iArg = 0;
  119320. z = &z[n+1];
  119321. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  119322. int nNew = sizeof(char *)*(iArg+1);
  119323. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  119324. if( !aNew ){
  119325. sqlite3_free(zCopy);
  119326. sqlite3_free((void *)aArg);
  119327. return SQLITE_NOMEM;
  119328. }
  119329. aArg = aNew;
  119330. aArg[iArg++] = z;
  119331. z[n] = '\0';
  119332. sqlite3Fts3Dequote(z);
  119333. z = &z[n+1];
  119334. }
  119335. rc = m->xCreate(iArg, aArg, ppTok);
  119336. assert( rc!=SQLITE_OK || *ppTok );
  119337. if( rc!=SQLITE_OK ){
  119338. *pzErr = sqlite3_mprintf("unknown tokenizer");
  119339. }else{
  119340. (*ppTok)->pModule = m;
  119341. }
  119342. sqlite3_free((void *)aArg);
  119343. }
  119344. sqlite3_free(zCopy);
  119345. return rc;
  119346. }
  119347. #ifdef SQLITE_TEST
  119348. /* #include <tcl.h> */
  119349. /* #include <string.h> */
  119350. /*
  119351. ** Implementation of a special SQL scalar function for testing tokenizers
  119352. ** designed to be used in concert with the Tcl testing framework. This
  119353. ** function must be called with two or more arguments:
  119354. **
  119355. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  119356. **
  119357. ** where <function-name> is the name passed as the second argument
  119358. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  119359. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  119360. **
  119361. ** The return value is a string that may be interpreted as a Tcl
  119362. ** list. For each token in the <input-string>, three elements are
  119363. ** added to the returned list. The first is the token position, the
  119364. ** second is the token text (folded, stemmed, etc.) and the third is the
  119365. ** substring of <input-string> associated with the token. For example,
  119366. ** using the built-in "simple" tokenizer:
  119367. **
  119368. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  119369. **
  119370. ** will return the string:
  119371. **
  119372. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  119373. **
  119374. */
  119375. static void testFunc(
  119376. sqlite3_context *context,
  119377. int argc,
  119378. sqlite3_value **argv
  119379. ){
  119380. Fts3Hash *pHash;
  119381. sqlite3_tokenizer_module *p;
  119382. sqlite3_tokenizer *pTokenizer = 0;
  119383. sqlite3_tokenizer_cursor *pCsr = 0;
  119384. const char *zErr = 0;
  119385. const char *zName;
  119386. int nName;
  119387. const char *zInput;
  119388. int nInput;
  119389. const char *azArg[64];
  119390. const char *zToken;
  119391. int nToken = 0;
  119392. int iStart = 0;
  119393. int iEnd = 0;
  119394. int iPos = 0;
  119395. int i;
  119396. Tcl_Obj *pRet;
  119397. if( argc<2 ){
  119398. sqlite3_result_error(context, "insufficient arguments", -1);
  119399. return;
  119400. }
  119401. nName = sqlite3_value_bytes(argv[0]);
  119402. zName = (const char *)sqlite3_value_text(argv[0]);
  119403. nInput = sqlite3_value_bytes(argv[argc-1]);
  119404. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  119405. pHash = (Fts3Hash *)sqlite3_user_data(context);
  119406. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  119407. if( !p ){
  119408. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  119409. sqlite3_result_error(context, zErr, -1);
  119410. sqlite3_free(zErr);
  119411. return;
  119412. }
  119413. pRet = Tcl_NewObj();
  119414. Tcl_IncrRefCount(pRet);
  119415. for(i=1; i<argc-1; i++){
  119416. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  119417. }
  119418. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  119419. zErr = "error in xCreate()";
  119420. goto finish;
  119421. }
  119422. pTokenizer->pModule = p;
  119423. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  119424. zErr = "error in xOpen()";
  119425. goto finish;
  119426. }
  119427. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  119428. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  119429. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  119430. zToken = &zInput[iStart];
  119431. nToken = iEnd-iStart;
  119432. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  119433. }
  119434. if( SQLITE_OK!=p->xClose(pCsr) ){
  119435. zErr = "error in xClose()";
  119436. goto finish;
  119437. }
  119438. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  119439. zErr = "error in xDestroy()";
  119440. goto finish;
  119441. }
  119442. finish:
  119443. if( zErr ){
  119444. sqlite3_result_error(context, zErr, -1);
  119445. }else{
  119446. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  119447. }
  119448. Tcl_DecrRefCount(pRet);
  119449. }
  119450. static
  119451. int registerTokenizer(
  119452. sqlite3 *db,
  119453. char *zName,
  119454. const sqlite3_tokenizer_module *p
  119455. ){
  119456. int rc;
  119457. sqlite3_stmt *pStmt;
  119458. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  119459. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  119460. if( rc!=SQLITE_OK ){
  119461. return rc;
  119462. }
  119463. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  119464. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  119465. sqlite3_step(pStmt);
  119466. return sqlite3_finalize(pStmt);
  119467. }
  119468. static
  119469. int queryTokenizer(
  119470. sqlite3 *db,
  119471. char *zName,
  119472. const sqlite3_tokenizer_module **pp
  119473. ){
  119474. int rc;
  119475. sqlite3_stmt *pStmt;
  119476. const char zSql[] = "SELECT fts3_tokenizer(?)";
  119477. *pp = 0;
  119478. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  119479. if( rc!=SQLITE_OK ){
  119480. return rc;
  119481. }
  119482. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  119483. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  119484. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  119485. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  119486. }
  119487. }
  119488. return sqlite3_finalize(pStmt);
  119489. }
  119490. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  119491. /*
  119492. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  119493. ** This function is used for testing only, it is not included in the
  119494. ** build unless SQLITE_TEST is defined.
  119495. **
  119496. ** The purpose of this is to test that the fts3_tokenizer() function
  119497. ** can be used as designed by the C-code in the queryTokenizer and
  119498. ** registerTokenizer() functions above. These two functions are repeated
  119499. ** in the README.tokenizer file as an example, so it is important to
  119500. ** test them.
  119501. **
  119502. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  119503. ** function with no arguments. An assert() will fail if a problem is
  119504. ** detected. i.e.:
  119505. **
  119506. ** SELECT fts3_tokenizer_internal_test();
  119507. **
  119508. */
  119509. static void intTestFunc(
  119510. sqlite3_context *context,
  119511. int argc,
  119512. sqlite3_value **argv
  119513. ){
  119514. int rc;
  119515. const sqlite3_tokenizer_module *p1;
  119516. const sqlite3_tokenizer_module *p2;
  119517. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  119518. UNUSED_PARAMETER(argc);
  119519. UNUSED_PARAMETER(argv);
  119520. /* Test the query function */
  119521. sqlite3Fts3SimpleTokenizerModule(&p1);
  119522. rc = queryTokenizer(db, "simple", &p2);
  119523. assert( rc==SQLITE_OK );
  119524. assert( p1==p2 );
  119525. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  119526. assert( rc==SQLITE_ERROR );
  119527. assert( p2==0 );
  119528. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  119529. /* Test the storage function */
  119530. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  119531. assert( rc==SQLITE_OK );
  119532. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  119533. assert( rc==SQLITE_OK );
  119534. assert( p2==p1 );
  119535. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  119536. }
  119537. #endif
  119538. /*
  119539. ** Set up SQL objects in database db used to access the contents of
  119540. ** the hash table pointed to by argument pHash. The hash table must
  119541. ** been initialized to use string keys, and to take a private copy
  119542. ** of the key when a value is inserted. i.e. by a call similar to:
  119543. **
  119544. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  119545. **
  119546. ** This function adds a scalar function (see header comment above
  119547. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  119548. ** defined at compilation time, a temporary virtual table (see header
  119549. ** comment above struct HashTableVtab) to the database schema. Both
  119550. ** provide read/write access to the contents of *pHash.
  119551. **
  119552. ** The third argument to this function, zName, is used as the name
  119553. ** of both the scalar and, if created, the virtual table.
  119554. */
  119555. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  119556. sqlite3 *db,
  119557. Fts3Hash *pHash,
  119558. const char *zName
  119559. ){
  119560. int rc = SQLITE_OK;
  119561. void *p = (void *)pHash;
  119562. const int any = SQLITE_ANY;
  119563. #ifdef SQLITE_TEST
  119564. char *zTest = 0;
  119565. char *zTest2 = 0;
  119566. void *pdb = (void *)db;
  119567. zTest = sqlite3_mprintf("%s_test", zName);
  119568. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  119569. if( !zTest || !zTest2 ){
  119570. rc = SQLITE_NOMEM;
  119571. }
  119572. #endif
  119573. if( SQLITE_OK==rc ){
  119574. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  119575. }
  119576. if( SQLITE_OK==rc ){
  119577. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  119578. }
  119579. #ifdef SQLITE_TEST
  119580. if( SQLITE_OK==rc ){
  119581. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  119582. }
  119583. if( SQLITE_OK==rc ){
  119584. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  119585. }
  119586. #endif
  119587. #ifdef SQLITE_TEST
  119588. sqlite3_free(zTest);
  119589. sqlite3_free(zTest2);
  119590. #endif
  119591. return rc;
  119592. }
  119593. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  119594. /************** End of fts3_tokenizer.c **************************************/
  119595. /************** Begin file fts3_tokenizer1.c *********************************/
  119596. /*
  119597. ** 2006 Oct 10
  119598. **
  119599. ** The author disclaims copyright to this source code. In place of
  119600. ** a legal notice, here is a blessing:
  119601. **
  119602. ** May you do good and not evil.
  119603. ** May you find forgiveness for yourself and forgive others.
  119604. ** May you share freely, never taking more than you give.
  119605. **
  119606. ******************************************************************************
  119607. **
  119608. ** Implementation of the "simple" full-text-search tokenizer.
  119609. */
  119610. /*
  119611. ** The code in this file is only compiled if:
  119612. **
  119613. ** * The FTS3 module is being built as an extension
  119614. ** (in which case SQLITE_CORE is not defined), or
  119615. **
  119616. ** * The FTS3 module is being built into the core of
  119617. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  119618. */
  119619. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119620. /* #include <assert.h> */
  119621. /* #include <stdlib.h> */
  119622. /* #include <stdio.h> */
  119623. /* #include <string.h> */
  119624. typedef struct simple_tokenizer {
  119625. sqlite3_tokenizer base;
  119626. char delim[128]; /* flag ASCII delimiters */
  119627. } simple_tokenizer;
  119628. typedef struct simple_tokenizer_cursor {
  119629. sqlite3_tokenizer_cursor base;
  119630. const char *pInput; /* input we are tokenizing */
  119631. int nBytes; /* size of the input */
  119632. int iOffset; /* current position in pInput */
  119633. int iToken; /* index of next token to be returned */
  119634. char *pToken; /* storage for current token */
  119635. int nTokenAllocated; /* space allocated to zToken buffer */
  119636. } simple_tokenizer_cursor;
  119637. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  119638. return c<0x80 && t->delim[c];
  119639. }
  119640. static int fts3_isalnum(int x){
  119641. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  119642. }
  119643. /*
  119644. ** Create a new tokenizer instance.
  119645. */
  119646. static int simpleCreate(
  119647. int argc, const char * const *argv,
  119648. sqlite3_tokenizer **ppTokenizer
  119649. ){
  119650. simple_tokenizer *t;
  119651. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  119652. if( t==NULL ) return SQLITE_NOMEM;
  119653. memset(t, 0, sizeof(*t));
  119654. /* TODO(shess) Delimiters need to remain the same from run to run,
  119655. ** else we need to reindex. One solution would be a meta-table to
  119656. ** track such information in the database, then we'd only want this
  119657. ** information on the initial create.
  119658. */
  119659. if( argc>1 ){
  119660. int i, n = (int)strlen(argv[1]);
  119661. for(i=0; i<n; i++){
  119662. unsigned char ch = argv[1][i];
  119663. /* We explicitly don't support UTF-8 delimiters for now. */
  119664. if( ch>=0x80 ){
  119665. sqlite3_free(t);
  119666. return SQLITE_ERROR;
  119667. }
  119668. t->delim[ch] = 1;
  119669. }
  119670. } else {
  119671. /* Mark non-alphanumeric ASCII characters as delimiters */
  119672. int i;
  119673. for(i=1; i<0x80; i++){
  119674. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  119675. }
  119676. }
  119677. *ppTokenizer = &t->base;
  119678. return SQLITE_OK;
  119679. }
  119680. /*
  119681. ** Destroy a tokenizer
  119682. */
  119683. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  119684. sqlite3_free(pTokenizer);
  119685. return SQLITE_OK;
  119686. }
  119687. /*
  119688. ** Prepare to begin tokenizing a particular string. The input
  119689. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  119690. ** used to incrementally tokenize this string is returned in
  119691. ** *ppCursor.
  119692. */
  119693. static int simpleOpen(
  119694. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  119695. const char *pInput, int nBytes, /* String to be tokenized */
  119696. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  119697. ){
  119698. simple_tokenizer_cursor *c;
  119699. UNUSED_PARAMETER(pTokenizer);
  119700. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  119701. if( c==NULL ) return SQLITE_NOMEM;
  119702. c->pInput = pInput;
  119703. if( pInput==0 ){
  119704. c->nBytes = 0;
  119705. }else if( nBytes<0 ){
  119706. c->nBytes = (int)strlen(pInput);
  119707. }else{
  119708. c->nBytes = nBytes;
  119709. }
  119710. c->iOffset = 0; /* start tokenizing at the beginning */
  119711. c->iToken = 0;
  119712. c->pToken = NULL; /* no space allocated, yet. */
  119713. c->nTokenAllocated = 0;
  119714. *ppCursor = &c->base;
  119715. return SQLITE_OK;
  119716. }
  119717. /*
  119718. ** Close a tokenization cursor previously opened by a call to
  119719. ** simpleOpen() above.
  119720. */
  119721. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  119722. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  119723. sqlite3_free(c->pToken);
  119724. sqlite3_free(c);
  119725. return SQLITE_OK;
  119726. }
  119727. /*
  119728. ** Extract the next token from a tokenization cursor. The cursor must
  119729. ** have been opened by a prior call to simpleOpen().
  119730. */
  119731. static int simpleNext(
  119732. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  119733. const char **ppToken, /* OUT: *ppToken is the token text */
  119734. int *pnBytes, /* OUT: Number of bytes in token */
  119735. int *piStartOffset, /* OUT: Starting offset of token */
  119736. int *piEndOffset, /* OUT: Ending offset of token */
  119737. int *piPosition /* OUT: Position integer of token */
  119738. ){
  119739. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  119740. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  119741. unsigned char *p = (unsigned char *)c->pInput;
  119742. while( c->iOffset<c->nBytes ){
  119743. int iStartOffset;
  119744. /* Scan past delimiter characters */
  119745. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  119746. c->iOffset++;
  119747. }
  119748. /* Count non-delimiter characters. */
  119749. iStartOffset = c->iOffset;
  119750. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  119751. c->iOffset++;
  119752. }
  119753. if( c->iOffset>iStartOffset ){
  119754. int i, n = c->iOffset-iStartOffset;
  119755. if( n>c->nTokenAllocated ){
  119756. char *pNew;
  119757. c->nTokenAllocated = n+20;
  119758. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  119759. if( !pNew ) return SQLITE_NOMEM;
  119760. c->pToken = pNew;
  119761. }
  119762. for(i=0; i<n; i++){
  119763. /* TODO(shess) This needs expansion to handle UTF-8
  119764. ** case-insensitivity.
  119765. */
  119766. unsigned char ch = p[iStartOffset+i];
  119767. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  119768. }
  119769. *ppToken = c->pToken;
  119770. *pnBytes = n;
  119771. *piStartOffset = iStartOffset;
  119772. *piEndOffset = c->iOffset;
  119773. *piPosition = c->iToken++;
  119774. return SQLITE_OK;
  119775. }
  119776. }
  119777. return SQLITE_DONE;
  119778. }
  119779. /*
  119780. ** The set of routines that implement the simple tokenizer
  119781. */
  119782. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  119783. 0,
  119784. simpleCreate,
  119785. simpleDestroy,
  119786. simpleOpen,
  119787. simpleClose,
  119788. simpleNext,
  119789. 0,
  119790. };
  119791. /*
  119792. ** Allocate a new simple tokenizer. Return a pointer to the new
  119793. ** tokenizer in *ppModule
  119794. */
  119795. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  119796. sqlite3_tokenizer_module const**ppModule
  119797. ){
  119798. *ppModule = &simpleTokenizerModule;
  119799. }
  119800. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  119801. /************** End of fts3_tokenizer1.c *************************************/
  119802. /************** Begin file fts3_tokenize_vtab.c ******************************/
  119803. /*
  119804. ** 2013 Apr 22
  119805. **
  119806. ** The author disclaims copyright to this source code. In place of
  119807. ** a legal notice, here is a blessing:
  119808. **
  119809. ** May you do good and not evil.
  119810. ** May you find forgiveness for yourself and forgive others.
  119811. ** May you share freely, never taking more than you give.
  119812. **
  119813. ******************************************************************************
  119814. **
  119815. ** This file contains code for the "fts3tokenize" virtual table module.
  119816. ** An fts3tokenize virtual table is created as follows:
  119817. **
  119818. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  119819. ** <tokenizer-name>, <arg-1>, ...
  119820. ** );
  119821. **
  119822. ** The table created has the following schema:
  119823. **
  119824. ** CREATE TABLE <tbl>(input, token, start, end, position)
  119825. **
  119826. ** When queried, the query must include a WHERE clause of type:
  119827. **
  119828. ** input = <string>
  119829. **
  119830. ** The virtual table module tokenizes this <string>, using the FTS3
  119831. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  119832. ** statement and returns one row for each token in the result. With
  119833. ** fields set as follows:
  119834. **
  119835. ** input: Always set to a copy of <string>
  119836. ** token: A token from the input.
  119837. ** start: Byte offset of the token within the input <string>.
  119838. ** end: Byte offset of the byte immediately following the end of the
  119839. ** token within the input string.
  119840. ** pos: Token offset of token within input.
  119841. **
  119842. */
  119843. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119844. /* #include <string.h> */
  119845. /* #include <assert.h> */
  119846. typedef struct Fts3tokTable Fts3tokTable;
  119847. typedef struct Fts3tokCursor Fts3tokCursor;
  119848. /*
  119849. ** Virtual table structure.
  119850. */
  119851. struct Fts3tokTable {
  119852. sqlite3_vtab base; /* Base class used by SQLite core */
  119853. const sqlite3_tokenizer_module *pMod;
  119854. sqlite3_tokenizer *pTok;
  119855. };
  119856. /*
  119857. ** Virtual table cursor structure.
  119858. */
  119859. struct Fts3tokCursor {
  119860. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  119861. char *zInput; /* Input string */
  119862. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  119863. int iRowid; /* Current 'rowid' value */
  119864. const char *zToken; /* Current 'token' value */
  119865. int nToken; /* Size of zToken in bytes */
  119866. int iStart; /* Current 'start' value */
  119867. int iEnd; /* Current 'end' value */
  119868. int iPos; /* Current 'pos' value */
  119869. };
  119870. /*
  119871. ** Query FTS for the tokenizer implementation named zName.
  119872. */
  119873. static int fts3tokQueryTokenizer(
  119874. Fts3Hash *pHash,
  119875. const char *zName,
  119876. const sqlite3_tokenizer_module **pp,
  119877. char **pzErr
  119878. ){
  119879. sqlite3_tokenizer_module *p;
  119880. int nName = (int)strlen(zName);
  119881. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  119882. if( !p ){
  119883. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  119884. return SQLITE_ERROR;
  119885. }
  119886. *pp = p;
  119887. return SQLITE_OK;
  119888. }
  119889. /*
  119890. ** The second argument, argv[], is an array of pointers to nul-terminated
  119891. ** strings. This function makes a copy of the array and strings into a
  119892. ** single block of memory. It then dequotes any of the strings that appear
  119893. ** to be quoted.
  119894. **
  119895. ** If successful, output parameter *pazDequote is set to point at the
  119896. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  119897. ** responsible for eventually calling sqlite3_free() to free the array
  119898. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  119899. ** The final value of *pazDequote is undefined in this case.
  119900. */
  119901. static int fts3tokDequoteArray(
  119902. int argc, /* Number of elements in argv[] */
  119903. const char * const *argv, /* Input array */
  119904. char ***pazDequote /* Output array */
  119905. ){
  119906. int rc = SQLITE_OK; /* Return code */
  119907. if( argc==0 ){
  119908. *pazDequote = 0;
  119909. }else{
  119910. int i;
  119911. int nByte = 0;
  119912. char **azDequote;
  119913. for(i=0; i<argc; i++){
  119914. nByte += (int)(strlen(argv[i]) + 1);
  119915. }
  119916. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  119917. if( azDequote==0 ){
  119918. rc = SQLITE_NOMEM;
  119919. }else{
  119920. char *pSpace = (char *)&azDequote[argc];
  119921. for(i=0; i<argc; i++){
  119922. int n = (int)strlen(argv[i]);
  119923. azDequote[i] = pSpace;
  119924. memcpy(pSpace, argv[i], n+1);
  119925. sqlite3Fts3Dequote(pSpace);
  119926. pSpace += (n+1);
  119927. }
  119928. }
  119929. }
  119930. return rc;
  119931. }
  119932. /*
  119933. ** Schema of the tokenizer table.
  119934. */
  119935. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  119936. /*
  119937. ** This function does all the work for both the xConnect and xCreate methods.
  119938. ** These tables have no persistent representation of their own, so xConnect
  119939. ** and xCreate are identical operations.
  119940. **
  119941. ** argv[0]: module name
  119942. ** argv[1]: database name
  119943. ** argv[2]: table name
  119944. ** argv[3]: first argument (tokenizer name)
  119945. */
  119946. static int fts3tokConnectMethod(
  119947. sqlite3 *db, /* Database connection */
  119948. void *pHash, /* Hash table of tokenizers */
  119949. int argc, /* Number of elements in argv array */
  119950. const char * const *argv, /* xCreate/xConnect argument array */
  119951. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  119952. char **pzErr /* OUT: sqlite3_malloc'd error message */
  119953. ){
  119954. Fts3tokTable *pTab;
  119955. const sqlite3_tokenizer_module *pMod = 0;
  119956. sqlite3_tokenizer *pTok = 0;
  119957. int rc;
  119958. char **azDequote = 0;
  119959. int nDequote;
  119960. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  119961. if( rc!=SQLITE_OK ) return rc;
  119962. nDequote = argc-3;
  119963. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  119964. if( rc==SQLITE_OK ){
  119965. const char *zModule;
  119966. if( nDequote<1 ){
  119967. zModule = "simple";
  119968. }else{
  119969. zModule = azDequote[0];
  119970. }
  119971. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  119972. }
  119973. assert( (rc==SQLITE_OK)==(pMod!=0) );
  119974. if( rc==SQLITE_OK ){
  119975. const char * const *azArg = (const char * const *)&azDequote[1];
  119976. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  119977. }
  119978. if( rc==SQLITE_OK ){
  119979. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  119980. if( pTab==0 ){
  119981. rc = SQLITE_NOMEM;
  119982. }
  119983. }
  119984. if( rc==SQLITE_OK ){
  119985. memset(pTab, 0, sizeof(Fts3tokTable));
  119986. pTab->pMod = pMod;
  119987. pTab->pTok = pTok;
  119988. *ppVtab = &pTab->base;
  119989. }else{
  119990. if( pTok ){
  119991. pMod->xDestroy(pTok);
  119992. }
  119993. }
  119994. sqlite3_free(azDequote);
  119995. return rc;
  119996. }
  119997. /*
  119998. ** This function does the work for both the xDisconnect and xDestroy methods.
  119999. ** These tables have no persistent representation of their own, so xDisconnect
  120000. ** and xDestroy are identical operations.
  120001. */
  120002. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  120003. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  120004. pTab->pMod->xDestroy(pTab->pTok);
  120005. sqlite3_free(pTab);
  120006. return SQLITE_OK;
  120007. }
  120008. /*
  120009. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  120010. */
  120011. static int fts3tokBestIndexMethod(
  120012. sqlite3_vtab *pVTab,
  120013. sqlite3_index_info *pInfo
  120014. ){
  120015. int i;
  120016. UNUSED_PARAMETER(pVTab);
  120017. for(i=0; i<pInfo->nConstraint; i++){
  120018. if( pInfo->aConstraint[i].usable
  120019. && pInfo->aConstraint[i].iColumn==0
  120020. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  120021. ){
  120022. pInfo->idxNum = 1;
  120023. pInfo->aConstraintUsage[i].argvIndex = 1;
  120024. pInfo->aConstraintUsage[i].omit = 1;
  120025. pInfo->estimatedCost = 1;
  120026. return SQLITE_OK;
  120027. }
  120028. }
  120029. pInfo->idxNum = 0;
  120030. assert( pInfo->estimatedCost>1000000.0 );
  120031. return SQLITE_OK;
  120032. }
  120033. /*
  120034. ** xOpen - Open a cursor.
  120035. */
  120036. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  120037. Fts3tokCursor *pCsr;
  120038. UNUSED_PARAMETER(pVTab);
  120039. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  120040. if( pCsr==0 ){
  120041. return SQLITE_NOMEM;
  120042. }
  120043. memset(pCsr, 0, sizeof(Fts3tokCursor));
  120044. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  120045. return SQLITE_OK;
  120046. }
  120047. /*
  120048. ** Reset the tokenizer cursor passed as the only argument. As if it had
  120049. ** just been returned by fts3tokOpenMethod().
  120050. */
  120051. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  120052. if( pCsr->pCsr ){
  120053. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  120054. pTab->pMod->xClose(pCsr->pCsr);
  120055. pCsr->pCsr = 0;
  120056. }
  120057. sqlite3_free(pCsr->zInput);
  120058. pCsr->zInput = 0;
  120059. pCsr->zToken = 0;
  120060. pCsr->nToken = 0;
  120061. pCsr->iStart = 0;
  120062. pCsr->iEnd = 0;
  120063. pCsr->iPos = 0;
  120064. pCsr->iRowid = 0;
  120065. }
  120066. /*
  120067. ** xClose - Close a cursor.
  120068. */
  120069. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  120070. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120071. fts3tokResetCursor(pCsr);
  120072. sqlite3_free(pCsr);
  120073. return SQLITE_OK;
  120074. }
  120075. /*
  120076. ** xNext - Advance the cursor to the next row, if any.
  120077. */
  120078. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  120079. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120080. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  120081. int rc; /* Return code */
  120082. pCsr->iRowid++;
  120083. rc = pTab->pMod->xNext(pCsr->pCsr,
  120084. &pCsr->zToken, &pCsr->nToken,
  120085. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  120086. );
  120087. if( rc!=SQLITE_OK ){
  120088. fts3tokResetCursor(pCsr);
  120089. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  120090. }
  120091. return rc;
  120092. }
  120093. /*
  120094. ** xFilter - Initialize a cursor to point at the start of its data.
  120095. */
  120096. static int fts3tokFilterMethod(
  120097. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  120098. int idxNum, /* Strategy index */
  120099. const char *idxStr, /* Unused */
  120100. int nVal, /* Number of elements in apVal */
  120101. sqlite3_value **apVal /* Arguments for the indexing scheme */
  120102. ){
  120103. int rc = SQLITE_ERROR;
  120104. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120105. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  120106. UNUSED_PARAMETER(idxStr);
  120107. UNUSED_PARAMETER(nVal);
  120108. fts3tokResetCursor(pCsr);
  120109. if( idxNum==1 ){
  120110. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  120111. int nByte = sqlite3_value_bytes(apVal[0]);
  120112. pCsr->zInput = sqlite3_malloc(nByte+1);
  120113. if( pCsr->zInput==0 ){
  120114. rc = SQLITE_NOMEM;
  120115. }else{
  120116. memcpy(pCsr->zInput, zByte, nByte);
  120117. pCsr->zInput[nByte] = 0;
  120118. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  120119. if( rc==SQLITE_OK ){
  120120. pCsr->pCsr->pTokenizer = pTab->pTok;
  120121. }
  120122. }
  120123. }
  120124. if( rc!=SQLITE_OK ) return rc;
  120125. return fts3tokNextMethod(pCursor);
  120126. }
  120127. /*
  120128. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  120129. */
  120130. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  120131. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120132. return (pCsr->zToken==0);
  120133. }
  120134. /*
  120135. ** xColumn - Return a column value.
  120136. */
  120137. static int fts3tokColumnMethod(
  120138. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  120139. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  120140. int iCol /* Index of column to read value from */
  120141. ){
  120142. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120143. /* CREATE TABLE x(input, token, start, end, position) */
  120144. switch( iCol ){
  120145. case 0:
  120146. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  120147. break;
  120148. case 1:
  120149. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  120150. break;
  120151. case 2:
  120152. sqlite3_result_int(pCtx, pCsr->iStart);
  120153. break;
  120154. case 3:
  120155. sqlite3_result_int(pCtx, pCsr->iEnd);
  120156. break;
  120157. default:
  120158. assert( iCol==4 );
  120159. sqlite3_result_int(pCtx, pCsr->iPos);
  120160. break;
  120161. }
  120162. return SQLITE_OK;
  120163. }
  120164. /*
  120165. ** xRowid - Return the current rowid for the cursor.
  120166. */
  120167. static int fts3tokRowidMethod(
  120168. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  120169. sqlite_int64 *pRowid /* OUT: Rowid value */
  120170. ){
  120171. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  120172. *pRowid = (sqlite3_int64)pCsr->iRowid;
  120173. return SQLITE_OK;
  120174. }
  120175. /*
  120176. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  120177. ** if successful or an error code if sqlite3_create_module() fails.
  120178. */
  120179. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  120180. static const sqlite3_module fts3tok_module = {
  120181. 0, /* iVersion */
  120182. fts3tokConnectMethod, /* xCreate */
  120183. fts3tokConnectMethod, /* xConnect */
  120184. fts3tokBestIndexMethod, /* xBestIndex */
  120185. fts3tokDisconnectMethod, /* xDisconnect */
  120186. fts3tokDisconnectMethod, /* xDestroy */
  120187. fts3tokOpenMethod, /* xOpen */
  120188. fts3tokCloseMethod, /* xClose */
  120189. fts3tokFilterMethod, /* xFilter */
  120190. fts3tokNextMethod, /* xNext */
  120191. fts3tokEofMethod, /* xEof */
  120192. fts3tokColumnMethod, /* xColumn */
  120193. fts3tokRowidMethod, /* xRowid */
  120194. 0, /* xUpdate */
  120195. 0, /* xBegin */
  120196. 0, /* xSync */
  120197. 0, /* xCommit */
  120198. 0, /* xRollback */
  120199. 0, /* xFindFunction */
  120200. 0, /* xRename */
  120201. 0, /* xSavepoint */
  120202. 0, /* xRelease */
  120203. 0 /* xRollbackTo */
  120204. };
  120205. int rc; /* Return code */
  120206. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  120207. return rc;
  120208. }
  120209. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  120210. /************** End of fts3_tokenize_vtab.c **********************************/
  120211. /************** Begin file fts3_write.c **************************************/
  120212. /*
  120213. ** 2009 Oct 23
  120214. **
  120215. ** The author disclaims copyright to this source code. In place of
  120216. ** a legal notice, here is a blessing:
  120217. **
  120218. ** May you do good and not evil.
  120219. ** May you find forgiveness for yourself and forgive others.
  120220. ** May you share freely, never taking more than you give.
  120221. **
  120222. ******************************************************************************
  120223. **
  120224. ** This file is part of the SQLite FTS3 extension module. Specifically,
  120225. ** this file contains code to insert, update and delete rows from FTS3
  120226. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  120227. ** of the sub-routines used to merge segments are also used by the query
  120228. ** code in fts3.c.
  120229. */
  120230. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  120231. /* #include <string.h> */
  120232. /* #include <assert.h> */
  120233. /* #include <stdlib.h> */
  120234. #define FTS_MAX_APPENDABLE_HEIGHT 16
  120235. /*
  120236. ** When full-text index nodes are loaded from disk, the buffer that they
  120237. ** are loaded into has the following number of bytes of padding at the end
  120238. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  120239. ** of 920 bytes is allocated for it.
  120240. **
  120241. ** This means that if we have a pointer into a buffer containing node data,
  120242. ** it is always safe to read up to two varints from it without risking an
  120243. ** overread, even if the node data is corrupted.
  120244. */
  120245. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  120246. /*
  120247. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  120248. ** memory incrementally instead of all at once. This can be a big performance
  120249. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  120250. ** method before retrieving all query results (as may happen, for example,
  120251. ** if a query has a LIMIT clause).
  120252. **
  120253. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  120254. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  120255. ** The code is written so that the hard lower-limit for each of these values
  120256. ** is 1. Clearly such small values would be inefficient, but can be useful
  120257. ** for testing purposes.
  120258. **
  120259. ** If this module is built with SQLITE_TEST defined, these constants may
  120260. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  120261. ** a Tcl interface to read and write the values.
  120262. */
  120263. #ifdef SQLITE_TEST
  120264. int test_fts3_node_chunksize = (4*1024);
  120265. int test_fts3_node_chunk_threshold = (4*1024)*4;
  120266. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  120267. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  120268. #else
  120269. # define FTS3_NODE_CHUNKSIZE (4*1024)
  120270. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  120271. #endif
  120272. /*
  120273. ** The two values that may be meaningfully bound to the :1 parameter in
  120274. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  120275. */
  120276. #define FTS_STAT_DOCTOTAL 0
  120277. #define FTS_STAT_INCRMERGEHINT 1
  120278. #define FTS_STAT_AUTOINCRMERGE 2
  120279. /*
  120280. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  120281. ** and incremental merge operation that takes place. This is used for
  120282. ** debugging FTS only, it should not usually be turned on in production
  120283. ** systems.
  120284. */
  120285. #ifdef FTS3_LOG_MERGES
  120286. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  120287. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  120288. }
  120289. #else
  120290. #define fts3LogMerge(x, y)
  120291. #endif
  120292. typedef struct PendingList PendingList;
  120293. typedef struct SegmentNode SegmentNode;
  120294. typedef struct SegmentWriter SegmentWriter;
  120295. /*
  120296. ** An instance of the following data structure is used to build doclists
  120297. ** incrementally. See function fts3PendingListAppend() for details.
  120298. */
  120299. struct PendingList {
  120300. int nData;
  120301. char *aData;
  120302. int nSpace;
  120303. sqlite3_int64 iLastDocid;
  120304. sqlite3_int64 iLastCol;
  120305. sqlite3_int64 iLastPos;
  120306. };
  120307. /*
  120308. ** Each cursor has a (possibly empty) linked list of the following objects.
  120309. */
  120310. struct Fts3DeferredToken {
  120311. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  120312. int iCol; /* Column token must occur in */
  120313. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  120314. PendingList *pList; /* Doclist is assembled here */
  120315. };
  120316. /*
  120317. ** An instance of this structure is used to iterate through the terms on
  120318. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  120319. ** this structure are only manipulated by code in this file, opaque handles
  120320. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  120321. ** terms when querying the full-text index. See functions:
  120322. **
  120323. ** sqlite3Fts3SegReaderNew()
  120324. ** sqlite3Fts3SegReaderFree()
  120325. ** sqlite3Fts3SegReaderIterate()
  120326. **
  120327. ** Methods used to manipulate Fts3SegReader structures:
  120328. **
  120329. ** fts3SegReaderNext()
  120330. ** fts3SegReaderFirstDocid()
  120331. ** fts3SegReaderNextDocid()
  120332. */
  120333. struct Fts3SegReader {
  120334. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  120335. u8 bLookup; /* True for a lookup only */
  120336. u8 rootOnly; /* True for a root-only reader */
  120337. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  120338. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  120339. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  120340. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  120341. char *aNode; /* Pointer to node data (or NULL) */
  120342. int nNode; /* Size of buffer at aNode (or 0) */
  120343. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  120344. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  120345. Fts3HashElem **ppNextElem;
  120346. /* Variables set by fts3SegReaderNext(). These may be read directly
  120347. ** by the caller. They are valid from the time SegmentReaderNew() returns
  120348. ** until SegmentReaderNext() returns something other than SQLITE_OK
  120349. ** (i.e. SQLITE_DONE).
  120350. */
  120351. int nTerm; /* Number of bytes in current term */
  120352. char *zTerm; /* Pointer to current term */
  120353. int nTermAlloc; /* Allocated size of zTerm buffer */
  120354. char *aDoclist; /* Pointer to doclist of current entry */
  120355. int nDoclist; /* Size of doclist in current entry */
  120356. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  120357. ** through the current doclist (aDoclist/nDoclist).
  120358. */
  120359. char *pOffsetList;
  120360. int nOffsetList; /* For descending pending seg-readers only */
  120361. sqlite3_int64 iDocid;
  120362. };
  120363. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  120364. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  120365. /*
  120366. ** An instance of this structure is used to create a segment b-tree in the
  120367. ** database. The internal details of this type are only accessed by the
  120368. ** following functions:
  120369. **
  120370. ** fts3SegWriterAdd()
  120371. ** fts3SegWriterFlush()
  120372. ** fts3SegWriterFree()
  120373. */
  120374. struct SegmentWriter {
  120375. SegmentNode *pTree; /* Pointer to interior tree structure */
  120376. sqlite3_int64 iFirst; /* First slot in %_segments written */
  120377. sqlite3_int64 iFree; /* Next free slot in %_segments */
  120378. char *zTerm; /* Pointer to previous term buffer */
  120379. int nTerm; /* Number of bytes in zTerm */
  120380. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  120381. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  120382. int nSize; /* Size of allocation at aData */
  120383. int nData; /* Bytes of data in aData */
  120384. char *aData; /* Pointer to block from malloc() */
  120385. };
  120386. /*
  120387. ** Type SegmentNode is used by the following three functions to create
  120388. ** the interior part of the segment b+-tree structures (everything except
  120389. ** the leaf nodes). These functions and type are only ever used by code
  120390. ** within the fts3SegWriterXXX() family of functions described above.
  120391. **
  120392. ** fts3NodeAddTerm()
  120393. ** fts3NodeWrite()
  120394. ** fts3NodeFree()
  120395. **
  120396. ** When a b+tree is written to the database (either as a result of a merge
  120397. ** or the pending-terms table being flushed), leaves are written into the
  120398. ** database file as soon as they are completely populated. The interior of
  120399. ** the tree is assembled in memory and written out only once all leaves have
  120400. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  120401. ** very large, meaning that the interior of the tree consumes relatively
  120402. ** little memory.
  120403. */
  120404. struct SegmentNode {
  120405. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  120406. SegmentNode *pRight; /* Pointer to right-sibling */
  120407. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  120408. int nEntry; /* Number of terms written to node so far */
  120409. char *zTerm; /* Pointer to previous term buffer */
  120410. int nTerm; /* Number of bytes in zTerm */
  120411. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  120412. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  120413. int nData; /* Bytes of valid data so far */
  120414. char *aData; /* Node data */
  120415. };
  120416. /*
  120417. ** Valid values for the second argument to fts3SqlStmt().
  120418. */
  120419. #define SQL_DELETE_CONTENT 0
  120420. #define SQL_IS_EMPTY 1
  120421. #define SQL_DELETE_ALL_CONTENT 2
  120422. #define SQL_DELETE_ALL_SEGMENTS 3
  120423. #define SQL_DELETE_ALL_SEGDIR 4
  120424. #define SQL_DELETE_ALL_DOCSIZE 5
  120425. #define SQL_DELETE_ALL_STAT 6
  120426. #define SQL_SELECT_CONTENT_BY_ROWID 7
  120427. #define SQL_NEXT_SEGMENT_INDEX 8
  120428. #define SQL_INSERT_SEGMENTS 9
  120429. #define SQL_NEXT_SEGMENTS_ID 10
  120430. #define SQL_INSERT_SEGDIR 11
  120431. #define SQL_SELECT_LEVEL 12
  120432. #define SQL_SELECT_LEVEL_RANGE 13
  120433. #define SQL_SELECT_LEVEL_COUNT 14
  120434. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  120435. #define SQL_DELETE_SEGDIR_LEVEL 16
  120436. #define SQL_DELETE_SEGMENTS_RANGE 17
  120437. #define SQL_CONTENT_INSERT 18
  120438. #define SQL_DELETE_DOCSIZE 19
  120439. #define SQL_REPLACE_DOCSIZE 20
  120440. #define SQL_SELECT_DOCSIZE 21
  120441. #define SQL_SELECT_STAT 22
  120442. #define SQL_REPLACE_STAT 23
  120443. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  120444. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  120445. #define SQL_DELETE_SEGDIR_RANGE 26
  120446. #define SQL_SELECT_ALL_LANGID 27
  120447. #define SQL_FIND_MERGE_LEVEL 28
  120448. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  120449. #define SQL_DELETE_SEGDIR_ENTRY 30
  120450. #define SQL_SHIFT_SEGDIR_ENTRY 31
  120451. #define SQL_SELECT_SEGDIR 32
  120452. #define SQL_CHOMP_SEGDIR 33
  120453. #define SQL_SEGMENT_IS_APPENDABLE 34
  120454. #define SQL_SELECT_INDEXES 35
  120455. #define SQL_SELECT_MXLEVEL 36
  120456. /*
  120457. ** This function is used to obtain an SQLite prepared statement handle
  120458. ** for the statement identified by the second argument. If successful,
  120459. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  120460. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  120461. **
  120462. ** If argument apVal is not NULL, then it must point to an array with
  120463. ** at least as many entries as the requested statement has bound
  120464. ** parameters. The values are bound to the statements parameters before
  120465. ** returning.
  120466. */
  120467. static int fts3SqlStmt(
  120468. Fts3Table *p, /* Virtual table handle */
  120469. int eStmt, /* One of the SQL_XXX constants above */
  120470. sqlite3_stmt **pp, /* OUT: Statement handle */
  120471. sqlite3_value **apVal /* Values to bind to statement */
  120472. ){
  120473. const char *azSql[] = {
  120474. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  120475. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  120476. /* 2 */ "DELETE FROM %Q.'%q_content'",
  120477. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  120478. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  120479. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  120480. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  120481. /* 7 */ "SELECT %s WHERE rowid=?",
  120482. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  120483. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  120484. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  120485. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  120486. /* Return segments in order from oldest to newest.*/
  120487. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  120488. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  120489. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  120490. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  120491. "ORDER BY level DESC, idx ASC",
  120492. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  120493. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  120494. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  120495. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  120496. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  120497. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  120498. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  120499. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  120500. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  120501. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  120502. /* 24 */ "",
  120503. /* 25 */ "",
  120504. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  120505. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  120506. /* This statement is used to determine which level to read the input from
  120507. ** when performing an incremental merge. It returns the absolute level number
  120508. ** of the oldest level in the db that contains at least ? segments. Or,
  120509. ** if no level in the FTS index contains more than ? segments, the statement
  120510. ** returns zero rows. */
  120511. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  120512. " ORDER BY (level %% 1024) ASC LIMIT 1",
  120513. /* Estimate the upper limit on the number of leaf nodes in a new segment
  120514. ** created by merging the oldest :2 segments from absolute level :1. See
  120515. ** function sqlite3Fts3Incrmerge() for details. */
  120516. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  120517. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  120518. /* SQL_DELETE_SEGDIR_ENTRY
  120519. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  120520. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  120521. /* SQL_SHIFT_SEGDIR_ENTRY
  120522. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  120523. ** to :1. */
  120524. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  120525. /* SQL_SELECT_SEGDIR
  120526. ** Read a single entry from the %_segdir table. The entry from absolute
  120527. ** level :1 with index value :2. */
  120528. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  120529. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  120530. /* SQL_CHOMP_SEGDIR
  120531. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  120532. ** entry located on absolute level :3 with index :4. */
  120533. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  120534. "WHERE level = ? AND idx = ?",
  120535. /* SQL_SEGMENT_IS_APPENDABLE
  120536. ** Return a single row if the segment with end_block=? is appendable. Or
  120537. ** no rows otherwise. */
  120538. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  120539. /* SQL_SELECT_INDEXES
  120540. ** Return the list of valid segment indexes for absolute level ? */
  120541. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  120542. /* SQL_SELECT_MXLEVEL
  120543. ** Return the largest relative level in the FTS index or indexes. */
  120544. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  120545. };
  120546. int rc = SQLITE_OK;
  120547. sqlite3_stmt *pStmt;
  120548. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  120549. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  120550. pStmt = p->aStmt[eStmt];
  120551. if( !pStmt ){
  120552. char *zSql;
  120553. if( eStmt==SQL_CONTENT_INSERT ){
  120554. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  120555. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  120556. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  120557. }else{
  120558. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  120559. }
  120560. if( !zSql ){
  120561. rc = SQLITE_NOMEM;
  120562. }else{
  120563. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  120564. sqlite3_free(zSql);
  120565. assert( rc==SQLITE_OK || pStmt==0 );
  120566. p->aStmt[eStmt] = pStmt;
  120567. }
  120568. }
  120569. if( apVal ){
  120570. int i;
  120571. int nParam = sqlite3_bind_parameter_count(pStmt);
  120572. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  120573. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  120574. }
  120575. }
  120576. *pp = pStmt;
  120577. return rc;
  120578. }
  120579. static int fts3SelectDocsize(
  120580. Fts3Table *pTab, /* FTS3 table handle */
  120581. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  120582. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  120583. ){
  120584. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  120585. int rc; /* Return code */
  120586. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  120587. if( rc==SQLITE_OK ){
  120588. sqlite3_bind_int64(pStmt, 1, iDocid);
  120589. rc = sqlite3_step(pStmt);
  120590. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  120591. rc = sqlite3_reset(pStmt);
  120592. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  120593. pStmt = 0;
  120594. }else{
  120595. rc = SQLITE_OK;
  120596. }
  120597. }
  120598. *ppStmt = pStmt;
  120599. return rc;
  120600. }
  120601. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  120602. Fts3Table *pTab, /* Fts3 table handle */
  120603. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  120604. ){
  120605. sqlite3_stmt *pStmt = 0;
  120606. int rc;
  120607. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  120608. if( rc==SQLITE_OK ){
  120609. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  120610. if( sqlite3_step(pStmt)!=SQLITE_ROW
  120611. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  120612. ){
  120613. rc = sqlite3_reset(pStmt);
  120614. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  120615. pStmt = 0;
  120616. }
  120617. }
  120618. *ppStmt = pStmt;
  120619. return rc;
  120620. }
  120621. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  120622. Fts3Table *pTab, /* Fts3 table handle */
  120623. sqlite3_int64 iDocid, /* Docid to read size data for */
  120624. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  120625. ){
  120626. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  120627. }
  120628. /*
  120629. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  120630. ** array apVal[] to the SQL statement identified by eStmt, the statement
  120631. ** is executed.
  120632. **
  120633. ** Returns SQLITE_OK if the statement is successfully executed, or an
  120634. ** SQLite error code otherwise.
  120635. */
  120636. static void fts3SqlExec(
  120637. int *pRC, /* Result code */
  120638. Fts3Table *p, /* The FTS3 table */
  120639. int eStmt, /* Index of statement to evaluate */
  120640. sqlite3_value **apVal /* Parameters to bind */
  120641. ){
  120642. sqlite3_stmt *pStmt;
  120643. int rc;
  120644. if( *pRC ) return;
  120645. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  120646. if( rc==SQLITE_OK ){
  120647. sqlite3_step(pStmt);
  120648. rc = sqlite3_reset(pStmt);
  120649. }
  120650. *pRC = rc;
  120651. }
  120652. /*
  120653. ** This function ensures that the caller has obtained a shared-cache
  120654. ** table-lock on the %_content table. This is required before reading
  120655. ** data from the fts3 table. If this lock is not acquired first, then
  120656. ** the caller may end up holding read-locks on the %_segments and %_segdir
  120657. ** tables, but no read-lock on the %_content table. If this happens
  120658. ** a second connection will be able to write to the fts3 table, but
  120659. ** attempting to commit those writes might return SQLITE_LOCKED or
  120660. ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
  120661. ** write-locks on the %_segments and %_segdir ** tables).
  120662. **
  120663. ** We try to avoid this because if FTS3 returns any error when committing
  120664. ** a transaction, the whole transaction will be rolled back. And this is
  120665. ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
  120666. ** still happen if the user reads data directly from the %_segments or
  120667. ** %_segdir tables instead of going through FTS3 though.
  120668. **
  120669. ** This reasoning does not apply to a content=xxx table.
  120670. */
  120671. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
  120672. int rc; /* Return code */
  120673. sqlite3_stmt *pStmt; /* Statement used to obtain lock */
  120674. if( p->zContentTbl==0 ){
  120675. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
  120676. if( rc==SQLITE_OK ){
  120677. sqlite3_bind_null(pStmt, 1);
  120678. sqlite3_step(pStmt);
  120679. rc = sqlite3_reset(pStmt);
  120680. }
  120681. }else{
  120682. rc = SQLITE_OK;
  120683. }
  120684. return rc;
  120685. }
  120686. /*
  120687. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  120688. ** Within each language id, a separate index is maintained to store the
  120689. ** document terms, and each configured prefix size (configured the FTS
  120690. ** "prefix=" option). And each index consists of multiple levels ("relative
  120691. ** levels").
  120692. **
  120693. ** All three of these values (the language id, the specific index and the
  120694. ** level within the index) are encoded in 64-bit integer values stored
  120695. ** in the %_segdir table on disk. This function is used to convert three
  120696. ** separate component values into the single 64-bit integer value that
  120697. ** can be used to query the %_segdir table.
  120698. **
  120699. ** Specifically, each language-id/index combination is allocated 1024
  120700. ** 64-bit integer level values ("absolute levels"). The main terms index
  120701. ** for language-id 0 is allocate values 0-1023. The first prefix index
  120702. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  120703. ** Language 1 indexes are allocated immediately following language 0.
  120704. **
  120705. ** So, for a system with nPrefix prefix indexes configured, the block of
  120706. ** absolute levels that corresponds to language-id iLangid and index
  120707. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  120708. */
  120709. static sqlite3_int64 getAbsoluteLevel(
  120710. Fts3Table *p, /* FTS3 table handle */
  120711. int iLangid, /* Language id */
  120712. int iIndex, /* Index in p->aIndex[] */
  120713. int iLevel /* Level of segments */
  120714. ){
  120715. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  120716. assert( iLangid>=0 );
  120717. assert( p->nIndex>0 );
  120718. assert( iIndex>=0 && iIndex<p->nIndex );
  120719. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  120720. return iBase + iLevel;
  120721. }
  120722. /*
  120723. ** Set *ppStmt to a statement handle that may be used to iterate through
  120724. ** all rows in the %_segdir table, from oldest to newest. If successful,
  120725. ** return SQLITE_OK. If an error occurs while preparing the statement,
  120726. ** return an SQLite error code.
  120727. **
  120728. ** There is only ever one instance of this SQL statement compiled for
  120729. ** each FTS3 table.
  120730. **
  120731. ** The statement returns the following columns from the %_segdir table:
  120732. **
  120733. ** 0: idx
  120734. ** 1: start_block
  120735. ** 2: leaves_end_block
  120736. ** 3: end_block
  120737. ** 4: root
  120738. */
  120739. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  120740. Fts3Table *p, /* FTS3 table */
  120741. int iLangid, /* Language being queried */
  120742. int iIndex, /* Index for p->aIndex[] */
  120743. int iLevel, /* Level to select (relative level) */
  120744. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  120745. ){
  120746. int rc;
  120747. sqlite3_stmt *pStmt = 0;
  120748. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  120749. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  120750. assert( iIndex>=0 && iIndex<p->nIndex );
  120751. if( iLevel<0 ){
  120752. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  120753. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  120754. if( rc==SQLITE_OK ){
  120755. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  120756. sqlite3_bind_int64(pStmt, 2,
  120757. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  120758. );
  120759. }
  120760. }else{
  120761. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  120762. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  120763. if( rc==SQLITE_OK ){
  120764. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  120765. }
  120766. }
  120767. *ppStmt = pStmt;
  120768. return rc;
  120769. }
  120770. /*
  120771. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  120772. ** if successful, or an SQLite error code otherwise.
  120773. **
  120774. ** This function also serves to allocate the PendingList structure itself.
  120775. ** For example, to create a new PendingList structure containing two
  120776. ** varints:
  120777. **
  120778. ** PendingList *p = 0;
  120779. ** fts3PendingListAppendVarint(&p, 1);
  120780. ** fts3PendingListAppendVarint(&p, 2);
  120781. */
  120782. static int fts3PendingListAppendVarint(
  120783. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  120784. sqlite3_int64 i /* Value to append to data */
  120785. ){
  120786. PendingList *p = *pp;
  120787. /* Allocate or grow the PendingList as required. */
  120788. if( !p ){
  120789. p = sqlite3_malloc(sizeof(*p) + 100);
  120790. if( !p ){
  120791. return SQLITE_NOMEM;
  120792. }
  120793. p->nSpace = 100;
  120794. p->aData = (char *)&p[1];
  120795. p->nData = 0;
  120796. }
  120797. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  120798. int nNew = p->nSpace * 2;
  120799. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  120800. if( !p ){
  120801. sqlite3_free(*pp);
  120802. *pp = 0;
  120803. return SQLITE_NOMEM;
  120804. }
  120805. p->nSpace = nNew;
  120806. p->aData = (char *)&p[1];
  120807. }
  120808. /* Append the new serialized varint to the end of the list. */
  120809. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  120810. p->aData[p->nData] = '\0';
  120811. *pp = p;
  120812. return SQLITE_OK;
  120813. }
  120814. /*
  120815. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  120816. ** is returned if the structure is sqlite3_realloced as part of adding
  120817. ** the entry. Otherwise, zero.
  120818. **
  120819. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  120820. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  120821. ** it is set to SQLITE_OK.
  120822. */
  120823. static int fts3PendingListAppend(
  120824. PendingList **pp, /* IN/OUT: PendingList structure */
  120825. sqlite3_int64 iDocid, /* Docid for entry to add */
  120826. sqlite3_int64 iCol, /* Column for entry to add */
  120827. sqlite3_int64 iPos, /* Position of term for entry to add */
  120828. int *pRc /* OUT: Return code */
  120829. ){
  120830. PendingList *p = *pp;
  120831. int rc = SQLITE_OK;
  120832. assert( !p || p->iLastDocid<=iDocid );
  120833. if( !p || p->iLastDocid!=iDocid ){
  120834. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  120835. if( p ){
  120836. assert( p->nData<p->nSpace );
  120837. assert( p->aData[p->nData]==0 );
  120838. p->nData++;
  120839. }
  120840. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  120841. goto pendinglistappend_out;
  120842. }
  120843. p->iLastCol = -1;
  120844. p->iLastPos = 0;
  120845. p->iLastDocid = iDocid;
  120846. }
  120847. if( iCol>0 && p->iLastCol!=iCol ){
  120848. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  120849. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  120850. ){
  120851. goto pendinglistappend_out;
  120852. }
  120853. p->iLastCol = iCol;
  120854. p->iLastPos = 0;
  120855. }
  120856. if( iCol>=0 ){
  120857. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  120858. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  120859. if( rc==SQLITE_OK ){
  120860. p->iLastPos = iPos;
  120861. }
  120862. }
  120863. pendinglistappend_out:
  120864. *pRc = rc;
  120865. if( p!=*pp ){
  120866. *pp = p;
  120867. return 1;
  120868. }
  120869. return 0;
  120870. }
  120871. /*
  120872. ** Free a PendingList object allocated by fts3PendingListAppend().
  120873. */
  120874. static void fts3PendingListDelete(PendingList *pList){
  120875. sqlite3_free(pList);
  120876. }
  120877. /*
  120878. ** Add an entry to one of the pending-terms hash tables.
  120879. */
  120880. static int fts3PendingTermsAddOne(
  120881. Fts3Table *p,
  120882. int iCol,
  120883. int iPos,
  120884. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  120885. const char *zToken,
  120886. int nToken
  120887. ){
  120888. PendingList *pList;
  120889. int rc = SQLITE_OK;
  120890. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  120891. if( pList ){
  120892. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  120893. }
  120894. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  120895. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  120896. /* Malloc failed while inserting the new entry. This can only
  120897. ** happen if there was no previous entry for this token.
  120898. */
  120899. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  120900. sqlite3_free(pList);
  120901. rc = SQLITE_NOMEM;
  120902. }
  120903. }
  120904. if( rc==SQLITE_OK ){
  120905. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  120906. }
  120907. return rc;
  120908. }
  120909. /*
  120910. ** Tokenize the nul-terminated string zText and add all tokens to the
  120911. ** pending-terms hash-table. The docid used is that currently stored in
  120912. ** p->iPrevDocid, and the column is specified by argument iCol.
  120913. **
  120914. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  120915. */
  120916. static int fts3PendingTermsAdd(
  120917. Fts3Table *p, /* Table into which text will be inserted */
  120918. int iLangid, /* Language id to use */
  120919. const char *zText, /* Text of document to be inserted */
  120920. int iCol, /* Column into which text is being inserted */
  120921. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  120922. ){
  120923. int rc;
  120924. int iStart = 0;
  120925. int iEnd = 0;
  120926. int iPos = 0;
  120927. int nWord = 0;
  120928. char const *zToken;
  120929. int nToken = 0;
  120930. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  120931. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  120932. sqlite3_tokenizer_cursor *pCsr;
  120933. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  120934. const char**,int*,int*,int*,int*);
  120935. assert( pTokenizer && pModule );
  120936. /* If the user has inserted a NULL value, this function may be called with
  120937. ** zText==0. In this case, add zero token entries to the hash table and
  120938. ** return early. */
  120939. if( zText==0 ){
  120940. *pnWord = 0;
  120941. return SQLITE_OK;
  120942. }
  120943. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  120944. if( rc!=SQLITE_OK ){
  120945. return rc;
  120946. }
  120947. xNext = pModule->xNext;
  120948. while( SQLITE_OK==rc
  120949. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  120950. ){
  120951. int i;
  120952. if( iPos>=nWord ) nWord = iPos+1;
  120953. /* Positions cannot be negative; we use -1 as a terminator internally.
  120954. ** Tokens must have a non-zero length.
  120955. */
  120956. if( iPos<0 || !zToken || nToken<=0 ){
  120957. rc = SQLITE_ERROR;
  120958. break;
  120959. }
  120960. /* Add the term to the terms index */
  120961. rc = fts3PendingTermsAddOne(
  120962. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  120963. );
  120964. /* Add the term to each of the prefix indexes that it is not too
  120965. ** short for. */
  120966. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  120967. struct Fts3Index *pIndex = &p->aIndex[i];
  120968. if( nToken<pIndex->nPrefix ) continue;
  120969. rc = fts3PendingTermsAddOne(
  120970. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  120971. );
  120972. }
  120973. }
  120974. pModule->xClose(pCsr);
  120975. *pnWord += nWord;
  120976. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  120977. }
  120978. /*
  120979. ** Calling this function indicates that subsequent calls to
  120980. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  120981. ** contents of the document with docid iDocid.
  120982. */
  120983. static int fts3PendingTermsDocid(
  120984. Fts3Table *p, /* Full-text table handle */
  120985. int iLangid, /* Language id of row being written */
  120986. sqlite_int64 iDocid /* Docid of row being written */
  120987. ){
  120988. assert( iLangid>=0 );
  120989. /* TODO(shess) Explore whether partially flushing the buffer on
  120990. ** forced-flush would provide better performance. I suspect that if
  120991. ** we ordered the doclists by size and flushed the largest until the
  120992. ** buffer was half empty, that would let the less frequent terms
  120993. ** generate longer doclists.
  120994. */
  120995. if( iDocid<=p->iPrevDocid
  120996. || p->iPrevLangid!=iLangid
  120997. || p->nPendingData>p->nMaxPendingData
  120998. ){
  120999. int rc = sqlite3Fts3PendingTermsFlush(p);
  121000. if( rc!=SQLITE_OK ) return rc;
  121001. }
  121002. p->iPrevDocid = iDocid;
  121003. p->iPrevLangid = iLangid;
  121004. return SQLITE_OK;
  121005. }
  121006. /*
  121007. ** Discard the contents of the pending-terms hash tables.
  121008. */
  121009. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  121010. int i;
  121011. for(i=0; i<p->nIndex; i++){
  121012. Fts3HashElem *pElem;
  121013. Fts3Hash *pHash = &p->aIndex[i].hPending;
  121014. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  121015. PendingList *pList = (PendingList *)fts3HashData(pElem);
  121016. fts3PendingListDelete(pList);
  121017. }
  121018. fts3HashClear(pHash);
  121019. }
  121020. p->nPendingData = 0;
  121021. }
  121022. /*
  121023. ** This function is called by the xUpdate() method as part of an INSERT
  121024. ** operation. It adds entries for each term in the new record to the
  121025. ** pendingTerms hash table.
  121026. **
  121027. ** Argument apVal is the same as the similarly named argument passed to
  121028. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  121029. */
  121030. static int fts3InsertTerms(
  121031. Fts3Table *p,
  121032. int iLangid,
  121033. sqlite3_value **apVal,
  121034. u32 *aSz
  121035. ){
  121036. int i; /* Iterator variable */
  121037. for(i=2; i<p->nColumn+2; i++){
  121038. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  121039. int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
  121040. if( rc!=SQLITE_OK ){
  121041. return rc;
  121042. }
  121043. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  121044. }
  121045. return SQLITE_OK;
  121046. }
  121047. /*
  121048. ** This function is called by the xUpdate() method for an INSERT operation.
  121049. ** The apVal parameter is passed a copy of the apVal argument passed by
  121050. ** SQLite to the xUpdate() method. i.e:
  121051. **
  121052. ** apVal[0] Not used for INSERT.
  121053. ** apVal[1] rowid
  121054. ** apVal[2] Left-most user-defined column
  121055. ** ...
  121056. ** apVal[p->nColumn+1] Right-most user-defined column
  121057. ** apVal[p->nColumn+2] Hidden column with same name as table
  121058. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  121059. ** apVal[p->nColumn+4] Hidden languageid column
  121060. */
  121061. static int fts3InsertData(
  121062. Fts3Table *p, /* Full-text table */
  121063. sqlite3_value **apVal, /* Array of values to insert */
  121064. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  121065. ){
  121066. int rc; /* Return code */
  121067. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  121068. if( p->zContentTbl ){
  121069. sqlite3_value *pRowid = apVal[p->nColumn+3];
  121070. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  121071. pRowid = apVal[1];
  121072. }
  121073. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  121074. return SQLITE_CONSTRAINT;
  121075. }
  121076. *piDocid = sqlite3_value_int64(pRowid);
  121077. return SQLITE_OK;
  121078. }
  121079. /* Locate the statement handle used to insert data into the %_content
  121080. ** table. The SQL for this statement is:
  121081. **
  121082. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  121083. **
  121084. ** The statement features N '?' variables, where N is the number of user
  121085. ** defined columns in the FTS3 table, plus one for the docid field.
  121086. */
  121087. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  121088. if( rc==SQLITE_OK && p->zLanguageid ){
  121089. rc = sqlite3_bind_int(
  121090. pContentInsert, p->nColumn+2,
  121091. sqlite3_value_int(apVal[p->nColumn+4])
  121092. );
  121093. }
  121094. if( rc!=SQLITE_OK ) return rc;
  121095. /* There is a quirk here. The users INSERT statement may have specified
  121096. ** a value for the "rowid" field, for the "docid" field, or for both.
  121097. ** Which is a problem, since "rowid" and "docid" are aliases for the
  121098. ** same value. For example:
  121099. **
  121100. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  121101. **
  121102. ** In FTS3, this is an error. It is an error to specify non-NULL values
  121103. ** for both docid and some other rowid alias.
  121104. */
  121105. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  121106. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  121107. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  121108. ){
  121109. /* A rowid/docid conflict. */
  121110. return SQLITE_ERROR;
  121111. }
  121112. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  121113. if( rc!=SQLITE_OK ) return rc;
  121114. }
  121115. /* Execute the statement to insert the record. Set *piDocid to the
  121116. ** new docid value.
  121117. */
  121118. sqlite3_step(pContentInsert);
  121119. rc = sqlite3_reset(pContentInsert);
  121120. *piDocid = sqlite3_last_insert_rowid(p->db);
  121121. return rc;
  121122. }
  121123. /*
  121124. ** Remove all data from the FTS3 table. Clear the hash table containing
  121125. ** pending terms.
  121126. */
  121127. static int fts3DeleteAll(Fts3Table *p, int bContent){
  121128. int rc = SQLITE_OK; /* Return code */
  121129. /* Discard the contents of the pending-terms hash table. */
  121130. sqlite3Fts3PendingTermsClear(p);
  121131. /* Delete everything from the shadow tables. Except, leave %_content as
  121132. ** is if bContent is false. */
  121133. assert( p->zContentTbl==0 || bContent==0 );
  121134. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  121135. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  121136. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  121137. if( p->bHasDocsize ){
  121138. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  121139. }
  121140. if( p->bHasStat ){
  121141. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  121142. }
  121143. return rc;
  121144. }
  121145. /*
  121146. **
  121147. */
  121148. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  121149. int iLangid = 0;
  121150. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  121151. return iLangid;
  121152. }
  121153. /*
  121154. ** The first element in the apVal[] array is assumed to contain the docid
  121155. ** (an integer) of a row about to be deleted. Remove all terms from the
  121156. ** full-text index.
  121157. */
  121158. static void fts3DeleteTerms(
  121159. int *pRC, /* Result code */
  121160. Fts3Table *p, /* The FTS table to delete from */
  121161. sqlite3_value *pRowid, /* The docid to be deleted */
  121162. u32 *aSz, /* Sizes of deleted document written here */
  121163. int *pbFound /* OUT: Set to true if row really does exist */
  121164. ){
  121165. int rc;
  121166. sqlite3_stmt *pSelect;
  121167. assert( *pbFound==0 );
  121168. if( *pRC ) return;
  121169. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  121170. if( rc==SQLITE_OK ){
  121171. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  121172. int i;
  121173. int iLangid = langidFromSelect(p, pSelect);
  121174. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  121175. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  121176. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  121177. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
  121178. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  121179. }
  121180. if( rc!=SQLITE_OK ){
  121181. sqlite3_reset(pSelect);
  121182. *pRC = rc;
  121183. return;
  121184. }
  121185. *pbFound = 1;
  121186. }
  121187. rc = sqlite3_reset(pSelect);
  121188. }else{
  121189. sqlite3_reset(pSelect);
  121190. }
  121191. *pRC = rc;
  121192. }
  121193. /*
  121194. ** Forward declaration to account for the circular dependency between
  121195. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  121196. */
  121197. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  121198. /*
  121199. ** This function allocates a new level iLevel index in the segdir table.
  121200. ** Usually, indexes are allocated within a level sequentially starting
  121201. ** with 0, so the allocated index is one greater than the value returned
  121202. ** by:
  121203. **
  121204. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  121205. **
  121206. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  121207. ** level, they are merged into a single level (iLevel+1) segment and the
  121208. ** allocated index is 0.
  121209. **
  121210. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  121211. ** returned. Otherwise, an SQLite error code is returned.
  121212. */
  121213. static int fts3AllocateSegdirIdx(
  121214. Fts3Table *p,
  121215. int iLangid, /* Language id */
  121216. int iIndex, /* Index for p->aIndex */
  121217. int iLevel,
  121218. int *piIdx
  121219. ){
  121220. int rc; /* Return Code */
  121221. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  121222. int iNext = 0; /* Result of query pNextIdx */
  121223. assert( iLangid>=0 );
  121224. assert( p->nIndex>=1 );
  121225. /* Set variable iNext to the next available segdir index at level iLevel. */
  121226. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  121227. if( rc==SQLITE_OK ){
  121228. sqlite3_bind_int64(
  121229. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  121230. );
  121231. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  121232. iNext = sqlite3_column_int(pNextIdx, 0);
  121233. }
  121234. rc = sqlite3_reset(pNextIdx);
  121235. }
  121236. if( rc==SQLITE_OK ){
  121237. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  121238. ** full, merge all segments in level iLevel into a single iLevel+1
  121239. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  121240. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  121241. */
  121242. if( iNext>=FTS3_MERGE_COUNT ){
  121243. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  121244. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  121245. *piIdx = 0;
  121246. }else{
  121247. *piIdx = iNext;
  121248. }
  121249. }
  121250. return rc;
  121251. }
  121252. /*
  121253. ** The %_segments table is declared as follows:
  121254. **
  121255. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  121256. **
  121257. ** This function reads data from a single row of the %_segments table. The
  121258. ** specific row is identified by the iBlockid parameter. If paBlob is not
  121259. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  121260. ** with the contents of the blob stored in the "block" column of the
  121261. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  121262. ** to the size of the blob in bytes before returning.
  121263. **
  121264. ** If an error occurs, or the table does not contain the specified row,
  121265. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  121266. ** paBlob is non-NULL, then it is the responsibility of the caller to
  121267. ** eventually free the returned buffer.
  121268. **
  121269. ** This function may leave an open sqlite3_blob* handle in the
  121270. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  121271. ** to this function. The handle may be closed by calling the
  121272. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  121273. ** performance improvement, but the blob handle should always be closed
  121274. ** before control is returned to the user (to prevent a lock being held
  121275. ** on the database file for longer than necessary). Thus, any virtual table
  121276. ** method (xFilter etc.) that may directly or indirectly call this function
  121277. ** must call sqlite3Fts3SegmentsClose() before returning.
  121278. */
  121279. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  121280. Fts3Table *p, /* FTS3 table handle */
  121281. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  121282. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  121283. int *pnBlob, /* OUT: Size of blob data */
  121284. int *pnLoad /* OUT: Bytes actually loaded */
  121285. ){
  121286. int rc; /* Return code */
  121287. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  121288. assert( pnBlob );
  121289. if( p->pSegments ){
  121290. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  121291. }else{
  121292. if( 0==p->zSegmentsTbl ){
  121293. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  121294. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  121295. }
  121296. rc = sqlite3_blob_open(
  121297. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  121298. );
  121299. }
  121300. if( rc==SQLITE_OK ){
  121301. int nByte = sqlite3_blob_bytes(p->pSegments);
  121302. *pnBlob = nByte;
  121303. if( paBlob ){
  121304. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  121305. if( !aByte ){
  121306. rc = SQLITE_NOMEM;
  121307. }else{
  121308. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  121309. nByte = FTS3_NODE_CHUNKSIZE;
  121310. *pnLoad = nByte;
  121311. }
  121312. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  121313. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  121314. if( rc!=SQLITE_OK ){
  121315. sqlite3_free(aByte);
  121316. aByte = 0;
  121317. }
  121318. }
  121319. *paBlob = aByte;
  121320. }
  121321. }
  121322. return rc;
  121323. }
  121324. /*
  121325. ** Close the blob handle at p->pSegments, if it is open. See comments above
  121326. ** the sqlite3Fts3ReadBlock() function for details.
  121327. */
  121328. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  121329. sqlite3_blob_close(p->pSegments);
  121330. p->pSegments = 0;
  121331. }
  121332. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  121333. int nRead; /* Number of bytes to read */
  121334. int rc; /* Return code */
  121335. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  121336. rc = sqlite3_blob_read(
  121337. pReader->pBlob,
  121338. &pReader->aNode[pReader->nPopulate],
  121339. nRead,
  121340. pReader->nPopulate
  121341. );
  121342. if( rc==SQLITE_OK ){
  121343. pReader->nPopulate += nRead;
  121344. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  121345. if( pReader->nPopulate==pReader->nNode ){
  121346. sqlite3_blob_close(pReader->pBlob);
  121347. pReader->pBlob = 0;
  121348. pReader->nPopulate = 0;
  121349. }
  121350. }
  121351. return rc;
  121352. }
  121353. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  121354. int rc = SQLITE_OK;
  121355. assert( !pReader->pBlob
  121356. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  121357. );
  121358. while( pReader->pBlob && rc==SQLITE_OK
  121359. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  121360. ){
  121361. rc = fts3SegReaderIncrRead(pReader);
  121362. }
  121363. return rc;
  121364. }
  121365. /*
  121366. ** Set an Fts3SegReader cursor to point at EOF.
  121367. */
  121368. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  121369. if( !fts3SegReaderIsRootOnly(pSeg) ){
  121370. sqlite3_free(pSeg->aNode);
  121371. sqlite3_blob_close(pSeg->pBlob);
  121372. pSeg->pBlob = 0;
  121373. }
  121374. pSeg->aNode = 0;
  121375. }
  121376. /*
  121377. ** Move the iterator passed as the first argument to the next term in the
  121378. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  121379. ** SQLITE_DONE. Otherwise, an SQLite error code.
  121380. */
  121381. static int fts3SegReaderNext(
  121382. Fts3Table *p,
  121383. Fts3SegReader *pReader,
  121384. int bIncr
  121385. ){
  121386. int rc; /* Return code of various sub-routines */
  121387. char *pNext; /* Cursor variable */
  121388. int nPrefix; /* Number of bytes in term prefix */
  121389. int nSuffix; /* Number of bytes in term suffix */
  121390. if( !pReader->aDoclist ){
  121391. pNext = pReader->aNode;
  121392. }else{
  121393. pNext = &pReader->aDoclist[pReader->nDoclist];
  121394. }
  121395. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  121396. if( fts3SegReaderIsPending(pReader) ){
  121397. Fts3HashElem *pElem = *(pReader->ppNextElem);
  121398. if( pElem==0 ){
  121399. pReader->aNode = 0;
  121400. }else{
  121401. PendingList *pList = (PendingList *)fts3HashData(pElem);
  121402. pReader->zTerm = (char *)fts3HashKey(pElem);
  121403. pReader->nTerm = fts3HashKeysize(pElem);
  121404. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  121405. pReader->aNode = pReader->aDoclist = pList->aData;
  121406. pReader->ppNextElem++;
  121407. assert( pReader->aNode );
  121408. }
  121409. return SQLITE_OK;
  121410. }
  121411. fts3SegReaderSetEof(pReader);
  121412. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  121413. ** blocks have already been traversed. */
  121414. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  121415. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  121416. return SQLITE_OK;
  121417. }
  121418. rc = sqlite3Fts3ReadBlock(
  121419. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  121420. (bIncr ? &pReader->nPopulate : 0)
  121421. );
  121422. if( rc!=SQLITE_OK ) return rc;
  121423. assert( pReader->pBlob==0 );
  121424. if( bIncr && pReader->nPopulate<pReader->nNode ){
  121425. pReader->pBlob = p->pSegments;
  121426. p->pSegments = 0;
  121427. }
  121428. pNext = pReader->aNode;
  121429. }
  121430. assert( !fts3SegReaderIsPending(pReader) );
  121431. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  121432. if( rc!=SQLITE_OK ) return rc;
  121433. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  121434. ** safe (no risk of overread) even if the node data is corrupted. */
  121435. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  121436. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  121437. if( nPrefix<0 || nSuffix<=0
  121438. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  121439. ){
  121440. return FTS_CORRUPT_VTAB;
  121441. }
  121442. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  121443. int nNew = (nPrefix+nSuffix)*2;
  121444. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  121445. if( !zNew ){
  121446. return SQLITE_NOMEM;
  121447. }
  121448. pReader->zTerm = zNew;
  121449. pReader->nTermAlloc = nNew;
  121450. }
  121451. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  121452. if( rc!=SQLITE_OK ) return rc;
  121453. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  121454. pReader->nTerm = nPrefix+nSuffix;
  121455. pNext += nSuffix;
  121456. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  121457. pReader->aDoclist = pNext;
  121458. pReader->pOffsetList = 0;
  121459. /* Check that the doclist does not appear to extend past the end of the
  121460. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  121461. ** of these statements is untrue, then the data structure is corrupt.
  121462. */
  121463. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  121464. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  121465. ){
  121466. return FTS_CORRUPT_VTAB;
  121467. }
  121468. return SQLITE_OK;
  121469. }
  121470. /*
  121471. ** Set the SegReader to point to the first docid in the doclist associated
  121472. ** with the current term.
  121473. */
  121474. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  121475. int rc = SQLITE_OK;
  121476. assert( pReader->aDoclist );
  121477. assert( !pReader->pOffsetList );
  121478. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  121479. u8 bEof = 0;
  121480. pReader->iDocid = 0;
  121481. pReader->nOffsetList = 0;
  121482. sqlite3Fts3DoclistPrev(0,
  121483. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  121484. &pReader->iDocid, &pReader->nOffsetList, &bEof
  121485. );
  121486. }else{
  121487. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  121488. if( rc==SQLITE_OK ){
  121489. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  121490. pReader->pOffsetList = &pReader->aDoclist[n];
  121491. }
  121492. }
  121493. return rc;
  121494. }
  121495. /*
  121496. ** Advance the SegReader to point to the next docid in the doclist
  121497. ** associated with the current term.
  121498. **
  121499. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  121500. ** *ppOffsetList is set to point to the first column-offset list
  121501. ** in the doclist entry (i.e. immediately past the docid varint).
  121502. ** *pnOffsetList is set to the length of the set of column-offset
  121503. ** lists, not including the nul-terminator byte. For example:
  121504. */
  121505. static int fts3SegReaderNextDocid(
  121506. Fts3Table *pTab,
  121507. Fts3SegReader *pReader, /* Reader to advance to next docid */
  121508. char **ppOffsetList, /* OUT: Pointer to current position-list */
  121509. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  121510. ){
  121511. int rc = SQLITE_OK;
  121512. char *p = pReader->pOffsetList;
  121513. char c = 0;
  121514. assert( p );
  121515. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  121516. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  121517. ** Pending-terms doclists are always built up in ascending order, so
  121518. ** we have to iterate through them backwards here. */
  121519. u8 bEof = 0;
  121520. if( ppOffsetList ){
  121521. *ppOffsetList = pReader->pOffsetList;
  121522. *pnOffsetList = pReader->nOffsetList - 1;
  121523. }
  121524. sqlite3Fts3DoclistPrev(0,
  121525. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  121526. &pReader->nOffsetList, &bEof
  121527. );
  121528. if( bEof ){
  121529. pReader->pOffsetList = 0;
  121530. }else{
  121531. pReader->pOffsetList = p;
  121532. }
  121533. }else{
  121534. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  121535. /* Pointer p currently points at the first byte of an offset list. The
  121536. ** following block advances it to point one byte past the end of
  121537. ** the same offset list. */
  121538. while( 1 ){
  121539. /* The following line of code (and the "p++" below the while() loop) is
  121540. ** normally all that is required to move pointer p to the desired
  121541. ** position. The exception is if this node is being loaded from disk
  121542. ** incrementally and pointer "p" now points to the first byte passed
  121543. ** the populated part of pReader->aNode[].
  121544. */
  121545. while( *p | c ) c = *p++ & 0x80;
  121546. assert( *p==0 );
  121547. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  121548. rc = fts3SegReaderIncrRead(pReader);
  121549. if( rc!=SQLITE_OK ) return rc;
  121550. }
  121551. p++;
  121552. /* If required, populate the output variables with a pointer to and the
  121553. ** size of the previous offset-list.
  121554. */
  121555. if( ppOffsetList ){
  121556. *ppOffsetList = pReader->pOffsetList;
  121557. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  121558. }
  121559. /* List may have been edited in place by fts3EvalNearTrim() */
  121560. while( p<pEnd && *p==0 ) p++;
  121561. /* If there are no more entries in the doclist, set pOffsetList to
  121562. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  121563. ** Fts3SegReader.pOffsetList to point to the next offset list before
  121564. ** returning.
  121565. */
  121566. if( p>=pEnd ){
  121567. pReader->pOffsetList = 0;
  121568. }else{
  121569. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  121570. if( rc==SQLITE_OK ){
  121571. sqlite3_int64 iDelta;
  121572. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  121573. if( pTab->bDescIdx ){
  121574. pReader->iDocid -= iDelta;
  121575. }else{
  121576. pReader->iDocid += iDelta;
  121577. }
  121578. }
  121579. }
  121580. }
  121581. return SQLITE_OK;
  121582. }
  121583. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  121584. Fts3Cursor *pCsr,
  121585. Fts3MultiSegReader *pMsr,
  121586. int *pnOvfl
  121587. ){
  121588. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  121589. int nOvfl = 0;
  121590. int ii;
  121591. int rc = SQLITE_OK;
  121592. int pgsz = p->nPgsz;
  121593. assert( p->bFts4 );
  121594. assert( pgsz>0 );
  121595. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  121596. Fts3SegReader *pReader = pMsr->apSegment[ii];
  121597. if( !fts3SegReaderIsPending(pReader)
  121598. && !fts3SegReaderIsRootOnly(pReader)
  121599. ){
  121600. sqlite3_int64 jj;
  121601. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  121602. int nBlob;
  121603. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  121604. if( rc!=SQLITE_OK ) break;
  121605. if( (nBlob+35)>pgsz ){
  121606. nOvfl += (nBlob + 34)/pgsz;
  121607. }
  121608. }
  121609. }
  121610. }
  121611. *pnOvfl = nOvfl;
  121612. return rc;
  121613. }
  121614. /*
  121615. ** Free all allocations associated with the iterator passed as the
  121616. ** second argument.
  121617. */
  121618. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  121619. if( pReader && !fts3SegReaderIsPending(pReader) ){
  121620. sqlite3_free(pReader->zTerm);
  121621. if( !fts3SegReaderIsRootOnly(pReader) ){
  121622. sqlite3_free(pReader->aNode);
  121623. sqlite3_blob_close(pReader->pBlob);
  121624. }
  121625. }
  121626. sqlite3_free(pReader);
  121627. }
  121628. /*
  121629. ** Allocate a new SegReader object.
  121630. */
  121631. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  121632. int iAge, /* Segment "age". */
  121633. int bLookup, /* True for a lookup only */
  121634. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  121635. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  121636. sqlite3_int64 iEndBlock, /* Final block of segment */
  121637. const char *zRoot, /* Buffer containing root node */
  121638. int nRoot, /* Size of buffer containing root node */
  121639. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  121640. ){
  121641. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  121642. int nExtra = 0; /* Bytes to allocate segment root node */
  121643. assert( iStartLeaf<=iEndLeaf );
  121644. if( iStartLeaf==0 ){
  121645. nExtra = nRoot + FTS3_NODE_PADDING;
  121646. }
  121647. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  121648. if( !pReader ){
  121649. return SQLITE_NOMEM;
  121650. }
  121651. memset(pReader, 0, sizeof(Fts3SegReader));
  121652. pReader->iIdx = iAge;
  121653. pReader->bLookup = bLookup!=0;
  121654. pReader->iStartBlock = iStartLeaf;
  121655. pReader->iLeafEndBlock = iEndLeaf;
  121656. pReader->iEndBlock = iEndBlock;
  121657. if( nExtra ){
  121658. /* The entire segment is stored in the root node. */
  121659. pReader->aNode = (char *)&pReader[1];
  121660. pReader->rootOnly = 1;
  121661. pReader->nNode = nRoot;
  121662. memcpy(pReader->aNode, zRoot, nRoot);
  121663. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  121664. }else{
  121665. pReader->iCurrentBlock = iStartLeaf-1;
  121666. }
  121667. *ppReader = pReader;
  121668. return SQLITE_OK;
  121669. }
  121670. /*
  121671. ** This is a comparison function used as a qsort() callback when sorting
  121672. ** an array of pending terms by term. This occurs as part of flushing
  121673. ** the contents of the pending-terms hash table to the database.
  121674. */
  121675. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  121676. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  121677. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  121678. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  121679. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  121680. int n = (n1<n2 ? n1 : n2);
  121681. int c = memcmp(z1, z2, n);
  121682. if( c==0 ){
  121683. c = n1 - n2;
  121684. }
  121685. return c;
  121686. }
  121687. /*
  121688. ** This function is used to allocate an Fts3SegReader that iterates through
  121689. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  121690. **
  121691. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  121692. ** through each term in the pending-terms table. Or, if isPrefixIter is
  121693. ** non-zero, it iterates through each term and its prefixes. For example, if
  121694. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  121695. ** "firebird", then the iterator visits the following 'terms' (in the order
  121696. ** shown):
  121697. **
  121698. ** f fi fir fire fireb firebi firebir firebird
  121699. ** m my mys mysq mysql
  121700. ** s sq sql sqli sqlit sqlite
  121701. **
  121702. ** Whereas if isPrefixIter is zero, the terms visited are:
  121703. **
  121704. ** firebird mysql sqlite
  121705. */
  121706. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  121707. Fts3Table *p, /* Virtual table handle */
  121708. int iIndex, /* Index for p->aIndex */
  121709. const char *zTerm, /* Term to search for */
  121710. int nTerm, /* Size of buffer zTerm */
  121711. int bPrefix, /* True for a prefix iterator */
  121712. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  121713. ){
  121714. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  121715. Fts3HashElem *pE; /* Iterator variable */
  121716. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  121717. int nElem = 0; /* Size of array at aElem */
  121718. int rc = SQLITE_OK; /* Return Code */
  121719. Fts3Hash *pHash;
  121720. pHash = &p->aIndex[iIndex].hPending;
  121721. if( bPrefix ){
  121722. int nAlloc = 0; /* Size of allocated array at aElem */
  121723. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  121724. char *zKey = (char *)fts3HashKey(pE);
  121725. int nKey = fts3HashKeysize(pE);
  121726. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  121727. if( nElem==nAlloc ){
  121728. Fts3HashElem **aElem2;
  121729. nAlloc += 16;
  121730. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  121731. aElem, nAlloc*sizeof(Fts3HashElem *)
  121732. );
  121733. if( !aElem2 ){
  121734. rc = SQLITE_NOMEM;
  121735. nElem = 0;
  121736. break;
  121737. }
  121738. aElem = aElem2;
  121739. }
  121740. aElem[nElem++] = pE;
  121741. }
  121742. }
  121743. /* If more than one term matches the prefix, sort the Fts3HashElem
  121744. ** objects in term order using qsort(). This uses the same comparison
  121745. ** callback as is used when flushing terms to disk.
  121746. */
  121747. if( nElem>1 ){
  121748. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  121749. }
  121750. }else{
  121751. /* The query is a simple term lookup that matches at most one term in
  121752. ** the index. All that is required is a straight hash-lookup.
  121753. **
  121754. ** Because the stack address of pE may be accessed via the aElem pointer
  121755. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  121756. ** within this entire function, not just this "else{...}" block.
  121757. */
  121758. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  121759. if( pE ){
  121760. aElem = &pE;
  121761. nElem = 1;
  121762. }
  121763. }
  121764. if( nElem>0 ){
  121765. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  121766. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  121767. if( !pReader ){
  121768. rc = SQLITE_NOMEM;
  121769. }else{
  121770. memset(pReader, 0, nByte);
  121771. pReader->iIdx = 0x7FFFFFFF;
  121772. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  121773. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  121774. }
  121775. }
  121776. if( bPrefix ){
  121777. sqlite3_free(aElem);
  121778. }
  121779. *ppReader = pReader;
  121780. return rc;
  121781. }
  121782. /*
  121783. ** Compare the entries pointed to by two Fts3SegReader structures.
  121784. ** Comparison is as follows:
  121785. **
  121786. ** 1) EOF is greater than not EOF.
  121787. **
  121788. ** 2) The current terms (if any) are compared using memcmp(). If one
  121789. ** term is a prefix of another, the longer term is considered the
  121790. ** larger.
  121791. **
  121792. ** 3) By segment age. An older segment is considered larger.
  121793. */
  121794. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  121795. int rc;
  121796. if( pLhs->aNode && pRhs->aNode ){
  121797. int rc2 = pLhs->nTerm - pRhs->nTerm;
  121798. if( rc2<0 ){
  121799. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  121800. }else{
  121801. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  121802. }
  121803. if( rc==0 ){
  121804. rc = rc2;
  121805. }
  121806. }else{
  121807. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  121808. }
  121809. if( rc==0 ){
  121810. rc = pRhs->iIdx - pLhs->iIdx;
  121811. }
  121812. assert( rc!=0 );
  121813. return rc;
  121814. }
  121815. /*
  121816. ** A different comparison function for SegReader structures. In this
  121817. ** version, it is assumed that each SegReader points to an entry in
  121818. ** a doclist for identical terms. Comparison is made as follows:
  121819. **
  121820. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  121821. **
  121822. ** 2) By current docid.
  121823. **
  121824. ** 3) By segment age. An older segment is considered larger.
  121825. */
  121826. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  121827. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  121828. if( rc==0 ){
  121829. if( pLhs->iDocid==pRhs->iDocid ){
  121830. rc = pRhs->iIdx - pLhs->iIdx;
  121831. }else{
  121832. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  121833. }
  121834. }
  121835. assert( pLhs->aNode && pRhs->aNode );
  121836. return rc;
  121837. }
  121838. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  121839. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  121840. if( rc==0 ){
  121841. if( pLhs->iDocid==pRhs->iDocid ){
  121842. rc = pRhs->iIdx - pLhs->iIdx;
  121843. }else{
  121844. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  121845. }
  121846. }
  121847. assert( pLhs->aNode && pRhs->aNode );
  121848. return rc;
  121849. }
  121850. /*
  121851. ** Compare the term that the Fts3SegReader object passed as the first argument
  121852. ** points to with the term specified by arguments zTerm and nTerm.
  121853. **
  121854. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  121855. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  121856. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  121857. */
  121858. static int fts3SegReaderTermCmp(
  121859. Fts3SegReader *pSeg, /* Segment reader object */
  121860. const char *zTerm, /* Term to compare to */
  121861. int nTerm /* Size of term zTerm in bytes */
  121862. ){
  121863. int res = 0;
  121864. if( pSeg->aNode ){
  121865. if( pSeg->nTerm>nTerm ){
  121866. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  121867. }else{
  121868. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  121869. }
  121870. if( res==0 ){
  121871. res = pSeg->nTerm-nTerm;
  121872. }
  121873. }
  121874. return res;
  121875. }
  121876. /*
  121877. ** Argument apSegment is an array of nSegment elements. It is known that
  121878. ** the final (nSegment-nSuspect) members are already in sorted order
  121879. ** (according to the comparison function provided). This function shuffles
  121880. ** the array around until all entries are in sorted order.
  121881. */
  121882. static void fts3SegReaderSort(
  121883. Fts3SegReader **apSegment, /* Array to sort entries of */
  121884. int nSegment, /* Size of apSegment array */
  121885. int nSuspect, /* Unsorted entry count */
  121886. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  121887. ){
  121888. int i; /* Iterator variable */
  121889. assert( nSuspect<=nSegment );
  121890. if( nSuspect==nSegment ) nSuspect--;
  121891. for(i=nSuspect-1; i>=0; i--){
  121892. int j;
  121893. for(j=i; j<(nSegment-1); j++){
  121894. Fts3SegReader *pTmp;
  121895. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  121896. pTmp = apSegment[j+1];
  121897. apSegment[j+1] = apSegment[j];
  121898. apSegment[j] = pTmp;
  121899. }
  121900. }
  121901. #ifndef NDEBUG
  121902. /* Check that the list really is sorted now. */
  121903. for(i=0; i<(nSuspect-1); i++){
  121904. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  121905. }
  121906. #endif
  121907. }
  121908. /*
  121909. ** Insert a record into the %_segments table.
  121910. */
  121911. static int fts3WriteSegment(
  121912. Fts3Table *p, /* Virtual table handle */
  121913. sqlite3_int64 iBlock, /* Block id for new block */
  121914. char *z, /* Pointer to buffer containing block data */
  121915. int n /* Size of buffer z in bytes */
  121916. ){
  121917. sqlite3_stmt *pStmt;
  121918. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  121919. if( rc==SQLITE_OK ){
  121920. sqlite3_bind_int64(pStmt, 1, iBlock);
  121921. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  121922. sqlite3_step(pStmt);
  121923. rc = sqlite3_reset(pStmt);
  121924. }
  121925. return rc;
  121926. }
  121927. /*
  121928. ** Find the largest relative level number in the table. If successful, set
  121929. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  121930. ** set *pnMax to zero and return an SQLite error code.
  121931. */
  121932. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  121933. int rc;
  121934. int mxLevel = 0;
  121935. sqlite3_stmt *pStmt = 0;
  121936. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  121937. if( rc==SQLITE_OK ){
  121938. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  121939. mxLevel = sqlite3_column_int(pStmt, 0);
  121940. }
  121941. rc = sqlite3_reset(pStmt);
  121942. }
  121943. *pnMax = mxLevel;
  121944. return rc;
  121945. }
  121946. /*
  121947. ** Insert a record into the %_segdir table.
  121948. */
  121949. static int fts3WriteSegdir(
  121950. Fts3Table *p, /* Virtual table handle */
  121951. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  121952. int iIdx, /* Value for "idx" field */
  121953. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  121954. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  121955. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  121956. char *zRoot, /* Blob value for "root" field */
  121957. int nRoot /* Number of bytes in buffer zRoot */
  121958. ){
  121959. sqlite3_stmt *pStmt;
  121960. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  121961. if( rc==SQLITE_OK ){
  121962. sqlite3_bind_int64(pStmt, 1, iLevel);
  121963. sqlite3_bind_int(pStmt, 2, iIdx);
  121964. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  121965. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  121966. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  121967. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  121968. sqlite3_step(pStmt);
  121969. rc = sqlite3_reset(pStmt);
  121970. }
  121971. return rc;
  121972. }
  121973. /*
  121974. ** Return the size of the common prefix (if any) shared by zPrev and
  121975. ** zNext, in bytes. For example,
  121976. **
  121977. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  121978. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  121979. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  121980. */
  121981. static int fts3PrefixCompress(
  121982. const char *zPrev, /* Buffer containing previous term */
  121983. int nPrev, /* Size of buffer zPrev in bytes */
  121984. const char *zNext, /* Buffer containing next term */
  121985. int nNext /* Size of buffer zNext in bytes */
  121986. ){
  121987. int n;
  121988. UNUSED_PARAMETER(nNext);
  121989. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  121990. return n;
  121991. }
  121992. /*
  121993. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  121994. ** (according to memcmp) than the previous term.
  121995. */
  121996. static int fts3NodeAddTerm(
  121997. Fts3Table *p, /* Virtual table handle */
  121998. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  121999. int isCopyTerm, /* True if zTerm/nTerm is transient */
  122000. const char *zTerm, /* Pointer to buffer containing term */
  122001. int nTerm /* Size of term in bytes */
  122002. ){
  122003. SegmentNode *pTree = *ppTree;
  122004. int rc;
  122005. SegmentNode *pNew;
  122006. /* First try to append the term to the current node. Return early if
  122007. ** this is possible.
  122008. */
  122009. if( pTree ){
  122010. int nData = pTree->nData; /* Current size of node in bytes */
  122011. int nReq = nData; /* Required space after adding zTerm */
  122012. int nPrefix; /* Number of bytes of prefix compression */
  122013. int nSuffix; /* Suffix length */
  122014. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  122015. nSuffix = nTerm-nPrefix;
  122016. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  122017. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  122018. if( nReq>p->nNodeSize ){
  122019. /* An unusual case: this is the first term to be added to the node
  122020. ** and the static node buffer (p->nNodeSize bytes) is not large
  122021. ** enough. Use a separately malloced buffer instead This wastes
  122022. ** p->nNodeSize bytes, but since this scenario only comes about when
  122023. ** the database contain two terms that share a prefix of almost 2KB,
  122024. ** this is not expected to be a serious problem.
  122025. */
  122026. assert( pTree->aData==(char *)&pTree[1] );
  122027. pTree->aData = (char *)sqlite3_malloc(nReq);
  122028. if( !pTree->aData ){
  122029. return SQLITE_NOMEM;
  122030. }
  122031. }
  122032. if( pTree->zTerm ){
  122033. /* There is no prefix-length field for first term in a node */
  122034. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  122035. }
  122036. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  122037. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  122038. pTree->nData = nData + nSuffix;
  122039. pTree->nEntry++;
  122040. if( isCopyTerm ){
  122041. if( pTree->nMalloc<nTerm ){
  122042. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  122043. if( !zNew ){
  122044. return SQLITE_NOMEM;
  122045. }
  122046. pTree->nMalloc = nTerm*2;
  122047. pTree->zMalloc = zNew;
  122048. }
  122049. pTree->zTerm = pTree->zMalloc;
  122050. memcpy(pTree->zTerm, zTerm, nTerm);
  122051. pTree->nTerm = nTerm;
  122052. }else{
  122053. pTree->zTerm = (char *)zTerm;
  122054. pTree->nTerm = nTerm;
  122055. }
  122056. return SQLITE_OK;
  122057. }
  122058. }
  122059. /* If control flows to here, it was not possible to append zTerm to the
  122060. ** current node. Create a new node (a right-sibling of the current node).
  122061. ** If this is the first node in the tree, the term is added to it.
  122062. **
  122063. ** Otherwise, the term is not added to the new node, it is left empty for
  122064. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  122065. ** has no parent, one is created here.
  122066. */
  122067. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  122068. if( !pNew ){
  122069. return SQLITE_NOMEM;
  122070. }
  122071. memset(pNew, 0, sizeof(SegmentNode));
  122072. pNew->nData = 1 + FTS3_VARINT_MAX;
  122073. pNew->aData = (char *)&pNew[1];
  122074. if( pTree ){
  122075. SegmentNode *pParent = pTree->pParent;
  122076. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  122077. if( pTree->pParent==0 ){
  122078. pTree->pParent = pParent;
  122079. }
  122080. pTree->pRight = pNew;
  122081. pNew->pLeftmost = pTree->pLeftmost;
  122082. pNew->pParent = pParent;
  122083. pNew->zMalloc = pTree->zMalloc;
  122084. pNew->nMalloc = pTree->nMalloc;
  122085. pTree->zMalloc = 0;
  122086. }else{
  122087. pNew->pLeftmost = pNew;
  122088. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  122089. }
  122090. *ppTree = pNew;
  122091. return rc;
  122092. }
  122093. /*
  122094. ** Helper function for fts3NodeWrite().
  122095. */
  122096. static int fts3TreeFinishNode(
  122097. SegmentNode *pTree,
  122098. int iHeight,
  122099. sqlite3_int64 iLeftChild
  122100. ){
  122101. int nStart;
  122102. assert( iHeight>=1 && iHeight<128 );
  122103. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  122104. pTree->aData[nStart] = (char)iHeight;
  122105. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  122106. return nStart;
  122107. }
  122108. /*
  122109. ** Write the buffer for the segment node pTree and all of its peers to the
  122110. ** database. Then call this function recursively to write the parent of
  122111. ** pTree and its peers to the database.
  122112. **
  122113. ** Except, if pTree is a root node, do not write it to the database. Instead,
  122114. ** set output variables *paRoot and *pnRoot to contain the root node.
  122115. **
  122116. ** If successful, SQLITE_OK is returned and output variable *piLast is
  122117. ** set to the largest blockid written to the database (or zero if no
  122118. ** blocks were written to the db). Otherwise, an SQLite error code is
  122119. ** returned.
  122120. */
  122121. static int fts3NodeWrite(
  122122. Fts3Table *p, /* Virtual table handle */
  122123. SegmentNode *pTree, /* SegmentNode handle */
  122124. int iHeight, /* Height of this node in tree */
  122125. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  122126. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  122127. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  122128. char **paRoot, /* OUT: Data for root node */
  122129. int *pnRoot /* OUT: Size of root node in bytes */
  122130. ){
  122131. int rc = SQLITE_OK;
  122132. if( !pTree->pParent ){
  122133. /* Root node of the tree. */
  122134. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  122135. *piLast = iFree-1;
  122136. *pnRoot = pTree->nData - nStart;
  122137. *paRoot = &pTree->aData[nStart];
  122138. }else{
  122139. SegmentNode *pIter;
  122140. sqlite3_int64 iNextFree = iFree;
  122141. sqlite3_int64 iNextLeaf = iLeaf;
  122142. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  122143. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  122144. int nWrite = pIter->nData - nStart;
  122145. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  122146. iNextFree++;
  122147. iNextLeaf += (pIter->nEntry+1);
  122148. }
  122149. if( rc==SQLITE_OK ){
  122150. assert( iNextLeaf==iFree );
  122151. rc = fts3NodeWrite(
  122152. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  122153. );
  122154. }
  122155. }
  122156. return rc;
  122157. }
  122158. /*
  122159. ** Free all memory allocations associated with the tree pTree.
  122160. */
  122161. static void fts3NodeFree(SegmentNode *pTree){
  122162. if( pTree ){
  122163. SegmentNode *p = pTree->pLeftmost;
  122164. fts3NodeFree(p->pParent);
  122165. while( p ){
  122166. SegmentNode *pRight = p->pRight;
  122167. if( p->aData!=(char *)&p[1] ){
  122168. sqlite3_free(p->aData);
  122169. }
  122170. assert( pRight==0 || p->zMalloc==0 );
  122171. sqlite3_free(p->zMalloc);
  122172. sqlite3_free(p);
  122173. p = pRight;
  122174. }
  122175. }
  122176. }
  122177. /*
  122178. ** Add a term to the segment being constructed by the SegmentWriter object
  122179. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  122180. ** be passed NULL. This function will allocate a new SegmentWriter object
  122181. ** and return it via the input/output variable *ppWriter in this case.
  122182. **
  122183. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  122184. */
  122185. static int fts3SegWriterAdd(
  122186. Fts3Table *p, /* Virtual table handle */
  122187. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  122188. int isCopyTerm, /* True if buffer zTerm must be copied */
  122189. const char *zTerm, /* Pointer to buffer containing term */
  122190. int nTerm, /* Size of term in bytes */
  122191. const char *aDoclist, /* Pointer to buffer containing doclist */
  122192. int nDoclist /* Size of doclist in bytes */
  122193. ){
  122194. int nPrefix; /* Size of term prefix in bytes */
  122195. int nSuffix; /* Size of term suffix in bytes */
  122196. int nReq; /* Number of bytes required on leaf page */
  122197. int nData;
  122198. SegmentWriter *pWriter = *ppWriter;
  122199. if( !pWriter ){
  122200. int rc;
  122201. sqlite3_stmt *pStmt;
  122202. /* Allocate the SegmentWriter structure */
  122203. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  122204. if( !pWriter ) return SQLITE_NOMEM;
  122205. memset(pWriter, 0, sizeof(SegmentWriter));
  122206. *ppWriter = pWriter;
  122207. /* Allocate a buffer in which to accumulate data */
  122208. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  122209. if( !pWriter->aData ) return SQLITE_NOMEM;
  122210. pWriter->nSize = p->nNodeSize;
  122211. /* Find the next free blockid in the %_segments table */
  122212. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  122213. if( rc!=SQLITE_OK ) return rc;
  122214. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  122215. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  122216. pWriter->iFirst = pWriter->iFree;
  122217. }
  122218. rc = sqlite3_reset(pStmt);
  122219. if( rc!=SQLITE_OK ) return rc;
  122220. }
  122221. nData = pWriter->nData;
  122222. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  122223. nSuffix = nTerm-nPrefix;
  122224. /* Figure out how many bytes are required by this new entry */
  122225. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  122226. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  122227. nSuffix + /* Term suffix */
  122228. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  122229. nDoclist; /* Doclist data */
  122230. if( nData>0 && nData+nReq>p->nNodeSize ){
  122231. int rc;
  122232. /* The current leaf node is full. Write it out to the database. */
  122233. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  122234. if( rc!=SQLITE_OK ) return rc;
  122235. p->nLeafAdd++;
  122236. /* Add the current term to the interior node tree. The term added to
  122237. ** the interior tree must:
  122238. **
  122239. ** a) be greater than the largest term on the leaf node just written
  122240. ** to the database (still available in pWriter->zTerm), and
  122241. **
  122242. ** b) be less than or equal to the term about to be added to the new
  122243. ** leaf node (zTerm/nTerm).
  122244. **
  122245. ** In other words, it must be the prefix of zTerm 1 byte longer than
  122246. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  122247. */
  122248. assert( nPrefix<nTerm );
  122249. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  122250. if( rc!=SQLITE_OK ) return rc;
  122251. nData = 0;
  122252. pWriter->nTerm = 0;
  122253. nPrefix = 0;
  122254. nSuffix = nTerm;
  122255. nReq = 1 + /* varint containing prefix size */
  122256. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  122257. nTerm + /* Term suffix */
  122258. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  122259. nDoclist; /* Doclist data */
  122260. }
  122261. /* If the buffer currently allocated is too small for this entry, realloc
  122262. ** the buffer to make it large enough.
  122263. */
  122264. if( nReq>pWriter->nSize ){
  122265. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  122266. if( !aNew ) return SQLITE_NOMEM;
  122267. pWriter->aData = aNew;
  122268. pWriter->nSize = nReq;
  122269. }
  122270. assert( nData+nReq<=pWriter->nSize );
  122271. /* Append the prefix-compressed term and doclist to the buffer. */
  122272. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  122273. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  122274. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  122275. nData += nSuffix;
  122276. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  122277. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  122278. pWriter->nData = nData + nDoclist;
  122279. /* Save the current term so that it can be used to prefix-compress the next.
  122280. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  122281. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  122282. ** store a copy of the pointer.
  122283. */
  122284. if( isCopyTerm ){
  122285. if( nTerm>pWriter->nMalloc ){
  122286. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  122287. if( !zNew ){
  122288. return SQLITE_NOMEM;
  122289. }
  122290. pWriter->nMalloc = nTerm*2;
  122291. pWriter->zMalloc = zNew;
  122292. pWriter->zTerm = zNew;
  122293. }
  122294. assert( pWriter->zTerm==pWriter->zMalloc );
  122295. memcpy(pWriter->zTerm, zTerm, nTerm);
  122296. }else{
  122297. pWriter->zTerm = (char *)zTerm;
  122298. }
  122299. pWriter->nTerm = nTerm;
  122300. return SQLITE_OK;
  122301. }
  122302. /*
  122303. ** Flush all data associated with the SegmentWriter object pWriter to the
  122304. ** database. This function must be called after all terms have been added
  122305. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  122306. ** returned. Otherwise, an SQLite error code.
  122307. */
  122308. static int fts3SegWriterFlush(
  122309. Fts3Table *p, /* Virtual table handle */
  122310. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  122311. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  122312. int iIdx /* Value for 'idx' column of %_segdir */
  122313. ){
  122314. int rc; /* Return code */
  122315. if( pWriter->pTree ){
  122316. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  122317. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  122318. char *zRoot = NULL; /* Pointer to buffer containing root node */
  122319. int nRoot = 0; /* Size of buffer zRoot */
  122320. iLastLeaf = pWriter->iFree;
  122321. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  122322. if( rc==SQLITE_OK ){
  122323. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  122324. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  122325. }
  122326. if( rc==SQLITE_OK ){
  122327. rc = fts3WriteSegdir(
  122328. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  122329. }
  122330. }else{
  122331. /* The entire tree fits on the root node. Write it to the segdir table. */
  122332. rc = fts3WriteSegdir(
  122333. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  122334. }
  122335. p->nLeafAdd++;
  122336. return rc;
  122337. }
  122338. /*
  122339. ** Release all memory held by the SegmentWriter object passed as the
  122340. ** first argument.
  122341. */
  122342. static void fts3SegWriterFree(SegmentWriter *pWriter){
  122343. if( pWriter ){
  122344. sqlite3_free(pWriter->aData);
  122345. sqlite3_free(pWriter->zMalloc);
  122346. fts3NodeFree(pWriter->pTree);
  122347. sqlite3_free(pWriter);
  122348. }
  122349. }
  122350. /*
  122351. ** The first value in the apVal[] array is assumed to contain an integer.
  122352. ** This function tests if there exist any documents with docid values that
  122353. ** are different from that integer. i.e. if deleting the document with docid
  122354. ** pRowid would mean the FTS3 table were empty.
  122355. **
  122356. ** If successful, *pisEmpty is set to true if the table is empty except for
  122357. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  122358. ** error occurs, an SQLite error code is returned.
  122359. */
  122360. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  122361. sqlite3_stmt *pStmt;
  122362. int rc;
  122363. if( p->zContentTbl ){
  122364. /* If using the content=xxx option, assume the table is never empty */
  122365. *pisEmpty = 0;
  122366. rc = SQLITE_OK;
  122367. }else{
  122368. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  122369. if( rc==SQLITE_OK ){
  122370. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  122371. *pisEmpty = sqlite3_column_int(pStmt, 0);
  122372. }
  122373. rc = sqlite3_reset(pStmt);
  122374. }
  122375. }
  122376. return rc;
  122377. }
  122378. /*
  122379. ** Set *pnMax to the largest segment level in the database for the index
  122380. ** iIndex.
  122381. **
  122382. ** Segment levels are stored in the 'level' column of the %_segdir table.
  122383. **
  122384. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  122385. */
  122386. static int fts3SegmentMaxLevel(
  122387. Fts3Table *p,
  122388. int iLangid,
  122389. int iIndex,
  122390. sqlite3_int64 *pnMax
  122391. ){
  122392. sqlite3_stmt *pStmt;
  122393. int rc;
  122394. assert( iIndex>=0 && iIndex<p->nIndex );
  122395. /* Set pStmt to the compiled version of:
  122396. **
  122397. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  122398. **
  122399. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  122400. */
  122401. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  122402. if( rc!=SQLITE_OK ) return rc;
  122403. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  122404. sqlite3_bind_int64(pStmt, 2,
  122405. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  122406. );
  122407. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  122408. *pnMax = sqlite3_column_int64(pStmt, 0);
  122409. }
  122410. return sqlite3_reset(pStmt);
  122411. }
  122412. /*
  122413. ** Delete all entries in the %_segments table associated with the segment
  122414. ** opened with seg-reader pSeg. This function does not affect the contents
  122415. ** of the %_segdir table.
  122416. */
  122417. static int fts3DeleteSegment(
  122418. Fts3Table *p, /* FTS table handle */
  122419. Fts3SegReader *pSeg /* Segment to delete */
  122420. ){
  122421. int rc = SQLITE_OK; /* Return code */
  122422. if( pSeg->iStartBlock ){
  122423. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  122424. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  122425. if( rc==SQLITE_OK ){
  122426. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  122427. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  122428. sqlite3_step(pDelete);
  122429. rc = sqlite3_reset(pDelete);
  122430. }
  122431. }
  122432. return rc;
  122433. }
  122434. /*
  122435. ** This function is used after merging multiple segments into a single large
  122436. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  122437. ** it:
  122438. **
  122439. ** 1) Deletes all %_segments entries for the segments associated with
  122440. ** each of the SegReader objects in the array passed as the third
  122441. ** argument, and
  122442. **
  122443. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  122444. ** entries regardless of level if (iLevel<0).
  122445. **
  122446. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  122447. */
  122448. static int fts3DeleteSegdir(
  122449. Fts3Table *p, /* Virtual table handle */
  122450. int iLangid, /* Language id */
  122451. int iIndex, /* Index for p->aIndex */
  122452. int iLevel, /* Level of %_segdir entries to delete */
  122453. Fts3SegReader **apSegment, /* Array of SegReader objects */
  122454. int nReader /* Size of array apSegment */
  122455. ){
  122456. int rc = SQLITE_OK; /* Return Code */
  122457. int i; /* Iterator variable */
  122458. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  122459. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  122460. rc = fts3DeleteSegment(p, apSegment[i]);
  122461. }
  122462. if( rc!=SQLITE_OK ){
  122463. return rc;
  122464. }
  122465. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  122466. if( iLevel==FTS3_SEGCURSOR_ALL ){
  122467. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  122468. if( rc==SQLITE_OK ){
  122469. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  122470. sqlite3_bind_int64(pDelete, 2,
  122471. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  122472. );
  122473. }
  122474. }else{
  122475. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  122476. if( rc==SQLITE_OK ){
  122477. sqlite3_bind_int64(
  122478. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  122479. );
  122480. }
  122481. }
  122482. if( rc==SQLITE_OK ){
  122483. sqlite3_step(pDelete);
  122484. rc = sqlite3_reset(pDelete);
  122485. }
  122486. return rc;
  122487. }
  122488. /*
  122489. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  122490. ** a position list that may (or may not) feature multiple columns. This
  122491. ** function adjusts the pointer *ppList and the length *pnList so that they
  122492. ** identify the subset of the position list that corresponds to column iCol.
  122493. **
  122494. ** If there are no entries in the input position list for column iCol, then
  122495. ** *pnList is set to zero before returning.
  122496. **
  122497. ** If parameter bZero is non-zero, then any part of the input list following
  122498. ** the end of the output list is zeroed before returning.
  122499. */
  122500. static void fts3ColumnFilter(
  122501. int iCol, /* Column to filter on */
  122502. int bZero, /* Zero out anything following *ppList */
  122503. char **ppList, /* IN/OUT: Pointer to position list */
  122504. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  122505. ){
  122506. char *pList = *ppList;
  122507. int nList = *pnList;
  122508. char *pEnd = &pList[nList];
  122509. int iCurrent = 0;
  122510. char *p = pList;
  122511. assert( iCol>=0 );
  122512. while( 1 ){
  122513. char c = 0;
  122514. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  122515. if( iCol==iCurrent ){
  122516. nList = (int)(p - pList);
  122517. break;
  122518. }
  122519. nList -= (int)(p - pList);
  122520. pList = p;
  122521. if( nList==0 ){
  122522. break;
  122523. }
  122524. p = &pList[1];
  122525. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  122526. }
  122527. if( bZero && &pList[nList]!=pEnd ){
  122528. memset(&pList[nList], 0, pEnd - &pList[nList]);
  122529. }
  122530. *ppList = pList;
  122531. *pnList = nList;
  122532. }
  122533. /*
  122534. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  122535. ** existing data). Grow the buffer if required.
  122536. **
  122537. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  122538. ** trying to resize the buffer, return SQLITE_NOMEM.
  122539. */
  122540. static int fts3MsrBufferData(
  122541. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  122542. char *pList,
  122543. int nList
  122544. ){
  122545. if( nList>pMsr->nBuffer ){
  122546. char *pNew;
  122547. pMsr->nBuffer = nList*2;
  122548. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  122549. if( !pNew ) return SQLITE_NOMEM;
  122550. pMsr->aBuffer = pNew;
  122551. }
  122552. memcpy(pMsr->aBuffer, pList, nList);
  122553. return SQLITE_OK;
  122554. }
  122555. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  122556. Fts3Table *p, /* Virtual table handle */
  122557. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  122558. sqlite3_int64 *piDocid, /* OUT: Docid value */
  122559. char **paPoslist, /* OUT: Pointer to position list */
  122560. int *pnPoslist /* OUT: Size of position list in bytes */
  122561. ){
  122562. int nMerge = pMsr->nAdvance;
  122563. Fts3SegReader **apSegment = pMsr->apSegment;
  122564. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  122565. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  122566. );
  122567. if( nMerge==0 ){
  122568. *paPoslist = 0;
  122569. return SQLITE_OK;
  122570. }
  122571. while( 1 ){
  122572. Fts3SegReader *pSeg;
  122573. pSeg = pMsr->apSegment[0];
  122574. if( pSeg->pOffsetList==0 ){
  122575. *paPoslist = 0;
  122576. break;
  122577. }else{
  122578. int rc;
  122579. char *pList;
  122580. int nList;
  122581. int j;
  122582. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  122583. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  122584. j = 1;
  122585. while( rc==SQLITE_OK
  122586. && j<nMerge
  122587. && apSegment[j]->pOffsetList
  122588. && apSegment[j]->iDocid==iDocid
  122589. ){
  122590. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  122591. j++;
  122592. }
  122593. if( rc!=SQLITE_OK ) return rc;
  122594. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  122595. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  122596. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  122597. if( rc!=SQLITE_OK ) return rc;
  122598. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  122599. pList = pMsr->aBuffer;
  122600. }
  122601. if( pMsr->iColFilter>=0 ){
  122602. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  122603. }
  122604. if( nList>0 ){
  122605. *paPoslist = pList;
  122606. *piDocid = iDocid;
  122607. *pnPoslist = nList;
  122608. break;
  122609. }
  122610. }
  122611. }
  122612. return SQLITE_OK;
  122613. }
  122614. static int fts3SegReaderStart(
  122615. Fts3Table *p, /* Virtual table handle */
  122616. Fts3MultiSegReader *pCsr, /* Cursor object */
  122617. const char *zTerm, /* Term searched for (or NULL) */
  122618. int nTerm /* Length of zTerm in bytes */
  122619. ){
  122620. int i;
  122621. int nSeg = pCsr->nSegment;
  122622. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  122623. ** for, then advance each segment iterator until it points to a term of
  122624. ** equal or greater value than the specified term. This prevents many
  122625. ** unnecessary merge/sort operations for the case where single segment
  122626. ** b-tree leaf nodes contain more than one term.
  122627. */
  122628. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  122629. int res = 0;
  122630. Fts3SegReader *pSeg = pCsr->apSegment[i];
  122631. do {
  122632. int rc = fts3SegReaderNext(p, pSeg, 0);
  122633. if( rc!=SQLITE_OK ) return rc;
  122634. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  122635. if( pSeg->bLookup && res!=0 ){
  122636. fts3SegReaderSetEof(pSeg);
  122637. }
  122638. }
  122639. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  122640. return SQLITE_OK;
  122641. }
  122642. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  122643. Fts3Table *p, /* Virtual table handle */
  122644. Fts3MultiSegReader *pCsr, /* Cursor object */
  122645. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  122646. ){
  122647. pCsr->pFilter = pFilter;
  122648. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  122649. }
  122650. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  122651. Fts3Table *p, /* Virtual table handle */
  122652. Fts3MultiSegReader *pCsr, /* Cursor object */
  122653. int iCol, /* Column to match on. */
  122654. const char *zTerm, /* Term to iterate through a doclist for */
  122655. int nTerm /* Number of bytes in zTerm */
  122656. ){
  122657. int i;
  122658. int rc;
  122659. int nSegment = pCsr->nSegment;
  122660. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  122661. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  122662. );
  122663. assert( pCsr->pFilter==0 );
  122664. assert( zTerm && nTerm>0 );
  122665. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  122666. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  122667. if( rc!=SQLITE_OK ) return rc;
  122668. /* Determine how many of the segments actually point to zTerm/nTerm. */
  122669. for(i=0; i<nSegment; i++){
  122670. Fts3SegReader *pSeg = pCsr->apSegment[i];
  122671. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  122672. break;
  122673. }
  122674. }
  122675. pCsr->nAdvance = i;
  122676. /* Advance each of the segments to point to the first docid. */
  122677. for(i=0; i<pCsr->nAdvance; i++){
  122678. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  122679. if( rc!=SQLITE_OK ) return rc;
  122680. }
  122681. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  122682. assert( iCol<0 || iCol<p->nColumn );
  122683. pCsr->iColFilter = iCol;
  122684. return SQLITE_OK;
  122685. }
  122686. /*
  122687. ** This function is called on a MultiSegReader that has been started using
  122688. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  122689. ** have been made. Calling this function puts the MultiSegReader in such
  122690. ** a state that if the next two calls are:
  122691. **
  122692. ** sqlite3Fts3SegReaderStart()
  122693. ** sqlite3Fts3SegReaderStep()
  122694. **
  122695. ** then the entire doclist for the term is available in
  122696. ** MultiSegReader.aDoclist/nDoclist.
  122697. */
  122698. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  122699. int i; /* Used to iterate through segment-readers */
  122700. assert( pCsr->zTerm==0 );
  122701. assert( pCsr->nTerm==0 );
  122702. assert( pCsr->aDoclist==0 );
  122703. assert( pCsr->nDoclist==0 );
  122704. pCsr->nAdvance = 0;
  122705. pCsr->bRestart = 1;
  122706. for(i=0; i<pCsr->nSegment; i++){
  122707. pCsr->apSegment[i]->pOffsetList = 0;
  122708. pCsr->apSegment[i]->nOffsetList = 0;
  122709. pCsr->apSegment[i]->iDocid = 0;
  122710. }
  122711. return SQLITE_OK;
  122712. }
  122713. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  122714. Fts3Table *p, /* Virtual table handle */
  122715. Fts3MultiSegReader *pCsr /* Cursor object */
  122716. ){
  122717. int rc = SQLITE_OK;
  122718. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  122719. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  122720. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  122721. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  122722. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  122723. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  122724. Fts3SegReader **apSegment = pCsr->apSegment;
  122725. int nSegment = pCsr->nSegment;
  122726. Fts3SegFilter *pFilter = pCsr->pFilter;
  122727. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  122728. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  122729. );
  122730. if( pCsr->nSegment==0 ) return SQLITE_OK;
  122731. do {
  122732. int nMerge;
  122733. int i;
  122734. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  122735. ** forward. Then sort the list in order of current term again.
  122736. */
  122737. for(i=0; i<pCsr->nAdvance; i++){
  122738. Fts3SegReader *pSeg = apSegment[i];
  122739. if( pSeg->bLookup ){
  122740. fts3SegReaderSetEof(pSeg);
  122741. }else{
  122742. rc = fts3SegReaderNext(p, pSeg, 0);
  122743. }
  122744. if( rc!=SQLITE_OK ) return rc;
  122745. }
  122746. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  122747. pCsr->nAdvance = 0;
  122748. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  122749. assert( rc==SQLITE_OK );
  122750. if( apSegment[0]->aNode==0 ) break;
  122751. pCsr->nTerm = apSegment[0]->nTerm;
  122752. pCsr->zTerm = apSegment[0]->zTerm;
  122753. /* If this is a prefix-search, and if the term that apSegment[0] points
  122754. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  122755. ** required callbacks have been made. In this case exit early.
  122756. **
  122757. ** Similarly, if this is a search for an exact match, and the first term
  122758. ** of segment apSegment[0] is not a match, exit early.
  122759. */
  122760. if( pFilter->zTerm && !isScan ){
  122761. if( pCsr->nTerm<pFilter->nTerm
  122762. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  122763. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  122764. ){
  122765. break;
  122766. }
  122767. }
  122768. nMerge = 1;
  122769. while( nMerge<nSegment
  122770. && apSegment[nMerge]->aNode
  122771. && apSegment[nMerge]->nTerm==pCsr->nTerm
  122772. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  122773. ){
  122774. nMerge++;
  122775. }
  122776. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  122777. if( nMerge==1
  122778. && !isIgnoreEmpty
  122779. && !isFirst
  122780. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  122781. ){
  122782. pCsr->nDoclist = apSegment[0]->nDoclist;
  122783. if( fts3SegReaderIsPending(apSegment[0]) ){
  122784. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  122785. pCsr->aDoclist = pCsr->aBuffer;
  122786. }else{
  122787. pCsr->aDoclist = apSegment[0]->aDoclist;
  122788. }
  122789. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  122790. }else{
  122791. int nDoclist = 0; /* Size of doclist */
  122792. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  122793. /* The current term of the first nMerge entries in the array
  122794. ** of Fts3SegReader objects is the same. The doclists must be merged
  122795. ** and a single term returned with the merged doclist.
  122796. */
  122797. for(i=0; i<nMerge; i++){
  122798. fts3SegReaderFirstDocid(p, apSegment[i]);
  122799. }
  122800. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  122801. while( apSegment[0]->pOffsetList ){
  122802. int j; /* Number of segments that share a docid */
  122803. char *pList;
  122804. int nList;
  122805. int nByte;
  122806. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  122807. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  122808. j = 1;
  122809. while( j<nMerge
  122810. && apSegment[j]->pOffsetList
  122811. && apSegment[j]->iDocid==iDocid
  122812. ){
  122813. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  122814. j++;
  122815. }
  122816. if( isColFilter ){
  122817. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  122818. }
  122819. if( !isIgnoreEmpty || nList>0 ){
  122820. /* Calculate the 'docid' delta value to write into the merged
  122821. ** doclist. */
  122822. sqlite3_int64 iDelta;
  122823. if( p->bDescIdx && nDoclist>0 ){
  122824. iDelta = iPrev - iDocid;
  122825. }else{
  122826. iDelta = iDocid - iPrev;
  122827. }
  122828. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  122829. assert( nDoclist>0 || iDelta==iDocid );
  122830. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  122831. if( nDoclist+nByte>pCsr->nBuffer ){
  122832. char *aNew;
  122833. pCsr->nBuffer = (nDoclist+nByte)*2;
  122834. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  122835. if( !aNew ){
  122836. return SQLITE_NOMEM;
  122837. }
  122838. pCsr->aBuffer = aNew;
  122839. }
  122840. if( isFirst ){
  122841. char *a = &pCsr->aBuffer[nDoclist];
  122842. int nWrite;
  122843. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  122844. if( nWrite ){
  122845. iPrev = iDocid;
  122846. nDoclist += nWrite;
  122847. }
  122848. }else{
  122849. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  122850. iPrev = iDocid;
  122851. if( isRequirePos ){
  122852. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  122853. nDoclist += nList;
  122854. pCsr->aBuffer[nDoclist++] = '\0';
  122855. }
  122856. }
  122857. }
  122858. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  122859. }
  122860. if( nDoclist>0 ){
  122861. pCsr->aDoclist = pCsr->aBuffer;
  122862. pCsr->nDoclist = nDoclist;
  122863. rc = SQLITE_ROW;
  122864. }
  122865. }
  122866. pCsr->nAdvance = nMerge;
  122867. }while( rc==SQLITE_OK );
  122868. return rc;
  122869. }
  122870. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  122871. Fts3MultiSegReader *pCsr /* Cursor object */
  122872. ){
  122873. if( pCsr ){
  122874. int i;
  122875. for(i=0; i<pCsr->nSegment; i++){
  122876. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  122877. }
  122878. sqlite3_free(pCsr->apSegment);
  122879. sqlite3_free(pCsr->aBuffer);
  122880. pCsr->nSegment = 0;
  122881. pCsr->apSegment = 0;
  122882. pCsr->aBuffer = 0;
  122883. }
  122884. }
  122885. /*
  122886. ** Merge all level iLevel segments in the database into a single
  122887. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  122888. ** single segment with a level equal to the numerically largest level
  122889. ** currently present in the database.
  122890. **
  122891. ** If this function is called with iLevel<0, but there is only one
  122892. ** segment in the database, SQLITE_DONE is returned immediately.
  122893. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  122894. ** an SQLite error code is returned.
  122895. */
  122896. static int fts3SegmentMerge(
  122897. Fts3Table *p,
  122898. int iLangid, /* Language id to merge */
  122899. int iIndex, /* Index in p->aIndex[] to merge */
  122900. int iLevel /* Level to merge */
  122901. ){
  122902. int rc; /* Return code */
  122903. int iIdx = 0; /* Index of new segment */
  122904. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  122905. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  122906. Fts3SegFilter filter; /* Segment term filter condition */
  122907. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  122908. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  122909. assert( iLevel==FTS3_SEGCURSOR_ALL
  122910. || iLevel==FTS3_SEGCURSOR_PENDING
  122911. || iLevel>=0
  122912. );
  122913. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  122914. assert( iIndex>=0 && iIndex<p->nIndex );
  122915. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  122916. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  122917. if( iLevel==FTS3_SEGCURSOR_ALL ){
  122918. /* This call is to merge all segments in the database to a single
  122919. ** segment. The level of the new segment is equal to the numerically
  122920. ** greatest segment level currently present in the database for this
  122921. ** index. The idx of the new segment is always 0. */
  122922. if( csr.nSegment==1 ){
  122923. rc = SQLITE_DONE;
  122924. goto finished;
  122925. }
  122926. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  122927. bIgnoreEmpty = 1;
  122928. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  122929. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  122930. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  122931. }else{
  122932. /* This call is to merge all segments at level iLevel. find the next
  122933. ** available segment index at level iLevel+1. The call to
  122934. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  122935. ** a single iLevel+2 segment if necessary. */
  122936. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  122937. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  122938. }
  122939. if( rc!=SQLITE_OK ) goto finished;
  122940. assert( csr.nSegment>0 );
  122941. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  122942. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  122943. memset(&filter, 0, sizeof(Fts3SegFilter));
  122944. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  122945. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  122946. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  122947. while( SQLITE_OK==rc ){
  122948. rc = sqlite3Fts3SegReaderStep(p, &csr);
  122949. if( rc!=SQLITE_ROW ) break;
  122950. rc = fts3SegWriterAdd(p, &pWriter, 1,
  122951. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  122952. }
  122953. if( rc!=SQLITE_OK ) goto finished;
  122954. assert( pWriter );
  122955. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  122956. rc = fts3DeleteSegdir(
  122957. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  122958. );
  122959. if( rc!=SQLITE_OK ) goto finished;
  122960. }
  122961. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  122962. finished:
  122963. fts3SegWriterFree(pWriter);
  122964. sqlite3Fts3SegReaderFinish(&csr);
  122965. return rc;
  122966. }
  122967. /*
  122968. ** Flush the contents of pendingTerms to level 0 segments.
  122969. */
  122970. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  122971. int rc = SQLITE_OK;
  122972. int i;
  122973. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  122974. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  122975. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  122976. }
  122977. sqlite3Fts3PendingTermsClear(p);
  122978. /* Determine the auto-incr-merge setting if unknown. If enabled,
  122979. ** estimate the number of leaf blocks of content to be written
  122980. */
  122981. if( rc==SQLITE_OK && p->bHasStat
  122982. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  122983. ){
  122984. sqlite3_stmt *pStmt = 0;
  122985. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  122986. if( rc==SQLITE_OK ){
  122987. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  122988. rc = sqlite3_step(pStmt);
  122989. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  122990. rc = sqlite3_reset(pStmt);
  122991. }
  122992. }
  122993. return rc;
  122994. }
  122995. /*
  122996. ** Encode N integers as varints into a blob.
  122997. */
  122998. static void fts3EncodeIntArray(
  122999. int N, /* The number of integers to encode */
  123000. u32 *a, /* The integer values */
  123001. char *zBuf, /* Write the BLOB here */
  123002. int *pNBuf /* Write number of bytes if zBuf[] used here */
  123003. ){
  123004. int i, j;
  123005. for(i=j=0; i<N; i++){
  123006. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  123007. }
  123008. *pNBuf = j;
  123009. }
  123010. /*
  123011. ** Decode a blob of varints into N integers
  123012. */
  123013. static void fts3DecodeIntArray(
  123014. int N, /* The number of integers to decode */
  123015. u32 *a, /* Write the integer values */
  123016. const char *zBuf, /* The BLOB containing the varints */
  123017. int nBuf /* size of the BLOB */
  123018. ){
  123019. int i, j;
  123020. UNUSED_PARAMETER(nBuf);
  123021. for(i=j=0; i<N; i++){
  123022. sqlite3_int64 x;
  123023. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  123024. assert(j<=nBuf);
  123025. a[i] = (u32)(x & 0xffffffff);
  123026. }
  123027. }
  123028. /*
  123029. ** Insert the sizes (in tokens) for each column of the document
  123030. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  123031. ** a blob of varints.
  123032. */
  123033. static void fts3InsertDocsize(
  123034. int *pRC, /* Result code */
  123035. Fts3Table *p, /* Table into which to insert */
  123036. u32 *aSz /* Sizes of each column, in tokens */
  123037. ){
  123038. char *pBlob; /* The BLOB encoding of the document size */
  123039. int nBlob; /* Number of bytes in the BLOB */
  123040. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  123041. int rc; /* Result code from subfunctions */
  123042. if( *pRC ) return;
  123043. pBlob = sqlite3_malloc( 10*p->nColumn );
  123044. if( pBlob==0 ){
  123045. *pRC = SQLITE_NOMEM;
  123046. return;
  123047. }
  123048. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  123049. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  123050. if( rc ){
  123051. sqlite3_free(pBlob);
  123052. *pRC = rc;
  123053. return;
  123054. }
  123055. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  123056. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  123057. sqlite3_step(pStmt);
  123058. *pRC = sqlite3_reset(pStmt);
  123059. }
  123060. /*
  123061. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  123062. ** where N is the number of user defined columns in the fts3 table plus
  123063. ** two. If nCol is the number of user defined columns, then values of the
  123064. ** varints are set as follows:
  123065. **
  123066. ** Varint 0: Total number of rows in the table.
  123067. **
  123068. ** Varint 1..nCol: For each column, the total number of tokens stored in
  123069. ** the column for all rows of the table.
  123070. **
  123071. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  123072. ** columns of all rows of the table.
  123073. **
  123074. */
  123075. static void fts3UpdateDocTotals(
  123076. int *pRC, /* The result code */
  123077. Fts3Table *p, /* Table being updated */
  123078. u32 *aSzIns, /* Size increases */
  123079. u32 *aSzDel, /* Size decreases */
  123080. int nChng /* Change in the number of documents */
  123081. ){
  123082. char *pBlob; /* Storage for BLOB written into %_stat */
  123083. int nBlob; /* Size of BLOB written into %_stat */
  123084. u32 *a; /* Array of integers that becomes the BLOB */
  123085. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  123086. int i; /* Loop counter */
  123087. int rc; /* Result code from subfunctions */
  123088. const int nStat = p->nColumn+2;
  123089. if( *pRC ) return;
  123090. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  123091. if( a==0 ){
  123092. *pRC = SQLITE_NOMEM;
  123093. return;
  123094. }
  123095. pBlob = (char*)&a[nStat];
  123096. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  123097. if( rc ){
  123098. sqlite3_free(a);
  123099. *pRC = rc;
  123100. return;
  123101. }
  123102. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  123103. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  123104. fts3DecodeIntArray(nStat, a,
  123105. sqlite3_column_blob(pStmt, 0),
  123106. sqlite3_column_bytes(pStmt, 0));
  123107. }else{
  123108. memset(a, 0, sizeof(u32)*(nStat) );
  123109. }
  123110. rc = sqlite3_reset(pStmt);
  123111. if( rc!=SQLITE_OK ){
  123112. sqlite3_free(a);
  123113. *pRC = rc;
  123114. return;
  123115. }
  123116. if( nChng<0 && a[0]<(u32)(-nChng) ){
  123117. a[0] = 0;
  123118. }else{
  123119. a[0] += nChng;
  123120. }
  123121. for(i=0; i<p->nColumn+1; i++){
  123122. u32 x = a[i+1];
  123123. if( x+aSzIns[i] < aSzDel[i] ){
  123124. x = 0;
  123125. }else{
  123126. x = x + aSzIns[i] - aSzDel[i];
  123127. }
  123128. a[i+1] = x;
  123129. }
  123130. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  123131. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  123132. if( rc ){
  123133. sqlite3_free(a);
  123134. *pRC = rc;
  123135. return;
  123136. }
  123137. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  123138. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  123139. sqlite3_step(pStmt);
  123140. *pRC = sqlite3_reset(pStmt);
  123141. sqlite3_free(a);
  123142. }
  123143. /*
  123144. ** Merge the entire database so that there is one segment for each
  123145. ** iIndex/iLangid combination.
  123146. */
  123147. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  123148. int bSeenDone = 0;
  123149. int rc;
  123150. sqlite3_stmt *pAllLangid = 0;
  123151. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  123152. if( rc==SQLITE_OK ){
  123153. int rc2;
  123154. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  123155. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  123156. int i;
  123157. int iLangid = sqlite3_column_int(pAllLangid, 0);
  123158. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  123159. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  123160. if( rc==SQLITE_DONE ){
  123161. bSeenDone = 1;
  123162. rc = SQLITE_OK;
  123163. }
  123164. }
  123165. }
  123166. rc2 = sqlite3_reset(pAllLangid);
  123167. if( rc==SQLITE_OK ) rc = rc2;
  123168. }
  123169. sqlite3Fts3SegmentsClose(p);
  123170. sqlite3Fts3PendingTermsClear(p);
  123171. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  123172. }
  123173. /*
  123174. ** This function is called when the user executes the following statement:
  123175. **
  123176. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  123177. **
  123178. ** The entire FTS index is discarded and rebuilt. If the table is one
  123179. ** created using the content=xxx option, then the new index is based on
  123180. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  123181. ** on the contents of the %_content table.
  123182. */
  123183. static int fts3DoRebuild(Fts3Table *p){
  123184. int rc; /* Return Code */
  123185. rc = fts3DeleteAll(p, 0);
  123186. if( rc==SQLITE_OK ){
  123187. u32 *aSz = 0;
  123188. u32 *aSzIns = 0;
  123189. u32 *aSzDel = 0;
  123190. sqlite3_stmt *pStmt = 0;
  123191. int nEntry = 0;
  123192. /* Compose and prepare an SQL statement to loop through the content table */
  123193. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  123194. if( !zSql ){
  123195. rc = SQLITE_NOMEM;
  123196. }else{
  123197. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  123198. sqlite3_free(zSql);
  123199. }
  123200. if( rc==SQLITE_OK ){
  123201. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  123202. aSz = (u32 *)sqlite3_malloc(nByte);
  123203. if( aSz==0 ){
  123204. rc = SQLITE_NOMEM;
  123205. }else{
  123206. memset(aSz, 0, nByte);
  123207. aSzIns = &aSz[p->nColumn+1];
  123208. aSzDel = &aSzIns[p->nColumn+1];
  123209. }
  123210. }
  123211. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  123212. int iCol;
  123213. int iLangid = langidFromSelect(p, pStmt);
  123214. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  123215. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  123216. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  123217. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  123218. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  123219. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  123220. }
  123221. if( p->bHasDocsize ){
  123222. fts3InsertDocsize(&rc, p, aSz);
  123223. }
  123224. if( rc!=SQLITE_OK ){
  123225. sqlite3_finalize(pStmt);
  123226. pStmt = 0;
  123227. }else{
  123228. nEntry++;
  123229. for(iCol=0; iCol<=p->nColumn; iCol++){
  123230. aSzIns[iCol] += aSz[iCol];
  123231. }
  123232. }
  123233. }
  123234. if( p->bFts4 ){
  123235. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  123236. }
  123237. sqlite3_free(aSz);
  123238. if( pStmt ){
  123239. int rc2 = sqlite3_finalize(pStmt);
  123240. if( rc==SQLITE_OK ){
  123241. rc = rc2;
  123242. }
  123243. }
  123244. }
  123245. return rc;
  123246. }
  123247. /*
  123248. ** This function opens a cursor used to read the input data for an
  123249. ** incremental merge operation. Specifically, it opens a cursor to scan
  123250. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  123251. ** level iAbsLevel.
  123252. */
  123253. static int fts3IncrmergeCsr(
  123254. Fts3Table *p, /* FTS3 table handle */
  123255. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  123256. int nSeg, /* Number of segments to merge */
  123257. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  123258. ){
  123259. int rc; /* Return Code */
  123260. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  123261. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  123262. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  123263. memset(pCsr, 0, sizeof(*pCsr));
  123264. nByte = sizeof(Fts3SegReader *) * nSeg;
  123265. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  123266. if( pCsr->apSegment==0 ){
  123267. rc = SQLITE_NOMEM;
  123268. }else{
  123269. memset(pCsr->apSegment, 0, nByte);
  123270. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  123271. }
  123272. if( rc==SQLITE_OK ){
  123273. int i;
  123274. int rc2;
  123275. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  123276. assert( pCsr->nSegment==0 );
  123277. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  123278. rc = sqlite3Fts3SegReaderNew(i, 0,
  123279. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  123280. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  123281. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  123282. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  123283. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  123284. &pCsr->apSegment[i]
  123285. );
  123286. pCsr->nSegment++;
  123287. }
  123288. rc2 = sqlite3_reset(pStmt);
  123289. if( rc==SQLITE_OK ) rc = rc2;
  123290. }
  123291. return rc;
  123292. }
  123293. typedef struct IncrmergeWriter IncrmergeWriter;
  123294. typedef struct NodeWriter NodeWriter;
  123295. typedef struct Blob Blob;
  123296. typedef struct NodeReader NodeReader;
  123297. /*
  123298. ** An instance of the following structure is used as a dynamic buffer
  123299. ** to build up nodes or other blobs of data in.
  123300. **
  123301. ** The function blobGrowBuffer() is used to extend the allocation.
  123302. */
  123303. struct Blob {
  123304. char *a; /* Pointer to allocation */
  123305. int n; /* Number of valid bytes of data in a[] */
  123306. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  123307. };
  123308. /*
  123309. ** This structure is used to build up buffers containing segment b-tree
  123310. ** nodes (blocks).
  123311. */
  123312. struct NodeWriter {
  123313. sqlite3_int64 iBlock; /* Current block id */
  123314. Blob key; /* Last key written to the current block */
  123315. Blob block; /* Current block image */
  123316. };
  123317. /*
  123318. ** An object of this type contains the state required to create or append
  123319. ** to an appendable b-tree segment.
  123320. */
  123321. struct IncrmergeWriter {
  123322. int nLeafEst; /* Space allocated for leaf blocks */
  123323. int nWork; /* Number of leaf pages flushed */
  123324. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  123325. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  123326. sqlite3_int64 iStart; /* Block number of first allocated block */
  123327. sqlite3_int64 iEnd; /* Block number of last allocated block */
  123328. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  123329. };
  123330. /*
  123331. ** An object of the following type is used to read data from a single
  123332. ** FTS segment node. See the following functions:
  123333. **
  123334. ** nodeReaderInit()
  123335. ** nodeReaderNext()
  123336. ** nodeReaderRelease()
  123337. */
  123338. struct NodeReader {
  123339. const char *aNode;
  123340. int nNode;
  123341. int iOff; /* Current offset within aNode[] */
  123342. /* Output variables. Containing the current node entry. */
  123343. sqlite3_int64 iChild; /* Pointer to child node */
  123344. Blob term; /* Current term */
  123345. const char *aDoclist; /* Pointer to doclist */
  123346. int nDoclist; /* Size of doclist in bytes */
  123347. };
  123348. /*
  123349. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  123350. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  123351. ** bytes in size, extend (realloc) it to be so.
  123352. **
  123353. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  123354. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  123355. ** to reflect the new size of the pBlob->a[] buffer.
  123356. */
  123357. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  123358. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  123359. int nAlloc = nMin;
  123360. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  123361. if( a ){
  123362. pBlob->nAlloc = nAlloc;
  123363. pBlob->a = a;
  123364. }else{
  123365. *pRc = SQLITE_NOMEM;
  123366. }
  123367. }
  123368. }
  123369. /*
  123370. ** Attempt to advance the node-reader object passed as the first argument to
  123371. ** the next entry on the node.
  123372. **
  123373. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  123374. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  123375. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  123376. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  123377. ** variables for the new entry.
  123378. */
  123379. static int nodeReaderNext(NodeReader *p){
  123380. int bFirst = (p->term.n==0); /* True for first term on the node */
  123381. int nPrefix = 0; /* Bytes to copy from previous term */
  123382. int nSuffix = 0; /* Bytes to append to the prefix */
  123383. int rc = SQLITE_OK; /* Return code */
  123384. assert( p->aNode );
  123385. if( p->iChild && bFirst==0 ) p->iChild++;
  123386. if( p->iOff>=p->nNode ){
  123387. /* EOF */
  123388. p->aNode = 0;
  123389. }else{
  123390. if( bFirst==0 ){
  123391. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  123392. }
  123393. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  123394. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  123395. if( rc==SQLITE_OK ){
  123396. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  123397. p->term.n = nPrefix+nSuffix;
  123398. p->iOff += nSuffix;
  123399. if( p->iChild==0 ){
  123400. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  123401. p->aDoclist = &p->aNode[p->iOff];
  123402. p->iOff += p->nDoclist;
  123403. }
  123404. }
  123405. }
  123406. assert( p->iOff<=p->nNode );
  123407. return rc;
  123408. }
  123409. /*
  123410. ** Release all dynamic resources held by node-reader object *p.
  123411. */
  123412. static void nodeReaderRelease(NodeReader *p){
  123413. sqlite3_free(p->term.a);
  123414. }
  123415. /*
  123416. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  123417. **
  123418. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  123419. ** point to the first entry on the node (if any). Otherwise, an SQLite
  123420. ** error code is returned.
  123421. */
  123422. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  123423. memset(p, 0, sizeof(NodeReader));
  123424. p->aNode = aNode;
  123425. p->nNode = nNode;
  123426. /* Figure out if this is a leaf or an internal node. */
  123427. if( p->aNode[0] ){
  123428. /* An internal node. */
  123429. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  123430. }else{
  123431. p->iOff = 1;
  123432. }
  123433. return nodeReaderNext(p);
  123434. }
  123435. /*
  123436. ** This function is called while writing an FTS segment each time a leaf o
  123437. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  123438. ** to be greater than the largest key on the node just written, but smaller
  123439. ** than or equal to the first key that will be written to the next leaf
  123440. ** node.
  123441. **
  123442. ** The block id of the leaf node just written to disk may be found in
  123443. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  123444. */
  123445. static int fts3IncrmergePush(
  123446. Fts3Table *p, /* Fts3 table handle */
  123447. IncrmergeWriter *pWriter, /* Writer object */
  123448. const char *zTerm, /* Term to write to internal node */
  123449. int nTerm /* Bytes at zTerm */
  123450. ){
  123451. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  123452. int iLayer;
  123453. assert( nTerm>0 );
  123454. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  123455. sqlite3_int64 iNextPtr = 0;
  123456. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  123457. int rc = SQLITE_OK;
  123458. int nPrefix;
  123459. int nSuffix;
  123460. int nSpace;
  123461. /* Figure out how much space the key will consume if it is written to
  123462. ** the current node of layer iLayer. Due to the prefix compression,
  123463. ** the space required changes depending on which node the key is to
  123464. ** be added to. */
  123465. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  123466. nSuffix = nTerm - nPrefix;
  123467. nSpace = sqlite3Fts3VarintLen(nPrefix);
  123468. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  123469. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  123470. /* If the current node of layer iLayer contains zero keys, or if adding
  123471. ** the key to it will not cause it to grow to larger than nNodeSize
  123472. ** bytes in size, write the key here. */
  123473. Blob *pBlk = &pNode->block;
  123474. if( pBlk->n==0 ){
  123475. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  123476. if( rc==SQLITE_OK ){
  123477. pBlk->a[0] = (char)iLayer;
  123478. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  123479. }
  123480. }
  123481. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  123482. blobGrowBuffer(&pNode->key, nTerm, &rc);
  123483. if( rc==SQLITE_OK ){
  123484. if( pNode->key.n ){
  123485. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  123486. }
  123487. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  123488. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  123489. pBlk->n += nSuffix;
  123490. memcpy(pNode->key.a, zTerm, nTerm);
  123491. pNode->key.n = nTerm;
  123492. }
  123493. }else{
  123494. /* Otherwise, flush the current node of layer iLayer to disk.
  123495. ** Then allocate a new, empty sibling node. The key will be written
  123496. ** into the parent of this node. */
  123497. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  123498. assert( pNode->block.nAlloc>=p->nNodeSize );
  123499. pNode->block.a[0] = (char)iLayer;
  123500. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  123501. iNextPtr = pNode->iBlock;
  123502. pNode->iBlock++;
  123503. pNode->key.n = 0;
  123504. }
  123505. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  123506. iPtr = iNextPtr;
  123507. }
  123508. assert( 0 );
  123509. return 0;
  123510. }
  123511. /*
  123512. ** Append a term and (optionally) doclist to the FTS segment node currently
  123513. ** stored in blob *pNode. The node need not contain any terms, but the
  123514. ** header must be written before this function is called.
  123515. **
  123516. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  123517. ** followed by the left-hand-child varint for an internal node.
  123518. **
  123519. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  123520. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  123521. ** node, both aDoclist and nDoclist must be passed 0.
  123522. **
  123523. ** If the size of the value in blob pPrev is zero, then this is the first
  123524. ** term written to the node. Otherwise, pPrev contains a copy of the
  123525. ** previous term. Before this function returns, it is updated to contain a
  123526. ** copy of zTerm/nTerm.
  123527. **
  123528. ** It is assumed that the buffer associated with pNode is already large
  123529. ** enough to accommodate the new entry. The buffer associated with pPrev
  123530. ** is extended by this function if requrired.
  123531. **
  123532. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  123533. ** returned. Otherwise, SQLITE_OK.
  123534. */
  123535. static int fts3AppendToNode(
  123536. Blob *pNode, /* Current node image to append to */
  123537. Blob *pPrev, /* Buffer containing previous term written */
  123538. const char *zTerm, /* New term to write */
  123539. int nTerm, /* Size of zTerm in bytes */
  123540. const char *aDoclist, /* Doclist (or NULL) to write */
  123541. int nDoclist /* Size of aDoclist in bytes */
  123542. ){
  123543. int rc = SQLITE_OK; /* Return code */
  123544. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  123545. int nPrefix; /* Size of term prefix in bytes */
  123546. int nSuffix; /* Size of term suffix in bytes */
  123547. /* Node must have already been started. There must be a doclist for a
  123548. ** leaf node, and there must not be a doclist for an internal node. */
  123549. assert( pNode->n>0 );
  123550. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  123551. blobGrowBuffer(pPrev, nTerm, &rc);
  123552. if( rc!=SQLITE_OK ) return rc;
  123553. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  123554. nSuffix = nTerm - nPrefix;
  123555. memcpy(pPrev->a, zTerm, nTerm);
  123556. pPrev->n = nTerm;
  123557. if( bFirst==0 ){
  123558. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  123559. }
  123560. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  123561. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  123562. pNode->n += nSuffix;
  123563. if( aDoclist ){
  123564. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  123565. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  123566. pNode->n += nDoclist;
  123567. }
  123568. assert( pNode->n<=pNode->nAlloc );
  123569. return SQLITE_OK;
  123570. }
  123571. /*
  123572. ** Append the current term and doclist pointed to by cursor pCsr to the
  123573. ** appendable b-tree segment opened for writing by pWriter.
  123574. **
  123575. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  123576. */
  123577. static int fts3IncrmergeAppend(
  123578. Fts3Table *p, /* Fts3 table handle */
  123579. IncrmergeWriter *pWriter, /* Writer object */
  123580. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  123581. ){
  123582. const char *zTerm = pCsr->zTerm;
  123583. int nTerm = pCsr->nTerm;
  123584. const char *aDoclist = pCsr->aDoclist;
  123585. int nDoclist = pCsr->nDoclist;
  123586. int rc = SQLITE_OK; /* Return code */
  123587. int nSpace; /* Total space in bytes required on leaf */
  123588. int nPrefix; /* Size of prefix shared with previous term */
  123589. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  123590. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  123591. pLeaf = &pWriter->aNodeWriter[0];
  123592. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  123593. nSuffix = nTerm - nPrefix;
  123594. nSpace = sqlite3Fts3VarintLen(nPrefix);
  123595. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  123596. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  123597. /* If the current block is not empty, and if adding this term/doclist
  123598. ** to the current block would make it larger than Fts3Table.nNodeSize
  123599. ** bytes, write this block out to the database. */
  123600. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  123601. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  123602. pWriter->nWork++;
  123603. /* Add the current term to the parent node. The term added to the
  123604. ** parent must:
  123605. **
  123606. ** a) be greater than the largest term on the leaf node just written
  123607. ** to the database (still available in pLeaf->key), and
  123608. **
  123609. ** b) be less than or equal to the term about to be added to the new
  123610. ** leaf node (zTerm/nTerm).
  123611. **
  123612. ** In other words, it must be the prefix of zTerm 1 byte longer than
  123613. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  123614. */
  123615. if( rc==SQLITE_OK ){
  123616. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  123617. }
  123618. /* Advance to the next output block */
  123619. pLeaf->iBlock++;
  123620. pLeaf->key.n = 0;
  123621. pLeaf->block.n = 0;
  123622. nSuffix = nTerm;
  123623. nSpace = 1;
  123624. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  123625. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  123626. }
  123627. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  123628. if( rc==SQLITE_OK ){
  123629. if( pLeaf->block.n==0 ){
  123630. pLeaf->block.n = 1;
  123631. pLeaf->block.a[0] = '\0';
  123632. }
  123633. rc = fts3AppendToNode(
  123634. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  123635. );
  123636. }
  123637. return rc;
  123638. }
  123639. /*
  123640. ** This function is called to release all dynamic resources held by the
  123641. ** merge-writer object pWriter, and if no error has occurred, to flush
  123642. ** all outstanding node buffers held by pWriter to disk.
  123643. **
  123644. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  123645. ** is made to write any data to disk. Instead, this function serves only
  123646. ** to release outstanding resources.
  123647. **
  123648. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  123649. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  123650. ** returning.
  123651. */
  123652. static void fts3IncrmergeRelease(
  123653. Fts3Table *p, /* FTS3 table handle */
  123654. IncrmergeWriter *pWriter, /* Merge-writer object */
  123655. int *pRc /* IN/OUT: Error code */
  123656. ){
  123657. int i; /* Used to iterate through non-root layers */
  123658. int iRoot; /* Index of root in pWriter->aNodeWriter */
  123659. NodeWriter *pRoot; /* NodeWriter for root node */
  123660. int rc = *pRc; /* Error code */
  123661. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  123662. ** root node. If the segment fits entirely on a single leaf node, iRoot
  123663. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  123664. ** will be 1. And so on. */
  123665. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  123666. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  123667. if( pNode->block.n>0 ) break;
  123668. assert( *pRc || pNode->block.nAlloc==0 );
  123669. assert( *pRc || pNode->key.nAlloc==0 );
  123670. sqlite3_free(pNode->block.a);
  123671. sqlite3_free(pNode->key.a);
  123672. }
  123673. /* Empty output segment. This is a no-op. */
  123674. if( iRoot<0 ) return;
  123675. /* The entire output segment fits on a single node. Normally, this means
  123676. ** the node would be stored as a blob in the "root" column of the %_segdir
  123677. ** table. However, this is not permitted in this case. The problem is that
  123678. ** space has already been reserved in the %_segments table, and so the
  123679. ** start_block and end_block fields of the %_segdir table must be populated.
  123680. ** And, by design or by accident, released versions of FTS cannot handle
  123681. ** segments that fit entirely on the root node with start_block!=0.
  123682. **
  123683. ** Instead, create a synthetic root node that contains nothing but a
  123684. ** pointer to the single content node. So that the segment consists of a
  123685. ** single leaf and a single interior (root) node.
  123686. **
  123687. ** Todo: Better might be to defer allocating space in the %_segments
  123688. ** table until we are sure it is needed.
  123689. */
  123690. if( iRoot==0 ){
  123691. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  123692. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  123693. if( rc==SQLITE_OK ){
  123694. pBlock->a[0] = 0x01;
  123695. pBlock->n = 1 + sqlite3Fts3PutVarint(
  123696. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  123697. );
  123698. }
  123699. iRoot = 1;
  123700. }
  123701. pRoot = &pWriter->aNodeWriter[iRoot];
  123702. /* Flush all currently outstanding nodes to disk. */
  123703. for(i=0; i<iRoot; i++){
  123704. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  123705. if( pNode->block.n>0 && rc==SQLITE_OK ){
  123706. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  123707. }
  123708. sqlite3_free(pNode->block.a);
  123709. sqlite3_free(pNode->key.a);
  123710. }
  123711. /* Write the %_segdir record. */
  123712. if( rc==SQLITE_OK ){
  123713. rc = fts3WriteSegdir(p,
  123714. pWriter->iAbsLevel+1, /* level */
  123715. pWriter->iIdx, /* idx */
  123716. pWriter->iStart, /* start_block */
  123717. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  123718. pWriter->iEnd, /* end_block */
  123719. pRoot->block.a, pRoot->block.n /* root */
  123720. );
  123721. }
  123722. sqlite3_free(pRoot->block.a);
  123723. sqlite3_free(pRoot->key.a);
  123724. *pRc = rc;
  123725. }
  123726. /*
  123727. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  123728. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  123729. ** the other, it is considered to be smaller than the other.
  123730. **
  123731. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  123732. ** if it is greater.
  123733. */
  123734. static int fts3TermCmp(
  123735. const char *zLhs, int nLhs, /* LHS of comparison */
  123736. const char *zRhs, int nRhs /* RHS of comparison */
  123737. ){
  123738. int nCmp = MIN(nLhs, nRhs);
  123739. int res;
  123740. res = memcmp(zLhs, zRhs, nCmp);
  123741. if( res==0 ) res = nLhs - nRhs;
  123742. return res;
  123743. }
  123744. /*
  123745. ** Query to see if the entry in the %_segments table with blockid iEnd is
  123746. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  123747. ** returning. Otherwise, set *pbRes to 0.
  123748. **
  123749. ** Or, if an error occurs while querying the database, return an SQLite
  123750. ** error code. The final value of *pbRes is undefined in this case.
  123751. **
  123752. ** This is used to test if a segment is an "appendable" segment. If it
  123753. ** is, then a NULL entry has been inserted into the %_segments table
  123754. ** with blockid %_segdir.end_block.
  123755. */
  123756. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  123757. int bRes = 0; /* Result to set *pbRes to */
  123758. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  123759. int rc; /* Return code */
  123760. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  123761. if( rc==SQLITE_OK ){
  123762. sqlite3_bind_int64(pCheck, 1, iEnd);
  123763. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  123764. rc = sqlite3_reset(pCheck);
  123765. }
  123766. *pbRes = bRes;
  123767. return rc;
  123768. }
  123769. /*
  123770. ** This function is called when initializing an incremental-merge operation.
  123771. ** It checks if the existing segment with index value iIdx at absolute level
  123772. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  123773. ** merge-writer object *pWriter is initialized to write to it.
  123774. **
  123775. ** An existing segment can be appended to by an incremental merge if:
  123776. **
  123777. ** * It was initially created as an appendable segment (with all required
  123778. ** space pre-allocated), and
  123779. **
  123780. ** * The first key read from the input (arguments zKey and nKey) is
  123781. ** greater than the largest key currently stored in the potential
  123782. ** output segment.
  123783. */
  123784. static int fts3IncrmergeLoad(
  123785. Fts3Table *p, /* Fts3 table handle */
  123786. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  123787. int iIdx, /* Index of candidate output segment */
  123788. const char *zKey, /* First key to write */
  123789. int nKey, /* Number of bytes in nKey */
  123790. IncrmergeWriter *pWriter /* Populate this object */
  123791. ){
  123792. int rc; /* Return code */
  123793. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  123794. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  123795. if( rc==SQLITE_OK ){
  123796. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  123797. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  123798. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  123799. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  123800. int nRoot = 0; /* Size of aRoot[] in bytes */
  123801. int rc2; /* Return code from sqlite3_reset() */
  123802. int bAppendable = 0; /* Set to true if segment is appendable */
  123803. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  123804. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  123805. sqlite3_bind_int(pSelect, 2, iIdx);
  123806. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  123807. iStart = sqlite3_column_int64(pSelect, 1);
  123808. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  123809. iEnd = sqlite3_column_int64(pSelect, 3);
  123810. nRoot = sqlite3_column_bytes(pSelect, 4);
  123811. aRoot = sqlite3_column_blob(pSelect, 4);
  123812. }else{
  123813. return sqlite3_reset(pSelect);
  123814. }
  123815. /* Check for the zero-length marker in the %_segments table */
  123816. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  123817. /* Check that zKey/nKey is larger than the largest key the candidate */
  123818. if( rc==SQLITE_OK && bAppendable ){
  123819. char *aLeaf = 0;
  123820. int nLeaf = 0;
  123821. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  123822. if( rc==SQLITE_OK ){
  123823. NodeReader reader;
  123824. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  123825. rc==SQLITE_OK && reader.aNode;
  123826. rc = nodeReaderNext(&reader)
  123827. ){
  123828. assert( reader.aNode );
  123829. }
  123830. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  123831. bAppendable = 0;
  123832. }
  123833. nodeReaderRelease(&reader);
  123834. }
  123835. sqlite3_free(aLeaf);
  123836. }
  123837. if( rc==SQLITE_OK && bAppendable ){
  123838. /* It is possible to append to this segment. Set up the IncrmergeWriter
  123839. ** object to do so. */
  123840. int i;
  123841. int nHeight = (int)aRoot[0];
  123842. NodeWriter *pNode;
  123843. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  123844. pWriter->iStart = iStart;
  123845. pWriter->iEnd = iEnd;
  123846. pWriter->iAbsLevel = iAbsLevel;
  123847. pWriter->iIdx = iIdx;
  123848. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  123849. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  123850. }
  123851. pNode = &pWriter->aNodeWriter[nHeight];
  123852. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  123853. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  123854. if( rc==SQLITE_OK ){
  123855. memcpy(pNode->block.a, aRoot, nRoot);
  123856. pNode->block.n = nRoot;
  123857. }
  123858. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  123859. NodeReader reader;
  123860. pNode = &pWriter->aNodeWriter[i];
  123861. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  123862. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  123863. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  123864. if( rc==SQLITE_OK ){
  123865. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  123866. pNode->key.n = reader.term.n;
  123867. if( i>0 ){
  123868. char *aBlock = 0;
  123869. int nBlock = 0;
  123870. pNode = &pWriter->aNodeWriter[i-1];
  123871. pNode->iBlock = reader.iChild;
  123872. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  123873. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  123874. if( rc==SQLITE_OK ){
  123875. memcpy(pNode->block.a, aBlock, nBlock);
  123876. pNode->block.n = nBlock;
  123877. }
  123878. sqlite3_free(aBlock);
  123879. }
  123880. }
  123881. nodeReaderRelease(&reader);
  123882. }
  123883. }
  123884. rc2 = sqlite3_reset(pSelect);
  123885. if( rc==SQLITE_OK ) rc = rc2;
  123886. }
  123887. return rc;
  123888. }
  123889. /*
  123890. ** Determine the largest segment index value that exists within absolute
  123891. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  123892. ** one before returning SQLITE_OK. Or, if there are no segments at all
  123893. ** within level iAbsLevel, set *piIdx to zero.
  123894. **
  123895. ** If an error occurs, return an SQLite error code. The final value of
  123896. ** *piIdx is undefined in this case.
  123897. */
  123898. static int fts3IncrmergeOutputIdx(
  123899. Fts3Table *p, /* FTS Table handle */
  123900. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  123901. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  123902. ){
  123903. int rc;
  123904. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  123905. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  123906. if( rc==SQLITE_OK ){
  123907. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  123908. sqlite3_step(pOutputIdx);
  123909. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  123910. rc = sqlite3_reset(pOutputIdx);
  123911. }
  123912. return rc;
  123913. }
  123914. /*
  123915. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  123916. ** with idx value iIdx.
  123917. **
  123918. ** In the %_segdir table, a segment is defined by the values in three
  123919. ** columns:
  123920. **
  123921. ** start_block
  123922. ** leaves_end_block
  123923. ** end_block
  123924. **
  123925. ** When an appendable segment is allocated, it is estimated that the
  123926. ** maximum number of leaf blocks that may be required is the sum of the
  123927. ** number of leaf blocks consumed by the input segments, plus the number
  123928. ** of input segments, multiplied by two. This value is stored in stack
  123929. ** variable nLeafEst.
  123930. **
  123931. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  123932. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  123933. ** array of leaf nodes starts at the first block allocated. The array
  123934. ** of interior nodes that are parents of the leaf nodes start at block
  123935. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  123936. **
  123937. ** In the actual code below, the value "16" is replaced with the
  123938. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  123939. */
  123940. static int fts3IncrmergeWriter(
  123941. Fts3Table *p, /* Fts3 table handle */
  123942. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  123943. int iIdx, /* Index of new output segment */
  123944. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  123945. IncrmergeWriter *pWriter /* Populate this object */
  123946. ){
  123947. int rc; /* Return Code */
  123948. int i; /* Iterator variable */
  123949. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  123950. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  123951. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  123952. /* Calculate nLeafEst. */
  123953. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  123954. if( rc==SQLITE_OK ){
  123955. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  123956. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  123957. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  123958. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  123959. }
  123960. rc = sqlite3_reset(pLeafEst);
  123961. }
  123962. if( rc!=SQLITE_OK ) return rc;
  123963. /* Calculate the first block to use in the output segment */
  123964. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  123965. if( rc==SQLITE_OK ){
  123966. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  123967. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  123968. pWriter->iEnd = pWriter->iStart - 1;
  123969. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  123970. }
  123971. rc = sqlite3_reset(pFirstBlock);
  123972. }
  123973. if( rc!=SQLITE_OK ) return rc;
  123974. /* Insert the marker in the %_segments table to make sure nobody tries
  123975. ** to steal the space just allocated. This is also used to identify
  123976. ** appendable segments. */
  123977. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  123978. if( rc!=SQLITE_OK ) return rc;
  123979. pWriter->iAbsLevel = iAbsLevel;
  123980. pWriter->nLeafEst = nLeafEst;
  123981. pWriter->iIdx = iIdx;
  123982. /* Set up the array of NodeWriter objects */
  123983. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  123984. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  123985. }
  123986. return SQLITE_OK;
  123987. }
  123988. /*
  123989. ** Remove an entry from the %_segdir table. This involves running the
  123990. ** following two statements:
  123991. **
  123992. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  123993. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  123994. **
  123995. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  123996. ** statement ensures that the remaining segments have contiguously allocated
  123997. ** idx values.
  123998. */
  123999. static int fts3RemoveSegdirEntry(
  124000. Fts3Table *p, /* FTS3 table handle */
  124001. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  124002. int iIdx /* Index of %_segdir entry to delete */
  124003. ){
  124004. int rc; /* Return code */
  124005. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  124006. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  124007. if( rc==SQLITE_OK ){
  124008. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  124009. sqlite3_bind_int(pDelete, 2, iIdx);
  124010. sqlite3_step(pDelete);
  124011. rc = sqlite3_reset(pDelete);
  124012. }
  124013. return rc;
  124014. }
  124015. /*
  124016. ** One or more segments have just been removed from absolute level iAbsLevel.
  124017. ** Update the 'idx' values of the remaining segments in the level so that
  124018. ** the idx values are a contiguous sequence starting from 0.
  124019. */
  124020. static int fts3RepackSegdirLevel(
  124021. Fts3Table *p, /* FTS3 table handle */
  124022. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  124023. ){
  124024. int rc; /* Return code */
  124025. int *aIdx = 0; /* Array of remaining idx values */
  124026. int nIdx = 0; /* Valid entries in aIdx[] */
  124027. int nAlloc = 0; /* Allocated size of aIdx[] */
  124028. int i; /* Iterator variable */
  124029. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  124030. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  124031. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  124032. if( rc==SQLITE_OK ){
  124033. int rc2;
  124034. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  124035. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  124036. if( nIdx>=nAlloc ){
  124037. int *aNew;
  124038. nAlloc += 16;
  124039. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  124040. if( !aNew ){
  124041. rc = SQLITE_NOMEM;
  124042. break;
  124043. }
  124044. aIdx = aNew;
  124045. }
  124046. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  124047. }
  124048. rc2 = sqlite3_reset(pSelect);
  124049. if( rc==SQLITE_OK ) rc = rc2;
  124050. }
  124051. if( rc==SQLITE_OK ){
  124052. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  124053. }
  124054. if( rc==SQLITE_OK ){
  124055. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  124056. }
  124057. assert( p->bIgnoreSavepoint==0 );
  124058. p->bIgnoreSavepoint = 1;
  124059. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  124060. if( aIdx[i]!=i ){
  124061. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  124062. sqlite3_bind_int(pUpdate, 1, i);
  124063. sqlite3_step(pUpdate);
  124064. rc = sqlite3_reset(pUpdate);
  124065. }
  124066. }
  124067. p->bIgnoreSavepoint = 0;
  124068. sqlite3_free(aIdx);
  124069. return rc;
  124070. }
  124071. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  124072. pNode->a[0] = (char)iHeight;
  124073. if( iChild ){
  124074. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  124075. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  124076. }else{
  124077. assert( pNode->nAlloc>=1 );
  124078. pNode->n = 1;
  124079. }
  124080. }
  124081. /*
  124082. ** The first two arguments are a pointer to and the size of a segment b-tree
  124083. ** node. The node may be a leaf or an internal node.
  124084. **
  124085. ** This function creates a new node image in blob object *pNew by copying
  124086. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  124087. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  124088. */
  124089. static int fts3TruncateNode(
  124090. const char *aNode, /* Current node image */
  124091. int nNode, /* Size of aNode in bytes */
  124092. Blob *pNew, /* OUT: Write new node image here */
  124093. const char *zTerm, /* Omit all terms smaller than this */
  124094. int nTerm, /* Size of zTerm in bytes */
  124095. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  124096. ){
  124097. NodeReader reader; /* Reader object */
  124098. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  124099. int rc = SQLITE_OK; /* Return code */
  124100. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  124101. /* Allocate required output space */
  124102. blobGrowBuffer(pNew, nNode, &rc);
  124103. if( rc!=SQLITE_OK ) return rc;
  124104. pNew->n = 0;
  124105. /* Populate new node buffer */
  124106. for(rc = nodeReaderInit(&reader, aNode, nNode);
  124107. rc==SQLITE_OK && reader.aNode;
  124108. rc = nodeReaderNext(&reader)
  124109. ){
  124110. if( pNew->n==0 ){
  124111. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  124112. if( res<0 || (bLeaf==0 && res==0) ) continue;
  124113. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  124114. *piBlock = reader.iChild;
  124115. }
  124116. rc = fts3AppendToNode(
  124117. pNew, &prev, reader.term.a, reader.term.n,
  124118. reader.aDoclist, reader.nDoclist
  124119. );
  124120. if( rc!=SQLITE_OK ) break;
  124121. }
  124122. if( pNew->n==0 ){
  124123. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  124124. *piBlock = reader.iChild;
  124125. }
  124126. assert( pNew->n<=pNew->nAlloc );
  124127. nodeReaderRelease(&reader);
  124128. sqlite3_free(prev.a);
  124129. return rc;
  124130. }
  124131. /*
  124132. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  124133. ** level iAbsLevel. This may involve deleting entries from the %_segments
  124134. ** table, and modifying existing entries in both the %_segments and %_segdir
  124135. ** tables.
  124136. **
  124137. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  124138. ** SQLite error code otherwise.
  124139. */
  124140. static int fts3TruncateSegment(
  124141. Fts3Table *p, /* FTS3 table handle */
  124142. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  124143. int iIdx, /* Index within level of segment to modify */
  124144. const char *zTerm, /* Remove terms smaller than this */
  124145. int nTerm /* Number of bytes in buffer zTerm */
  124146. ){
  124147. int rc = SQLITE_OK; /* Return code */
  124148. Blob root = {0,0,0}; /* New root page image */
  124149. Blob block = {0,0,0}; /* Buffer used for any other block */
  124150. sqlite3_int64 iBlock = 0; /* Block id */
  124151. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  124152. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  124153. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  124154. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  124155. if( rc==SQLITE_OK ){
  124156. int rc2; /* sqlite3_reset() return code */
  124157. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  124158. sqlite3_bind_int(pFetch, 2, iIdx);
  124159. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  124160. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  124161. int nRoot = sqlite3_column_bytes(pFetch, 4);
  124162. iOldStart = sqlite3_column_int64(pFetch, 1);
  124163. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  124164. }
  124165. rc2 = sqlite3_reset(pFetch);
  124166. if( rc==SQLITE_OK ) rc = rc2;
  124167. }
  124168. while( rc==SQLITE_OK && iBlock ){
  124169. char *aBlock = 0;
  124170. int nBlock = 0;
  124171. iNewStart = iBlock;
  124172. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  124173. if( rc==SQLITE_OK ){
  124174. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  124175. }
  124176. if( rc==SQLITE_OK ){
  124177. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  124178. }
  124179. sqlite3_free(aBlock);
  124180. }
  124181. /* Variable iNewStart now contains the first valid leaf node. */
  124182. if( rc==SQLITE_OK && iNewStart ){
  124183. sqlite3_stmt *pDel = 0;
  124184. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  124185. if( rc==SQLITE_OK ){
  124186. sqlite3_bind_int64(pDel, 1, iOldStart);
  124187. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  124188. sqlite3_step(pDel);
  124189. rc = sqlite3_reset(pDel);
  124190. }
  124191. }
  124192. if( rc==SQLITE_OK ){
  124193. sqlite3_stmt *pChomp = 0;
  124194. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  124195. if( rc==SQLITE_OK ){
  124196. sqlite3_bind_int64(pChomp, 1, iNewStart);
  124197. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  124198. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  124199. sqlite3_bind_int(pChomp, 4, iIdx);
  124200. sqlite3_step(pChomp);
  124201. rc = sqlite3_reset(pChomp);
  124202. }
  124203. }
  124204. sqlite3_free(root.a);
  124205. sqlite3_free(block.a);
  124206. return rc;
  124207. }
  124208. /*
  124209. ** This function is called after an incrmental-merge operation has run to
  124210. ** merge (or partially merge) two or more segments from absolute level
  124211. ** iAbsLevel.
  124212. **
  124213. ** Each input segment is either removed from the db completely (if all of
  124214. ** its data was copied to the output segment by the incrmerge operation)
  124215. ** or modified in place so that it no longer contains those entries that
  124216. ** have been duplicated in the output segment.
  124217. */
  124218. static int fts3IncrmergeChomp(
  124219. Fts3Table *p, /* FTS table handle */
  124220. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  124221. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  124222. int *pnRem /* Number of segments not deleted */
  124223. ){
  124224. int i;
  124225. int nRem = 0;
  124226. int rc = SQLITE_OK;
  124227. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  124228. Fts3SegReader *pSeg = 0;
  124229. int j;
  124230. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  124231. ** somewhere in the pCsr->apSegment[] array. */
  124232. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  124233. pSeg = pCsr->apSegment[j];
  124234. if( pSeg->iIdx==i ) break;
  124235. }
  124236. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  124237. if( pSeg->aNode==0 ){
  124238. /* Seg-reader is at EOF. Remove the entire input segment. */
  124239. rc = fts3DeleteSegment(p, pSeg);
  124240. if( rc==SQLITE_OK ){
  124241. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  124242. }
  124243. *pnRem = 0;
  124244. }else{
  124245. /* The incremental merge did not copy all the data from this
  124246. ** segment to the upper level. The segment is modified in place
  124247. ** so that it contains no keys smaller than zTerm/nTerm. */
  124248. const char *zTerm = pSeg->zTerm;
  124249. int nTerm = pSeg->nTerm;
  124250. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  124251. nRem++;
  124252. }
  124253. }
  124254. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  124255. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  124256. }
  124257. *pnRem = nRem;
  124258. return rc;
  124259. }
  124260. /*
  124261. ** Store an incr-merge hint in the database.
  124262. */
  124263. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  124264. sqlite3_stmt *pReplace = 0;
  124265. int rc; /* Return code */
  124266. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  124267. if( rc==SQLITE_OK ){
  124268. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  124269. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  124270. sqlite3_step(pReplace);
  124271. rc = sqlite3_reset(pReplace);
  124272. }
  124273. return rc;
  124274. }
  124275. /*
  124276. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  124277. ** exists, is stored in the rowid==1 row of the %_stat table.
  124278. **
  124279. ** If successful, populate blob *pHint with the value read from the %_stat
  124280. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  124281. ** SQLite error code.
  124282. */
  124283. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  124284. sqlite3_stmt *pSelect = 0;
  124285. int rc;
  124286. pHint->n = 0;
  124287. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  124288. if( rc==SQLITE_OK ){
  124289. int rc2;
  124290. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  124291. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  124292. const char *aHint = sqlite3_column_blob(pSelect, 0);
  124293. int nHint = sqlite3_column_bytes(pSelect, 0);
  124294. if( aHint ){
  124295. blobGrowBuffer(pHint, nHint, &rc);
  124296. if( rc==SQLITE_OK ){
  124297. memcpy(pHint->a, aHint, nHint);
  124298. pHint->n = nHint;
  124299. }
  124300. }
  124301. }
  124302. rc2 = sqlite3_reset(pSelect);
  124303. if( rc==SQLITE_OK ) rc = rc2;
  124304. }
  124305. return rc;
  124306. }
  124307. /*
  124308. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  124309. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  124310. ** consists of two varints, the absolute level number of the input segments
  124311. ** and the number of input segments.
  124312. **
  124313. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  124314. ** set *pRc to an SQLite error code before returning.
  124315. */
  124316. static void fts3IncrmergeHintPush(
  124317. Blob *pHint, /* Hint blob to append to */
  124318. i64 iAbsLevel, /* First varint to store in hint */
  124319. int nInput, /* Second varint to store in hint */
  124320. int *pRc /* IN/OUT: Error code */
  124321. ){
  124322. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  124323. if( *pRc==SQLITE_OK ){
  124324. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  124325. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  124326. }
  124327. }
  124328. /*
  124329. ** Read the last entry (most recently pushed) from the hint blob *pHint
  124330. ** and then remove the entry. Write the two values read to *piAbsLevel and
  124331. ** *pnInput before returning.
  124332. **
  124333. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  124334. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  124335. */
  124336. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  124337. const int nHint = pHint->n;
  124338. int i;
  124339. i = pHint->n-2;
  124340. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  124341. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  124342. pHint->n = i;
  124343. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  124344. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  124345. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  124346. return SQLITE_OK;
  124347. }
  124348. /*
  124349. ** Attempt an incremental merge that writes nMerge leaf blocks.
  124350. **
  124351. ** Incremental merges happen nMin segments at a time. The two
  124352. ** segments to be merged are the nMin oldest segments (the ones with
  124353. ** the smallest indexes) in the highest level that contains at least
  124354. ** nMin segments. Multiple merges might occur in an attempt to write the
  124355. ** quota of nMerge leaf blocks.
  124356. */
  124357. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  124358. int rc; /* Return code */
  124359. int nRem = nMerge; /* Number of leaf pages yet to be written */
  124360. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  124361. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  124362. IncrmergeWriter *pWriter; /* Writer object */
  124363. int nSeg = 0; /* Number of input segments */
  124364. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  124365. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  124366. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  124367. /* Allocate space for the cursor, filter and writer objects */
  124368. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  124369. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  124370. if( !pWriter ) return SQLITE_NOMEM;
  124371. pFilter = (Fts3SegFilter *)&pWriter[1];
  124372. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  124373. rc = fts3IncrmergeHintLoad(p, &hint);
  124374. while( rc==SQLITE_OK && nRem>0 ){
  124375. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  124376. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  124377. int bUseHint = 0; /* True if attempting to append */
  124378. /* Search the %_segdir table for the absolute level with the smallest
  124379. ** relative level number that contains at least nMin segments, if any.
  124380. ** If one is found, set iAbsLevel to the absolute level number and
  124381. ** nSeg to nMin. If no level with at least nMin segments can be found,
  124382. ** set nSeg to -1.
  124383. */
  124384. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  124385. sqlite3_bind_int(pFindLevel, 1, nMin);
  124386. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  124387. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  124388. nSeg = nMin;
  124389. }else{
  124390. nSeg = -1;
  124391. }
  124392. rc = sqlite3_reset(pFindLevel);
  124393. /* If the hint read from the %_stat table is not empty, check if the
  124394. ** last entry in it specifies a relative level smaller than or equal
  124395. ** to the level identified by the block above (if any). If so, this
  124396. ** iteration of the loop will work on merging at the hinted level.
  124397. */
  124398. if( rc==SQLITE_OK && hint.n ){
  124399. int nHint = hint.n;
  124400. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  124401. int nHintSeg = 0; /* Hint number of segments */
  124402. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  124403. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  124404. iAbsLevel = iHintAbsLevel;
  124405. nSeg = nHintSeg;
  124406. bUseHint = 1;
  124407. bDirtyHint = 1;
  124408. }else{
  124409. /* This undoes the effect of the HintPop() above - so that no entry
  124410. ** is removed from the hint blob. */
  124411. hint.n = nHint;
  124412. }
  124413. }
  124414. /* If nSeg is less that zero, then there is no level with at least
  124415. ** nMin segments and no hint in the %_stat table. No work to do.
  124416. ** Exit early in this case. */
  124417. if( nSeg<0 ) break;
  124418. /* Open a cursor to iterate through the contents of the oldest nSeg
  124419. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  124420. ** the 'hint' parameters, it is possible that there are less than nSeg
  124421. ** segments available in level iAbsLevel. In this case, no work is
  124422. ** done on iAbsLevel - fall through to the next iteration of the loop
  124423. ** to start work on some other level. */
  124424. memset(pWriter, 0, nAlloc);
  124425. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  124426. if( rc==SQLITE_OK ){
  124427. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  124428. }
  124429. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  124430. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  124431. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  124432. ){
  124433. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  124434. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  124435. if( rc==SQLITE_OK ){
  124436. if( bUseHint && iIdx>0 ){
  124437. const char *zKey = pCsr->zTerm;
  124438. int nKey = pCsr->nTerm;
  124439. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  124440. }else{
  124441. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  124442. }
  124443. }
  124444. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  124445. fts3LogMerge(nSeg, iAbsLevel);
  124446. do {
  124447. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  124448. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  124449. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  124450. }while( rc==SQLITE_ROW );
  124451. /* Update or delete the input segments */
  124452. if( rc==SQLITE_OK ){
  124453. nRem -= (1 + pWriter->nWork);
  124454. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  124455. if( nSeg!=0 ){
  124456. bDirtyHint = 1;
  124457. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  124458. }
  124459. }
  124460. }
  124461. fts3IncrmergeRelease(p, pWriter, &rc);
  124462. }
  124463. sqlite3Fts3SegReaderFinish(pCsr);
  124464. }
  124465. /* Write the hint values into the %_stat table for the next incr-merger */
  124466. if( bDirtyHint && rc==SQLITE_OK ){
  124467. rc = fts3IncrmergeHintStore(p, &hint);
  124468. }
  124469. sqlite3_free(pWriter);
  124470. sqlite3_free(hint.a);
  124471. return rc;
  124472. }
  124473. /*
  124474. ** Convert the text beginning at *pz into an integer and return
  124475. ** its value. Advance *pz to point to the first character past
  124476. ** the integer.
  124477. */
  124478. static int fts3Getint(const char **pz){
  124479. const char *z = *pz;
  124480. int i = 0;
  124481. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  124482. *pz = z;
  124483. return i;
  124484. }
  124485. /*
  124486. ** Process statements of the form:
  124487. **
  124488. ** INSERT INTO table(table) VALUES('merge=A,B');
  124489. **
  124490. ** A and B are integers that decode to be the number of leaf pages
  124491. ** written for the merge, and the minimum number of segments on a level
  124492. ** before it will be selected for a merge, respectively.
  124493. */
  124494. static int fts3DoIncrmerge(
  124495. Fts3Table *p, /* FTS3 table handle */
  124496. const char *zParam /* Nul-terminated string containing "A,B" */
  124497. ){
  124498. int rc;
  124499. int nMin = (FTS3_MERGE_COUNT / 2);
  124500. int nMerge = 0;
  124501. const char *z = zParam;
  124502. /* Read the first integer value */
  124503. nMerge = fts3Getint(&z);
  124504. /* If the first integer value is followed by a ',', read the second
  124505. ** integer value. */
  124506. if( z[0]==',' && z[1]!='\0' ){
  124507. z++;
  124508. nMin = fts3Getint(&z);
  124509. }
  124510. if( z[0]!='\0' || nMin<2 ){
  124511. rc = SQLITE_ERROR;
  124512. }else{
  124513. rc = SQLITE_OK;
  124514. if( !p->bHasStat ){
  124515. assert( p->bFts4==0 );
  124516. sqlite3Fts3CreateStatTable(&rc, p);
  124517. }
  124518. if( rc==SQLITE_OK ){
  124519. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  124520. }
  124521. sqlite3Fts3SegmentsClose(p);
  124522. }
  124523. return rc;
  124524. }
  124525. /*
  124526. ** Process statements of the form:
  124527. **
  124528. ** INSERT INTO table(table) VALUES('automerge=X');
  124529. **
  124530. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  124531. ** turn it on. The setting is persistent.
  124532. */
  124533. static int fts3DoAutoincrmerge(
  124534. Fts3Table *p, /* FTS3 table handle */
  124535. const char *zParam /* Nul-terminated string containing boolean */
  124536. ){
  124537. int rc = SQLITE_OK;
  124538. sqlite3_stmt *pStmt = 0;
  124539. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  124540. if( !p->bHasStat ){
  124541. assert( p->bFts4==0 );
  124542. sqlite3Fts3CreateStatTable(&rc, p);
  124543. if( rc ) return rc;
  124544. }
  124545. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  124546. if( rc ) return rc;;
  124547. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  124548. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  124549. sqlite3_step(pStmt);
  124550. rc = sqlite3_reset(pStmt);
  124551. return rc;
  124552. }
  124553. /*
  124554. ** Return a 64-bit checksum for the FTS index entry specified by the
  124555. ** arguments to this function.
  124556. */
  124557. static u64 fts3ChecksumEntry(
  124558. const char *zTerm, /* Pointer to buffer containing term */
  124559. int nTerm, /* Size of zTerm in bytes */
  124560. int iLangid, /* Language id for current row */
  124561. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  124562. i64 iDocid, /* Docid for current row. */
  124563. int iCol, /* Column number */
  124564. int iPos /* Position */
  124565. ){
  124566. int i;
  124567. u64 ret = (u64)iDocid;
  124568. ret += (ret<<3) + iLangid;
  124569. ret += (ret<<3) + iIndex;
  124570. ret += (ret<<3) + iCol;
  124571. ret += (ret<<3) + iPos;
  124572. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  124573. return ret;
  124574. }
  124575. /*
  124576. ** Return a checksum of all entries in the FTS index that correspond to
  124577. ** language id iLangid. The checksum is calculated by XORing the checksums
  124578. ** of each individual entry (see fts3ChecksumEntry()) together.
  124579. **
  124580. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  124581. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  124582. ** return value is undefined in this case.
  124583. */
  124584. static u64 fts3ChecksumIndex(
  124585. Fts3Table *p, /* FTS3 table handle */
  124586. int iLangid, /* Language id to return cksum for */
  124587. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  124588. int *pRc /* OUT: Return code */
  124589. ){
  124590. Fts3SegFilter filter;
  124591. Fts3MultiSegReader csr;
  124592. int rc;
  124593. u64 cksum = 0;
  124594. assert( *pRc==SQLITE_OK );
  124595. memset(&filter, 0, sizeof(filter));
  124596. memset(&csr, 0, sizeof(csr));
  124597. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  124598. filter.flags |= FTS3_SEGMENT_SCAN;
  124599. rc = sqlite3Fts3SegReaderCursor(
  124600. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  124601. );
  124602. if( rc==SQLITE_OK ){
  124603. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  124604. }
  124605. if( rc==SQLITE_OK ){
  124606. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  124607. char *pCsr = csr.aDoclist;
  124608. char *pEnd = &pCsr[csr.nDoclist];
  124609. i64 iDocid = 0;
  124610. i64 iCol = 0;
  124611. i64 iPos = 0;
  124612. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  124613. while( pCsr<pEnd ){
  124614. i64 iVal = 0;
  124615. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  124616. if( pCsr<pEnd ){
  124617. if( iVal==0 || iVal==1 ){
  124618. iCol = 0;
  124619. iPos = 0;
  124620. if( iVal ){
  124621. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  124622. }else{
  124623. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  124624. iDocid += iVal;
  124625. }
  124626. }else{
  124627. iPos += (iVal - 2);
  124628. cksum = cksum ^ fts3ChecksumEntry(
  124629. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  124630. (int)iCol, (int)iPos
  124631. );
  124632. }
  124633. }
  124634. }
  124635. }
  124636. }
  124637. sqlite3Fts3SegReaderFinish(&csr);
  124638. *pRc = rc;
  124639. return cksum;
  124640. }
  124641. /*
  124642. ** Check if the contents of the FTS index match the current contents of the
  124643. ** content table. If no error occurs and the contents do match, set *pbOk
  124644. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  124645. ** to false before returning.
  124646. **
  124647. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  124648. ** code. The final value of *pbOk is undefined in this case.
  124649. */
  124650. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  124651. int rc = SQLITE_OK; /* Return code */
  124652. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  124653. u64 cksum2 = 0; /* Checksum based on %_content contents */
  124654. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  124655. /* This block calculates the checksum according to the FTS index. */
  124656. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  124657. if( rc==SQLITE_OK ){
  124658. int rc2;
  124659. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  124660. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  124661. int iLangid = sqlite3_column_int(pAllLangid, 0);
  124662. int i;
  124663. for(i=0; i<p->nIndex; i++){
  124664. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  124665. }
  124666. }
  124667. rc2 = sqlite3_reset(pAllLangid);
  124668. if( rc==SQLITE_OK ) rc = rc2;
  124669. }
  124670. /* This block calculates the checksum according to the %_content table */
  124671. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  124672. if( rc==SQLITE_OK ){
  124673. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  124674. sqlite3_stmt *pStmt = 0;
  124675. char *zSql;
  124676. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  124677. if( !zSql ){
  124678. rc = SQLITE_NOMEM;
  124679. }else{
  124680. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  124681. sqlite3_free(zSql);
  124682. }
  124683. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  124684. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  124685. int iLang = langidFromSelect(p, pStmt);
  124686. int iCol;
  124687. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  124688. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  124689. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  124690. sqlite3_tokenizer_cursor *pT = 0;
  124691. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  124692. while( rc==SQLITE_OK ){
  124693. char const *zToken; /* Buffer containing token */
  124694. int nToken = 0; /* Number of bytes in token */
  124695. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  124696. int iPos = 0; /* Position of token in zText */
  124697. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  124698. if( rc==SQLITE_OK ){
  124699. int i;
  124700. cksum2 = cksum2 ^ fts3ChecksumEntry(
  124701. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  124702. );
  124703. for(i=1; i<p->nIndex; i++){
  124704. if( p->aIndex[i].nPrefix<=nToken ){
  124705. cksum2 = cksum2 ^ fts3ChecksumEntry(
  124706. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  124707. );
  124708. }
  124709. }
  124710. }
  124711. }
  124712. if( pT ) pModule->xClose(pT);
  124713. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  124714. }
  124715. }
  124716. sqlite3_finalize(pStmt);
  124717. }
  124718. *pbOk = (cksum1==cksum2);
  124719. return rc;
  124720. }
  124721. /*
  124722. ** Run the integrity-check. If no error occurs and the current contents of
  124723. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  124724. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  124725. **
  124726. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  124727. ** error code.
  124728. **
  124729. ** The integrity-check works as follows. For each token and indexed token
  124730. ** prefix in the document set, a 64-bit checksum is calculated (by code
  124731. ** in fts3ChecksumEntry()) based on the following:
  124732. **
  124733. ** + The index number (0 for the main index, 1 for the first prefix
  124734. ** index etc.),
  124735. ** + The token (or token prefix) text itself,
  124736. ** + The language-id of the row it appears in,
  124737. ** + The docid of the row it appears in,
  124738. ** + The column it appears in, and
  124739. ** + The tokens position within that column.
  124740. **
  124741. ** The checksums for all entries in the index are XORed together to create
  124742. ** a single checksum for the entire index.
  124743. **
  124744. ** The integrity-check code calculates the same checksum in two ways:
  124745. **
  124746. ** 1. By scanning the contents of the FTS index, and
  124747. ** 2. By scanning and tokenizing the content table.
  124748. **
  124749. ** If the two checksums are identical, the integrity-check is deemed to have
  124750. ** passed.
  124751. */
  124752. static int fts3DoIntegrityCheck(
  124753. Fts3Table *p /* FTS3 table handle */
  124754. ){
  124755. int rc;
  124756. int bOk = 0;
  124757. rc = fts3IntegrityCheck(p, &bOk);
  124758. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  124759. return rc;
  124760. }
  124761. /*
  124762. ** Handle a 'special' INSERT of the form:
  124763. **
  124764. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  124765. **
  124766. ** Argument pVal contains the result of <expr>. Currently the only
  124767. ** meaningful value to insert is the text 'optimize'.
  124768. */
  124769. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  124770. int rc; /* Return Code */
  124771. const char *zVal = (const char *)sqlite3_value_text(pVal);
  124772. int nVal = sqlite3_value_bytes(pVal);
  124773. if( !zVal ){
  124774. return SQLITE_NOMEM;
  124775. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  124776. rc = fts3DoOptimize(p, 0);
  124777. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  124778. rc = fts3DoRebuild(p);
  124779. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  124780. rc = fts3DoIntegrityCheck(p);
  124781. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  124782. rc = fts3DoIncrmerge(p, &zVal[6]);
  124783. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  124784. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  124785. #ifdef SQLITE_TEST
  124786. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  124787. p->nNodeSize = atoi(&zVal[9]);
  124788. rc = SQLITE_OK;
  124789. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  124790. p->nMaxPendingData = atoi(&zVal[11]);
  124791. rc = SQLITE_OK;
  124792. #endif
  124793. }else{
  124794. rc = SQLITE_ERROR;
  124795. }
  124796. return rc;
  124797. }
  124798. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  124799. /*
  124800. ** Delete all cached deferred doclists. Deferred doclists are cached
  124801. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  124802. */
  124803. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  124804. Fts3DeferredToken *pDef;
  124805. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  124806. fts3PendingListDelete(pDef->pList);
  124807. pDef->pList = 0;
  124808. }
  124809. }
  124810. /*
  124811. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  124812. ** this list using sqlite3Fts3DeferToken().
  124813. */
  124814. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  124815. Fts3DeferredToken *pDef;
  124816. Fts3DeferredToken *pNext;
  124817. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  124818. pNext = pDef->pNext;
  124819. fts3PendingListDelete(pDef->pList);
  124820. sqlite3_free(pDef);
  124821. }
  124822. pCsr->pDeferred = 0;
  124823. }
  124824. /*
  124825. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  124826. ** based on the row that pCsr currently points to.
  124827. **
  124828. ** A deferred-doclist is like any other doclist with position information
  124829. ** included, except that it only contains entries for a single row of the
  124830. ** table, not for all rows.
  124831. */
  124832. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  124833. int rc = SQLITE_OK; /* Return code */
  124834. if( pCsr->pDeferred ){
  124835. int i; /* Used to iterate through table columns */
  124836. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  124837. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  124838. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  124839. sqlite3_tokenizer *pT = p->pTokenizer;
  124840. sqlite3_tokenizer_module const *pModule = pT->pModule;
  124841. assert( pCsr->isRequireSeek==0 );
  124842. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  124843. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  124844. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  124845. sqlite3_tokenizer_cursor *pTC = 0;
  124846. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  124847. while( rc==SQLITE_OK ){
  124848. char const *zToken; /* Buffer containing token */
  124849. int nToken = 0; /* Number of bytes in token */
  124850. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  124851. int iPos = 0; /* Position of token in zText */
  124852. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  124853. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  124854. Fts3PhraseToken *pPT = pDef->pToken;
  124855. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  124856. && (pPT->bFirst==0 || iPos==0)
  124857. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  124858. && (0==memcmp(zToken, pPT->z, pPT->n))
  124859. ){
  124860. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  124861. }
  124862. }
  124863. }
  124864. if( pTC ) pModule->xClose(pTC);
  124865. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  124866. }
  124867. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  124868. if( pDef->pList ){
  124869. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  124870. }
  124871. }
  124872. }
  124873. return rc;
  124874. }
  124875. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  124876. Fts3DeferredToken *p,
  124877. char **ppData,
  124878. int *pnData
  124879. ){
  124880. char *pRet;
  124881. int nSkip;
  124882. sqlite3_int64 dummy;
  124883. *ppData = 0;
  124884. *pnData = 0;
  124885. if( p->pList==0 ){
  124886. return SQLITE_OK;
  124887. }
  124888. pRet = (char *)sqlite3_malloc(p->pList->nData);
  124889. if( !pRet ) return SQLITE_NOMEM;
  124890. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  124891. *pnData = p->pList->nData - nSkip;
  124892. *ppData = pRet;
  124893. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  124894. return SQLITE_OK;
  124895. }
  124896. /*
  124897. ** Add an entry for token pToken to the pCsr->pDeferred list.
  124898. */
  124899. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  124900. Fts3Cursor *pCsr, /* Fts3 table cursor */
  124901. Fts3PhraseToken *pToken, /* Token to defer */
  124902. int iCol /* Column that token must appear in (or -1) */
  124903. ){
  124904. Fts3DeferredToken *pDeferred;
  124905. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  124906. if( !pDeferred ){
  124907. return SQLITE_NOMEM;
  124908. }
  124909. memset(pDeferred, 0, sizeof(*pDeferred));
  124910. pDeferred->pToken = pToken;
  124911. pDeferred->pNext = pCsr->pDeferred;
  124912. pDeferred->iCol = iCol;
  124913. pCsr->pDeferred = pDeferred;
  124914. assert( pToken->pDeferred==0 );
  124915. pToken->pDeferred = pDeferred;
  124916. return SQLITE_OK;
  124917. }
  124918. #endif
  124919. /*
  124920. ** SQLite value pRowid contains the rowid of a row that may or may not be
  124921. ** present in the FTS3 table. If it is, delete it and adjust the contents
  124922. ** of subsiduary data structures accordingly.
  124923. */
  124924. static int fts3DeleteByRowid(
  124925. Fts3Table *p,
  124926. sqlite3_value *pRowid,
  124927. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  124928. u32 *aSzDel
  124929. ){
  124930. int rc = SQLITE_OK; /* Return code */
  124931. int bFound = 0; /* True if *pRowid really is in the table */
  124932. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  124933. if( bFound && rc==SQLITE_OK ){
  124934. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  124935. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  124936. if( rc==SQLITE_OK ){
  124937. if( isEmpty ){
  124938. /* Deleting this row means the whole table is empty. In this case
  124939. ** delete the contents of all three tables and throw away any
  124940. ** data in the pendingTerms hash table. */
  124941. rc = fts3DeleteAll(p, 1);
  124942. *pnChng = 0;
  124943. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  124944. }else{
  124945. *pnChng = *pnChng - 1;
  124946. if( p->zContentTbl==0 ){
  124947. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  124948. }
  124949. if( p->bHasDocsize ){
  124950. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  124951. }
  124952. }
  124953. }
  124954. }
  124955. return rc;
  124956. }
  124957. /*
  124958. ** This function does the work for the xUpdate method of FTS3 virtual
  124959. ** tables. The schema of the virtual table being:
  124960. **
  124961. ** CREATE TABLE <table name>(
  124962. ** <user columns>,
  124963. ** <table name> HIDDEN,
  124964. ** docid HIDDEN,
  124965. ** <langid> HIDDEN
  124966. ** );
  124967. **
  124968. **
  124969. */
  124970. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  124971. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  124972. int nArg, /* Size of argument array */
  124973. sqlite3_value **apVal, /* Array of arguments */
  124974. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  124975. ){
  124976. Fts3Table *p = (Fts3Table *)pVtab;
  124977. int rc = SQLITE_OK; /* Return Code */
  124978. int isRemove = 0; /* True for an UPDATE or DELETE */
  124979. u32 *aSzIns = 0; /* Sizes of inserted documents */
  124980. u32 *aSzDel = 0; /* Sizes of deleted documents */
  124981. int nChng = 0; /* Net change in number of documents */
  124982. int bInsertDone = 0;
  124983. assert( p->pSegments==0 );
  124984. assert(
  124985. nArg==1 /* DELETE operations */
  124986. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  124987. );
  124988. /* Check for a "special" INSERT operation. One of the form:
  124989. **
  124990. ** INSERT INTO xyz(xyz) VALUES('command');
  124991. */
  124992. if( nArg>1
  124993. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  124994. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  124995. ){
  124996. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  124997. goto update_out;
  124998. }
  124999. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  125000. rc = SQLITE_CONSTRAINT;
  125001. goto update_out;
  125002. }
  125003. /* Allocate space to hold the change in document sizes */
  125004. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  125005. if( aSzDel==0 ){
  125006. rc = SQLITE_NOMEM;
  125007. goto update_out;
  125008. }
  125009. aSzIns = &aSzDel[p->nColumn+1];
  125010. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  125011. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  125012. ** value, then this operation requires constraint handling.
  125013. **
  125014. ** If the on-conflict mode is REPLACE, this means that the existing row
  125015. ** should be deleted from the database before inserting the new row. Or,
  125016. ** if the on-conflict mode is other than REPLACE, then this method must
  125017. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  125018. ** modify the database file.
  125019. */
  125020. if( nArg>1 && p->zContentTbl==0 ){
  125021. /* Find the value object that holds the new rowid value. */
  125022. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  125023. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  125024. pNewRowid = apVal[1];
  125025. }
  125026. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  125027. sqlite3_value_type(apVal[0])==SQLITE_NULL
  125028. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  125029. )){
  125030. /* The new rowid is not NULL (in this case the rowid will be
  125031. ** automatically assigned and there is no chance of a conflict), and
  125032. ** the statement is either an INSERT or an UPDATE that modifies the
  125033. ** rowid column. So if the conflict mode is REPLACE, then delete any
  125034. ** existing row with rowid=pNewRowid.
  125035. **
  125036. ** Or, if the conflict mode is not REPLACE, insert the new record into
  125037. ** the %_content table. If we hit the duplicate rowid constraint (or any
  125038. ** other error) while doing so, return immediately.
  125039. **
  125040. ** This branch may also run if pNewRowid contains a value that cannot
  125041. ** be losslessly converted to an integer. In this case, the eventual
  125042. ** call to fts3InsertData() (either just below or further on in this
  125043. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  125044. ** invoked, it will delete zero rows (since no row will have
  125045. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  125046. */
  125047. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  125048. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  125049. }else{
  125050. rc = fts3InsertData(p, apVal, pRowid);
  125051. bInsertDone = 1;
  125052. }
  125053. }
  125054. }
  125055. if( rc!=SQLITE_OK ){
  125056. goto update_out;
  125057. }
  125058. /* If this is a DELETE or UPDATE operation, remove the old record. */
  125059. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  125060. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  125061. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  125062. isRemove = 1;
  125063. }
  125064. /* If this is an INSERT or UPDATE operation, insert the new record. */
  125065. if( nArg>1 && rc==SQLITE_OK ){
  125066. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  125067. if( bInsertDone==0 ){
  125068. rc = fts3InsertData(p, apVal, pRowid);
  125069. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  125070. rc = FTS_CORRUPT_VTAB;
  125071. }
  125072. }
  125073. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  125074. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  125075. }
  125076. if( rc==SQLITE_OK ){
  125077. assert( p->iPrevDocid==*pRowid );
  125078. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  125079. }
  125080. if( p->bHasDocsize ){
  125081. fts3InsertDocsize(&rc, p, aSzIns);
  125082. }
  125083. nChng++;
  125084. }
  125085. if( p->bFts4 ){
  125086. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  125087. }
  125088. update_out:
  125089. sqlite3_free(aSzDel);
  125090. sqlite3Fts3SegmentsClose(p);
  125091. return rc;
  125092. }
  125093. /*
  125094. ** Flush any data in the pending-terms hash table to disk. If successful,
  125095. ** merge all segments in the database (including the new segment, if
  125096. ** there was any data to flush) into a single segment.
  125097. */
  125098. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  125099. int rc;
  125100. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  125101. if( rc==SQLITE_OK ){
  125102. rc = fts3DoOptimize(p, 1);
  125103. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  125104. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  125105. if( rc2!=SQLITE_OK ) rc = rc2;
  125106. }else{
  125107. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  125108. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  125109. }
  125110. }
  125111. sqlite3Fts3SegmentsClose(p);
  125112. return rc;
  125113. }
  125114. #endif
  125115. /************** End of fts3_write.c ******************************************/
  125116. /************** Begin file fts3_snippet.c ************************************/
  125117. /*
  125118. ** 2009 Oct 23
  125119. **
  125120. ** The author disclaims copyright to this source code. In place of
  125121. ** a legal notice, here is a blessing:
  125122. **
  125123. ** May you do good and not evil.
  125124. ** May you find forgiveness for yourself and forgive others.
  125125. ** May you share freely, never taking more than you give.
  125126. **
  125127. ******************************************************************************
  125128. */
  125129. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125130. /* #include <string.h> */
  125131. /* #include <assert.h> */
  125132. /*
  125133. ** Characters that may appear in the second argument to matchinfo().
  125134. */
  125135. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  125136. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  125137. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  125138. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  125139. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  125140. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  125141. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  125142. /*
  125143. ** The default value for the second argument to matchinfo().
  125144. */
  125145. #define FTS3_MATCHINFO_DEFAULT "pcx"
  125146. /*
  125147. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  125148. ** Fts3Expr.aDoclist[]/nDoclist.
  125149. */
  125150. typedef struct LoadDoclistCtx LoadDoclistCtx;
  125151. struct LoadDoclistCtx {
  125152. Fts3Cursor *pCsr; /* FTS3 Cursor */
  125153. int nPhrase; /* Number of phrases seen so far */
  125154. int nToken; /* Number of tokens seen so far */
  125155. };
  125156. /*
  125157. ** The following types are used as part of the implementation of the
  125158. ** fts3BestSnippet() routine.
  125159. */
  125160. typedef struct SnippetIter SnippetIter;
  125161. typedef struct SnippetPhrase SnippetPhrase;
  125162. typedef struct SnippetFragment SnippetFragment;
  125163. struct SnippetIter {
  125164. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  125165. int iCol; /* Extract snippet from this column */
  125166. int nSnippet; /* Requested snippet length (in tokens) */
  125167. int nPhrase; /* Number of phrases in query */
  125168. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  125169. int iCurrent; /* First token of current snippet */
  125170. };
  125171. struct SnippetPhrase {
  125172. int nToken; /* Number of tokens in phrase */
  125173. char *pList; /* Pointer to start of phrase position list */
  125174. int iHead; /* Next value in position list */
  125175. char *pHead; /* Position list data following iHead */
  125176. int iTail; /* Next value in trailing position list */
  125177. char *pTail; /* Position list data following iTail */
  125178. };
  125179. struct SnippetFragment {
  125180. int iCol; /* Column snippet is extracted from */
  125181. int iPos; /* Index of first token in snippet */
  125182. u64 covered; /* Mask of query phrases covered */
  125183. u64 hlmask; /* Mask of snippet terms to highlight */
  125184. };
  125185. /*
  125186. ** This type is used as an fts3ExprIterate() context object while
  125187. ** accumulating the data returned by the matchinfo() function.
  125188. */
  125189. typedef struct MatchInfo MatchInfo;
  125190. struct MatchInfo {
  125191. Fts3Cursor *pCursor; /* FTS3 Cursor */
  125192. int nCol; /* Number of columns in table */
  125193. int nPhrase; /* Number of matchable phrases in query */
  125194. sqlite3_int64 nDoc; /* Number of docs in database */
  125195. u32 *aMatchinfo; /* Pre-allocated buffer */
  125196. };
  125197. /*
  125198. ** The snippet() and offsets() functions both return text values. An instance
  125199. ** of the following structure is used to accumulate those values while the
  125200. ** functions are running. See fts3StringAppend() for details.
  125201. */
  125202. typedef struct StrBuffer StrBuffer;
  125203. struct StrBuffer {
  125204. char *z; /* Pointer to buffer containing string */
  125205. int n; /* Length of z in bytes (excl. nul-term) */
  125206. int nAlloc; /* Allocated size of buffer z in bytes */
  125207. };
  125208. /*
  125209. ** This function is used to help iterate through a position-list. A position
  125210. ** list is a list of unique integers, sorted from smallest to largest. Each
  125211. ** element of the list is represented by an FTS3 varint that takes the value
  125212. ** of the difference between the current element and the previous one plus
  125213. ** two. For example, to store the position-list:
  125214. **
  125215. ** 4 9 113
  125216. **
  125217. ** the three varints:
  125218. **
  125219. ** 6 7 106
  125220. **
  125221. ** are encoded.
  125222. **
  125223. ** When this function is called, *pp points to the start of an element of
  125224. ** the list. *piPos contains the value of the previous entry in the list.
  125225. ** After it returns, *piPos contains the value of the next element of the
  125226. ** list and *pp is advanced to the following varint.
  125227. */
  125228. static void fts3GetDeltaPosition(char **pp, int *piPos){
  125229. int iVal;
  125230. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  125231. *piPos += (iVal-2);
  125232. }
  125233. /*
  125234. ** Helper function for fts3ExprIterate() (see below).
  125235. */
  125236. static int fts3ExprIterate2(
  125237. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  125238. int *piPhrase, /* Pointer to phrase counter */
  125239. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  125240. void *pCtx /* Second argument to pass to callback */
  125241. ){
  125242. int rc; /* Return code */
  125243. int eType = pExpr->eType; /* Type of expression node pExpr */
  125244. if( eType!=FTSQUERY_PHRASE ){
  125245. assert( pExpr->pLeft && pExpr->pRight );
  125246. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  125247. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  125248. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  125249. }
  125250. }else{
  125251. rc = x(pExpr, *piPhrase, pCtx);
  125252. (*piPhrase)++;
  125253. }
  125254. return rc;
  125255. }
  125256. /*
  125257. ** Iterate through all phrase nodes in an FTS3 query, except those that
  125258. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  125259. ** For each phrase node found, the supplied callback function is invoked.
  125260. **
  125261. ** If the callback function returns anything other than SQLITE_OK,
  125262. ** the iteration is abandoned and the error code returned immediately.
  125263. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  125264. ** all eligible phrase nodes.
  125265. */
  125266. static int fts3ExprIterate(
  125267. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  125268. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  125269. void *pCtx /* Second argument to pass to callback */
  125270. ){
  125271. int iPhrase = 0; /* Variable used as the phrase counter */
  125272. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  125273. }
  125274. /*
  125275. ** This is an fts3ExprIterate() callback used while loading the doclists
  125276. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  125277. ** fts3ExprLoadDoclists().
  125278. */
  125279. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  125280. int rc = SQLITE_OK;
  125281. Fts3Phrase *pPhrase = pExpr->pPhrase;
  125282. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  125283. UNUSED_PARAMETER(iPhrase);
  125284. p->nPhrase++;
  125285. p->nToken += pPhrase->nToken;
  125286. return rc;
  125287. }
  125288. /*
  125289. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  125290. ** pCsr.
  125291. **
  125292. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  125293. ** phrases in the expression (all phrases except those directly or
  125294. ** indirectly descended from the right-hand-side of a NOT operator). If
  125295. ** pnToken is not NULL, then it is set to the number of tokens in all
  125296. ** matchable phrases of the expression.
  125297. */
  125298. static int fts3ExprLoadDoclists(
  125299. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  125300. int *pnPhrase, /* OUT: Number of phrases in query */
  125301. int *pnToken /* OUT: Number of tokens in query */
  125302. ){
  125303. int rc; /* Return Code */
  125304. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  125305. sCtx.pCsr = pCsr;
  125306. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  125307. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  125308. if( pnToken ) *pnToken = sCtx.nToken;
  125309. return rc;
  125310. }
  125311. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  125312. (*(int *)ctx)++;
  125313. UNUSED_PARAMETER(pExpr);
  125314. UNUSED_PARAMETER(iPhrase);
  125315. return SQLITE_OK;
  125316. }
  125317. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  125318. int nPhrase = 0;
  125319. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  125320. return nPhrase;
  125321. }
  125322. /*
  125323. ** Advance the position list iterator specified by the first two
  125324. ** arguments so that it points to the first element with a value greater
  125325. ** than or equal to parameter iNext.
  125326. */
  125327. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  125328. char *pIter = *ppIter;
  125329. if( pIter ){
  125330. int iIter = *piIter;
  125331. while( iIter<iNext ){
  125332. if( 0==(*pIter & 0xFE) ){
  125333. iIter = -1;
  125334. pIter = 0;
  125335. break;
  125336. }
  125337. fts3GetDeltaPosition(&pIter, &iIter);
  125338. }
  125339. *piIter = iIter;
  125340. *ppIter = pIter;
  125341. }
  125342. }
  125343. /*
  125344. ** Advance the snippet iterator to the next candidate snippet.
  125345. */
  125346. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  125347. int i; /* Loop counter */
  125348. if( pIter->iCurrent<0 ){
  125349. /* The SnippetIter object has just been initialized. The first snippet
  125350. ** candidate always starts at offset 0 (even if this candidate has a
  125351. ** score of 0.0).
  125352. */
  125353. pIter->iCurrent = 0;
  125354. /* Advance the 'head' iterator of each phrase to the first offset that
  125355. ** is greater than or equal to (iNext+nSnippet).
  125356. */
  125357. for(i=0; i<pIter->nPhrase; i++){
  125358. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  125359. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  125360. }
  125361. }else{
  125362. int iStart;
  125363. int iEnd = 0x7FFFFFFF;
  125364. for(i=0; i<pIter->nPhrase; i++){
  125365. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  125366. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  125367. iEnd = pPhrase->iHead;
  125368. }
  125369. }
  125370. if( iEnd==0x7FFFFFFF ){
  125371. return 1;
  125372. }
  125373. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  125374. for(i=0; i<pIter->nPhrase; i++){
  125375. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  125376. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  125377. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  125378. }
  125379. }
  125380. return 0;
  125381. }
  125382. /*
  125383. ** Retrieve information about the current candidate snippet of snippet
  125384. ** iterator pIter.
  125385. */
  125386. static void fts3SnippetDetails(
  125387. SnippetIter *pIter, /* Snippet iterator */
  125388. u64 mCovered, /* Bitmask of phrases already covered */
  125389. int *piToken, /* OUT: First token of proposed snippet */
  125390. int *piScore, /* OUT: "Score" for this snippet */
  125391. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  125392. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  125393. ){
  125394. int iStart = pIter->iCurrent; /* First token of snippet */
  125395. int iScore = 0; /* Score of this snippet */
  125396. int i; /* Loop counter */
  125397. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  125398. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  125399. for(i=0; i<pIter->nPhrase; i++){
  125400. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  125401. if( pPhrase->pTail ){
  125402. char *pCsr = pPhrase->pTail;
  125403. int iCsr = pPhrase->iTail;
  125404. while( iCsr<(iStart+pIter->nSnippet) ){
  125405. int j;
  125406. u64 mPhrase = (u64)1 << i;
  125407. u64 mPos = (u64)1 << (iCsr - iStart);
  125408. assert( iCsr>=iStart );
  125409. if( (mCover|mCovered)&mPhrase ){
  125410. iScore++;
  125411. }else{
  125412. iScore += 1000;
  125413. }
  125414. mCover |= mPhrase;
  125415. for(j=0; j<pPhrase->nToken; j++){
  125416. mHighlight |= (mPos>>j);
  125417. }
  125418. if( 0==(*pCsr & 0x0FE) ) break;
  125419. fts3GetDeltaPosition(&pCsr, &iCsr);
  125420. }
  125421. }
  125422. }
  125423. /* Set the output variables before returning. */
  125424. *piToken = iStart;
  125425. *piScore = iScore;
  125426. *pmCover = mCover;
  125427. *pmHighlight = mHighlight;
  125428. }
  125429. /*
  125430. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  125431. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  125432. */
  125433. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  125434. SnippetIter *p = (SnippetIter *)ctx;
  125435. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  125436. char *pCsr;
  125437. int rc;
  125438. pPhrase->nToken = pExpr->pPhrase->nToken;
  125439. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  125440. assert( rc==SQLITE_OK || pCsr==0 );
  125441. if( pCsr ){
  125442. int iFirst = 0;
  125443. pPhrase->pList = pCsr;
  125444. fts3GetDeltaPosition(&pCsr, &iFirst);
  125445. assert( iFirst>=0 );
  125446. pPhrase->pHead = pCsr;
  125447. pPhrase->pTail = pCsr;
  125448. pPhrase->iHead = iFirst;
  125449. pPhrase->iTail = iFirst;
  125450. }else{
  125451. assert( rc!=SQLITE_OK || (
  125452. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  125453. ));
  125454. }
  125455. return rc;
  125456. }
  125457. /*
  125458. ** Select the fragment of text consisting of nFragment contiguous tokens
  125459. ** from column iCol that represent the "best" snippet. The best snippet
  125460. ** is the snippet with the highest score, where scores are calculated
  125461. ** by adding:
  125462. **
  125463. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  125464. **
  125465. ** (b) +1000 points for the first occurrence of each matchable phrase in
  125466. ** the snippet for which the corresponding mCovered bit is not set.
  125467. **
  125468. ** The selected snippet parameters are stored in structure *pFragment before
  125469. ** returning. The score of the selected snippet is stored in *piScore
  125470. ** before returning.
  125471. */
  125472. static int fts3BestSnippet(
  125473. int nSnippet, /* Desired snippet length */
  125474. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  125475. int iCol, /* Index of column to create snippet from */
  125476. u64 mCovered, /* Mask of phrases already covered */
  125477. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  125478. SnippetFragment *pFragment, /* OUT: Best snippet found */
  125479. int *piScore /* OUT: Score of snippet pFragment */
  125480. ){
  125481. int rc; /* Return Code */
  125482. int nList; /* Number of phrases in expression */
  125483. SnippetIter sIter; /* Iterates through snippet candidates */
  125484. int nByte; /* Number of bytes of space to allocate */
  125485. int iBestScore = -1; /* Best snippet score found so far */
  125486. int i; /* Loop counter */
  125487. memset(&sIter, 0, sizeof(sIter));
  125488. /* Iterate through the phrases in the expression to count them. The same
  125489. ** callback makes sure the doclists are loaded for each phrase.
  125490. */
  125491. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  125492. if( rc!=SQLITE_OK ){
  125493. return rc;
  125494. }
  125495. /* Now that it is known how many phrases there are, allocate and zero
  125496. ** the required space using malloc().
  125497. */
  125498. nByte = sizeof(SnippetPhrase) * nList;
  125499. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  125500. if( !sIter.aPhrase ){
  125501. return SQLITE_NOMEM;
  125502. }
  125503. memset(sIter.aPhrase, 0, nByte);
  125504. /* Initialize the contents of the SnippetIter object. Then iterate through
  125505. ** the set of phrases in the expression to populate the aPhrase[] array.
  125506. */
  125507. sIter.pCsr = pCsr;
  125508. sIter.iCol = iCol;
  125509. sIter.nSnippet = nSnippet;
  125510. sIter.nPhrase = nList;
  125511. sIter.iCurrent = -1;
  125512. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  125513. /* Set the *pmSeen output variable. */
  125514. for(i=0; i<nList; i++){
  125515. if( sIter.aPhrase[i].pHead ){
  125516. *pmSeen |= (u64)1 << i;
  125517. }
  125518. }
  125519. /* Loop through all candidate snippets. Store the best snippet in
  125520. ** *pFragment. Store its associated 'score' in iBestScore.
  125521. */
  125522. pFragment->iCol = iCol;
  125523. while( !fts3SnippetNextCandidate(&sIter) ){
  125524. int iPos;
  125525. int iScore;
  125526. u64 mCover;
  125527. u64 mHighlight;
  125528. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  125529. assert( iScore>=0 );
  125530. if( iScore>iBestScore ){
  125531. pFragment->iPos = iPos;
  125532. pFragment->hlmask = mHighlight;
  125533. pFragment->covered = mCover;
  125534. iBestScore = iScore;
  125535. }
  125536. }
  125537. sqlite3_free(sIter.aPhrase);
  125538. *piScore = iBestScore;
  125539. return SQLITE_OK;
  125540. }
  125541. /*
  125542. ** Append a string to the string-buffer passed as the first argument.
  125543. **
  125544. ** If nAppend is negative, then the length of the string zAppend is
  125545. ** determined using strlen().
  125546. */
  125547. static int fts3StringAppend(
  125548. StrBuffer *pStr, /* Buffer to append to */
  125549. const char *zAppend, /* Pointer to data to append to buffer */
  125550. int nAppend /* Size of zAppend in bytes (or -1) */
  125551. ){
  125552. if( nAppend<0 ){
  125553. nAppend = (int)strlen(zAppend);
  125554. }
  125555. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  125556. ** to grow the buffer until so that it is big enough to accomadate the
  125557. ** appended data.
  125558. */
  125559. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  125560. int nAlloc = pStr->nAlloc+nAppend+100;
  125561. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  125562. if( !zNew ){
  125563. return SQLITE_NOMEM;
  125564. }
  125565. pStr->z = zNew;
  125566. pStr->nAlloc = nAlloc;
  125567. }
  125568. /* Append the data to the string buffer. */
  125569. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  125570. pStr->n += nAppend;
  125571. pStr->z[pStr->n] = '\0';
  125572. return SQLITE_OK;
  125573. }
  125574. /*
  125575. ** The fts3BestSnippet() function often selects snippets that end with a
  125576. ** query term. That is, the final term of the snippet is always a term
  125577. ** that requires highlighting. For example, if 'X' is a highlighted term
  125578. ** and '.' is a non-highlighted term, BestSnippet() may select:
  125579. **
  125580. ** ........X.....X
  125581. **
  125582. ** This function "shifts" the beginning of the snippet forward in the
  125583. ** document so that there are approximately the same number of
  125584. ** non-highlighted terms to the right of the final highlighted term as there
  125585. ** are to the left of the first highlighted term. For example, to this:
  125586. **
  125587. ** ....X.....X....
  125588. **
  125589. ** This is done as part of extracting the snippet text, not when selecting
  125590. ** the snippet. Snippet selection is done based on doclists only, so there
  125591. ** is no way for fts3BestSnippet() to know whether or not the document
  125592. ** actually contains terms that follow the final highlighted term.
  125593. */
  125594. static int fts3SnippetShift(
  125595. Fts3Table *pTab, /* FTS3 table snippet comes from */
  125596. int iLangid, /* Language id to use in tokenizing */
  125597. int nSnippet, /* Number of tokens desired for snippet */
  125598. const char *zDoc, /* Document text to extract snippet from */
  125599. int nDoc, /* Size of buffer zDoc in bytes */
  125600. int *piPos, /* IN/OUT: First token of snippet */
  125601. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  125602. ){
  125603. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  125604. if( hlmask ){
  125605. int nLeft; /* Tokens to the left of first highlight */
  125606. int nRight; /* Tokens to the right of last highlight */
  125607. int nDesired; /* Ideal number of tokens to shift forward */
  125608. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  125609. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  125610. nDesired = (nLeft-nRight)/2;
  125611. /* Ideally, the start of the snippet should be pushed forward in the
  125612. ** document nDesired tokens. This block checks if there are actually
  125613. ** nDesired tokens to the right of the snippet. If so, *piPos and
  125614. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  125615. ** right. Otherwise, the snippet is shifted by the number of tokens
  125616. ** available.
  125617. */
  125618. if( nDesired>0 ){
  125619. int nShift; /* Number of tokens to shift snippet by */
  125620. int iCurrent = 0; /* Token counter */
  125621. int rc; /* Return Code */
  125622. sqlite3_tokenizer_module *pMod;
  125623. sqlite3_tokenizer_cursor *pC;
  125624. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  125625. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  125626. ** or more tokens in zDoc/nDoc.
  125627. */
  125628. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  125629. if( rc!=SQLITE_OK ){
  125630. return rc;
  125631. }
  125632. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  125633. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  125634. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  125635. }
  125636. pMod->xClose(pC);
  125637. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  125638. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  125639. assert( nShift<=nDesired );
  125640. if( nShift>0 ){
  125641. *piPos += nShift;
  125642. *pHlmask = hlmask >> nShift;
  125643. }
  125644. }
  125645. }
  125646. return SQLITE_OK;
  125647. }
  125648. /*
  125649. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  125650. ** append it to string buffer pOut.
  125651. */
  125652. static int fts3SnippetText(
  125653. Fts3Cursor *pCsr, /* FTS3 Cursor */
  125654. SnippetFragment *pFragment, /* Snippet to extract */
  125655. int iFragment, /* Fragment number */
  125656. int isLast, /* True for final fragment in snippet */
  125657. int nSnippet, /* Number of tokens in extracted snippet */
  125658. const char *zOpen, /* String inserted before highlighted term */
  125659. const char *zClose, /* String inserted after highlighted term */
  125660. const char *zEllipsis, /* String inserted between snippets */
  125661. StrBuffer *pOut /* Write output here */
  125662. ){
  125663. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125664. int rc; /* Return code */
  125665. const char *zDoc; /* Document text to extract snippet from */
  125666. int nDoc; /* Size of zDoc in bytes */
  125667. int iCurrent = 0; /* Current token number of document */
  125668. int iEnd = 0; /* Byte offset of end of current token */
  125669. int isShiftDone = 0; /* True after snippet is shifted */
  125670. int iPos = pFragment->iPos; /* First token of snippet */
  125671. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  125672. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  125673. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  125674. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  125675. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  125676. if( zDoc==0 ){
  125677. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  125678. return SQLITE_NOMEM;
  125679. }
  125680. return SQLITE_OK;
  125681. }
  125682. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  125683. /* Open a token cursor on the document. */
  125684. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  125685. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  125686. if( rc!=SQLITE_OK ){
  125687. return rc;
  125688. }
  125689. while( rc==SQLITE_OK ){
  125690. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  125691. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  125692. int iBegin = 0; /* Offset in zDoc of start of token */
  125693. int iFin = 0; /* Offset in zDoc of end of token */
  125694. int isHighlight = 0; /* True for highlighted terms */
  125695. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  125696. ** in the FTS code the variable that the third argument to xNext points to
  125697. ** is initialized to zero before the first (*but not necessarily
  125698. ** subsequent*) call to xNext(). This is done for a particular application
  125699. ** that needs to know whether or not the tokenizer is being used for
  125700. ** snippet generation or for some other purpose.
  125701. **
  125702. ** Extreme care is required when writing code to depend on this
  125703. ** initialization. It is not a documented part of the tokenizer interface.
  125704. ** If a tokenizer is used directly by any code outside of FTS, this
  125705. ** convention might not be respected. */
  125706. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  125707. if( rc!=SQLITE_OK ){
  125708. if( rc==SQLITE_DONE ){
  125709. /* Special case - the last token of the snippet is also the last token
  125710. ** of the column. Append any punctuation that occurred between the end
  125711. ** of the previous token and the end of the document to the output.
  125712. ** Then break out of the loop. */
  125713. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  125714. }
  125715. break;
  125716. }
  125717. if( iCurrent<iPos ){ continue; }
  125718. if( !isShiftDone ){
  125719. int n = nDoc - iBegin;
  125720. rc = fts3SnippetShift(
  125721. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  125722. );
  125723. isShiftDone = 1;
  125724. /* Now that the shift has been done, check if the initial "..." are
  125725. ** required. They are required if (a) this is not the first fragment,
  125726. ** or (b) this fragment does not begin at position 0 of its column.
  125727. */
  125728. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  125729. rc = fts3StringAppend(pOut, zEllipsis, -1);
  125730. }
  125731. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  125732. }
  125733. if( iCurrent>=(iPos+nSnippet) ){
  125734. if( isLast ){
  125735. rc = fts3StringAppend(pOut, zEllipsis, -1);
  125736. }
  125737. break;
  125738. }
  125739. /* Set isHighlight to true if this term should be highlighted. */
  125740. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  125741. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  125742. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  125743. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  125744. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  125745. iEnd = iFin;
  125746. }
  125747. pMod->xClose(pC);
  125748. return rc;
  125749. }
  125750. /*
  125751. ** This function is used to count the entries in a column-list (a
  125752. ** delta-encoded list of term offsets within a single column of a single
  125753. ** row). When this function is called, *ppCollist should point to the
  125754. ** beginning of the first varint in the column-list (the varint that
  125755. ** contains the position of the first matching term in the column data).
  125756. ** Before returning, *ppCollist is set to point to the first byte after
  125757. ** the last varint in the column-list (either the 0x00 signifying the end
  125758. ** of the position-list, or the 0x01 that precedes the column number of
  125759. ** the next column in the position-list).
  125760. **
  125761. ** The number of elements in the column-list is returned.
  125762. */
  125763. static int fts3ColumnlistCount(char **ppCollist){
  125764. char *pEnd = *ppCollist;
  125765. char c = 0;
  125766. int nEntry = 0;
  125767. /* A column-list is terminated by either a 0x01 or 0x00. */
  125768. while( 0xFE & (*pEnd | c) ){
  125769. c = *pEnd++ & 0x80;
  125770. if( !c ) nEntry++;
  125771. }
  125772. *ppCollist = pEnd;
  125773. return nEntry;
  125774. }
  125775. /*
  125776. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  125777. ** for a single query.
  125778. **
  125779. ** fts3ExprIterate() callback to load the 'global' elements of a
  125780. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  125781. ** of the matchinfo array that are constant for all rows returned by the
  125782. ** current query.
  125783. **
  125784. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  125785. ** function populates Matchinfo.aMatchinfo[] as follows:
  125786. **
  125787. ** for(iCol=0; iCol<nCol; iCol++){
  125788. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  125789. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  125790. ** }
  125791. **
  125792. ** where X is the number of matches for phrase iPhrase is column iCol of all
  125793. ** rows of the table. Y is the number of rows for which column iCol contains
  125794. ** at least one instance of phrase iPhrase.
  125795. **
  125796. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  125797. ** Y values are set to nDoc, where nDoc is the number of documents in the
  125798. ** file system. This is done because the full-text index doclist is required
  125799. ** to calculate these values properly, and the full-text index doclist is
  125800. ** not available for deferred tokens.
  125801. */
  125802. static int fts3ExprGlobalHitsCb(
  125803. Fts3Expr *pExpr, /* Phrase expression node */
  125804. int iPhrase, /* Phrase number (numbered from zero) */
  125805. void *pCtx /* Pointer to MatchInfo structure */
  125806. ){
  125807. MatchInfo *p = (MatchInfo *)pCtx;
  125808. return sqlite3Fts3EvalPhraseStats(
  125809. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  125810. );
  125811. }
  125812. /*
  125813. ** fts3ExprIterate() callback used to collect the "local" part of the
  125814. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  125815. ** array that are different for each row returned by the query.
  125816. */
  125817. static int fts3ExprLocalHitsCb(
  125818. Fts3Expr *pExpr, /* Phrase expression node */
  125819. int iPhrase, /* Phrase number */
  125820. void *pCtx /* Pointer to MatchInfo structure */
  125821. ){
  125822. int rc = SQLITE_OK;
  125823. MatchInfo *p = (MatchInfo *)pCtx;
  125824. int iStart = iPhrase * p->nCol * 3;
  125825. int i;
  125826. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  125827. char *pCsr;
  125828. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  125829. if( pCsr ){
  125830. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  125831. }else{
  125832. p->aMatchinfo[iStart+i*3] = 0;
  125833. }
  125834. }
  125835. return rc;
  125836. }
  125837. static int fts3MatchinfoCheck(
  125838. Fts3Table *pTab,
  125839. char cArg,
  125840. char **pzErr
  125841. ){
  125842. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  125843. || (cArg==FTS3_MATCHINFO_NCOL)
  125844. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  125845. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  125846. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  125847. || (cArg==FTS3_MATCHINFO_LCS)
  125848. || (cArg==FTS3_MATCHINFO_HITS)
  125849. ){
  125850. return SQLITE_OK;
  125851. }
  125852. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  125853. return SQLITE_ERROR;
  125854. }
  125855. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  125856. int nVal; /* Number of integers output by cArg */
  125857. switch( cArg ){
  125858. case FTS3_MATCHINFO_NDOC:
  125859. case FTS3_MATCHINFO_NPHRASE:
  125860. case FTS3_MATCHINFO_NCOL:
  125861. nVal = 1;
  125862. break;
  125863. case FTS3_MATCHINFO_AVGLENGTH:
  125864. case FTS3_MATCHINFO_LENGTH:
  125865. case FTS3_MATCHINFO_LCS:
  125866. nVal = pInfo->nCol;
  125867. break;
  125868. default:
  125869. assert( cArg==FTS3_MATCHINFO_HITS );
  125870. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  125871. break;
  125872. }
  125873. return nVal;
  125874. }
  125875. static int fts3MatchinfoSelectDoctotal(
  125876. Fts3Table *pTab,
  125877. sqlite3_stmt **ppStmt,
  125878. sqlite3_int64 *pnDoc,
  125879. const char **paLen
  125880. ){
  125881. sqlite3_stmt *pStmt;
  125882. const char *a;
  125883. sqlite3_int64 nDoc;
  125884. if( !*ppStmt ){
  125885. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  125886. if( rc!=SQLITE_OK ) return rc;
  125887. }
  125888. pStmt = *ppStmt;
  125889. assert( sqlite3_data_count(pStmt)==1 );
  125890. a = sqlite3_column_blob(pStmt, 0);
  125891. a += sqlite3Fts3GetVarint(a, &nDoc);
  125892. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  125893. *pnDoc = (u32)nDoc;
  125894. if( paLen ) *paLen = a;
  125895. return SQLITE_OK;
  125896. }
  125897. /*
  125898. ** An instance of the following structure is used to store state while
  125899. ** iterating through a multi-column position-list corresponding to the
  125900. ** hits for a single phrase on a single row in order to calculate the
  125901. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  125902. */
  125903. typedef struct LcsIterator LcsIterator;
  125904. struct LcsIterator {
  125905. Fts3Expr *pExpr; /* Pointer to phrase expression */
  125906. int iPosOffset; /* Tokens count up to end of this phrase */
  125907. char *pRead; /* Cursor used to iterate through aDoclist */
  125908. int iPos; /* Current position */
  125909. };
  125910. /*
  125911. ** If LcsIterator.iCol is set to the following value, the iterator has
  125912. ** finished iterating through all offsets for all columns.
  125913. */
  125914. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  125915. static int fts3MatchinfoLcsCb(
  125916. Fts3Expr *pExpr, /* Phrase expression node */
  125917. int iPhrase, /* Phrase number (numbered from zero) */
  125918. void *pCtx /* Pointer to MatchInfo structure */
  125919. ){
  125920. LcsIterator *aIter = (LcsIterator *)pCtx;
  125921. aIter[iPhrase].pExpr = pExpr;
  125922. return SQLITE_OK;
  125923. }
  125924. /*
  125925. ** Advance the iterator passed as an argument to the next position. Return
  125926. ** 1 if the iterator is at EOF or if it now points to the start of the
  125927. ** position list for the next column.
  125928. */
  125929. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  125930. char *pRead = pIter->pRead;
  125931. sqlite3_int64 iRead;
  125932. int rc = 0;
  125933. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  125934. if( iRead==0 || iRead==1 ){
  125935. pRead = 0;
  125936. rc = 1;
  125937. }else{
  125938. pIter->iPos += (int)(iRead-2);
  125939. }
  125940. pIter->pRead = pRead;
  125941. return rc;
  125942. }
  125943. /*
  125944. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  125945. **
  125946. ** If the call is successful, the longest-common-substring lengths for each
  125947. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  125948. ** array before returning. SQLITE_OK is returned in this case.
  125949. **
  125950. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  125951. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  125952. ** undefined.
  125953. */
  125954. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  125955. LcsIterator *aIter;
  125956. int i;
  125957. int iCol;
  125958. int nToken = 0;
  125959. /* Allocate and populate the array of LcsIterator objects. The array
  125960. ** contains one element for each matchable phrase in the query.
  125961. **/
  125962. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  125963. if( !aIter ) return SQLITE_NOMEM;
  125964. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  125965. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  125966. for(i=0; i<pInfo->nPhrase; i++){
  125967. LcsIterator *pIter = &aIter[i];
  125968. nToken -= pIter->pExpr->pPhrase->nToken;
  125969. pIter->iPosOffset = nToken;
  125970. }
  125971. for(iCol=0; iCol<pInfo->nCol; iCol++){
  125972. int nLcs = 0; /* LCS value for this column */
  125973. int nLive = 0; /* Number of iterators in aIter not at EOF */
  125974. for(i=0; i<pInfo->nPhrase; i++){
  125975. int rc;
  125976. LcsIterator *pIt = &aIter[i];
  125977. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  125978. if( rc!=SQLITE_OK ) return rc;
  125979. if( pIt->pRead ){
  125980. pIt->iPos = pIt->iPosOffset;
  125981. fts3LcsIteratorAdvance(&aIter[i]);
  125982. nLive++;
  125983. }
  125984. }
  125985. while( nLive>0 ){
  125986. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  125987. int nThisLcs = 0; /* LCS for the current iterator positions */
  125988. for(i=0; i<pInfo->nPhrase; i++){
  125989. LcsIterator *pIter = &aIter[i];
  125990. if( pIter->pRead==0 ){
  125991. /* This iterator is already at EOF for this column. */
  125992. nThisLcs = 0;
  125993. }else{
  125994. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  125995. pAdv = pIter;
  125996. }
  125997. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  125998. nThisLcs++;
  125999. }else{
  126000. nThisLcs = 1;
  126001. }
  126002. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  126003. }
  126004. }
  126005. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  126006. }
  126007. pInfo->aMatchinfo[iCol] = nLcs;
  126008. }
  126009. sqlite3_free(aIter);
  126010. return SQLITE_OK;
  126011. }
  126012. /*
  126013. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  126014. ** be returned by the matchinfo() function. Argument zArg contains the
  126015. ** format string passed as the second argument to matchinfo (or the
  126016. ** default value "pcx" if no second argument was specified). The format
  126017. ** string has already been validated and the pInfo->aMatchinfo[] array
  126018. ** is guaranteed to be large enough for the output.
  126019. **
  126020. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  126021. ** If it is false, then assume that those fields that do not change between
  126022. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  126023. ** have already been populated.
  126024. **
  126025. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  126026. ** occurs. If a value other than SQLITE_OK is returned, the state the
  126027. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  126028. */
  126029. static int fts3MatchinfoValues(
  126030. Fts3Cursor *pCsr, /* FTS3 cursor object */
  126031. int bGlobal, /* True to grab the global stats */
  126032. MatchInfo *pInfo, /* Matchinfo context object */
  126033. const char *zArg /* Matchinfo format string */
  126034. ){
  126035. int rc = SQLITE_OK;
  126036. int i;
  126037. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126038. sqlite3_stmt *pSelect = 0;
  126039. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  126040. switch( zArg[i] ){
  126041. case FTS3_MATCHINFO_NPHRASE:
  126042. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  126043. break;
  126044. case FTS3_MATCHINFO_NCOL:
  126045. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  126046. break;
  126047. case FTS3_MATCHINFO_NDOC:
  126048. if( bGlobal ){
  126049. sqlite3_int64 nDoc = 0;
  126050. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  126051. pInfo->aMatchinfo[0] = (u32)nDoc;
  126052. }
  126053. break;
  126054. case FTS3_MATCHINFO_AVGLENGTH:
  126055. if( bGlobal ){
  126056. sqlite3_int64 nDoc; /* Number of rows in table */
  126057. const char *a; /* Aggregate column length array */
  126058. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  126059. if( rc==SQLITE_OK ){
  126060. int iCol;
  126061. for(iCol=0; iCol<pInfo->nCol; iCol++){
  126062. u32 iVal;
  126063. sqlite3_int64 nToken;
  126064. a += sqlite3Fts3GetVarint(a, &nToken);
  126065. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  126066. pInfo->aMatchinfo[iCol] = iVal;
  126067. }
  126068. }
  126069. }
  126070. break;
  126071. case FTS3_MATCHINFO_LENGTH: {
  126072. sqlite3_stmt *pSelectDocsize = 0;
  126073. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  126074. if( rc==SQLITE_OK ){
  126075. int iCol;
  126076. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  126077. for(iCol=0; iCol<pInfo->nCol; iCol++){
  126078. sqlite3_int64 nToken;
  126079. a += sqlite3Fts3GetVarint(a, &nToken);
  126080. pInfo->aMatchinfo[iCol] = (u32)nToken;
  126081. }
  126082. }
  126083. sqlite3_reset(pSelectDocsize);
  126084. break;
  126085. }
  126086. case FTS3_MATCHINFO_LCS:
  126087. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  126088. if( rc==SQLITE_OK ){
  126089. rc = fts3MatchinfoLcs(pCsr, pInfo);
  126090. }
  126091. break;
  126092. default: {
  126093. Fts3Expr *pExpr;
  126094. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  126095. pExpr = pCsr->pExpr;
  126096. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  126097. if( rc!=SQLITE_OK ) break;
  126098. if( bGlobal ){
  126099. if( pCsr->pDeferred ){
  126100. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  126101. if( rc!=SQLITE_OK ) break;
  126102. }
  126103. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  126104. if( rc!=SQLITE_OK ) break;
  126105. }
  126106. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  126107. break;
  126108. }
  126109. }
  126110. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  126111. }
  126112. sqlite3_reset(pSelect);
  126113. return rc;
  126114. }
  126115. /*
  126116. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  126117. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  126118. */
  126119. static int fts3GetMatchinfo(
  126120. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  126121. const char *zArg /* Second argument to matchinfo() function */
  126122. ){
  126123. MatchInfo sInfo;
  126124. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126125. int rc = SQLITE_OK;
  126126. int bGlobal = 0; /* Collect 'global' stats as well as local */
  126127. memset(&sInfo, 0, sizeof(MatchInfo));
  126128. sInfo.pCursor = pCsr;
  126129. sInfo.nCol = pTab->nColumn;
  126130. /* If there is cached matchinfo() data, but the format string for the
  126131. ** cache does not match the format string for this request, discard
  126132. ** the cached data. */
  126133. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  126134. assert( pCsr->aMatchinfo );
  126135. sqlite3_free(pCsr->aMatchinfo);
  126136. pCsr->zMatchinfo = 0;
  126137. pCsr->aMatchinfo = 0;
  126138. }
  126139. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  126140. ** matchinfo function has been called for this query. In this case
  126141. ** allocate the array used to accumulate the matchinfo data and
  126142. ** initialize those elements that are constant for every row.
  126143. */
  126144. if( pCsr->aMatchinfo==0 ){
  126145. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  126146. int nArg; /* Bytes in zArg */
  126147. int i; /* Used to iterate through zArg */
  126148. /* Determine the number of phrases in the query */
  126149. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  126150. sInfo.nPhrase = pCsr->nPhrase;
  126151. /* Determine the number of integers in the buffer returned by this call. */
  126152. for(i=0; zArg[i]; i++){
  126153. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  126154. }
  126155. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  126156. nArg = (int)strlen(zArg);
  126157. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  126158. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  126159. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  126160. pCsr->nMatchinfo = nMatchinfo;
  126161. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  126162. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  126163. pCsr->isMatchinfoNeeded = 1;
  126164. bGlobal = 1;
  126165. }
  126166. sInfo.aMatchinfo = pCsr->aMatchinfo;
  126167. sInfo.nPhrase = pCsr->nPhrase;
  126168. if( pCsr->isMatchinfoNeeded ){
  126169. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  126170. pCsr->isMatchinfoNeeded = 0;
  126171. }
  126172. return rc;
  126173. }
  126174. /*
  126175. ** Implementation of snippet() function.
  126176. */
  126177. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  126178. sqlite3_context *pCtx, /* SQLite function call context */
  126179. Fts3Cursor *pCsr, /* Cursor object */
  126180. const char *zStart, /* Snippet start text - "<b>" */
  126181. const char *zEnd, /* Snippet end text - "</b>" */
  126182. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  126183. int iCol, /* Extract snippet from this column */
  126184. int nToken /* Approximate number of tokens in snippet */
  126185. ){
  126186. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126187. int rc = SQLITE_OK;
  126188. int i;
  126189. StrBuffer res = {0, 0, 0};
  126190. /* The returned text includes up to four fragments of text extracted from
  126191. ** the data in the current row. The first iteration of the for(...) loop
  126192. ** below attempts to locate a single fragment of text nToken tokens in
  126193. ** size that contains at least one instance of all phrases in the query
  126194. ** expression that appear in the current row. If such a fragment of text
  126195. ** cannot be found, the second iteration of the loop attempts to locate
  126196. ** a pair of fragments, and so on.
  126197. */
  126198. int nSnippet = 0; /* Number of fragments in this snippet */
  126199. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  126200. int nFToken = -1; /* Number of tokens in each fragment */
  126201. if( !pCsr->pExpr ){
  126202. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  126203. return;
  126204. }
  126205. for(nSnippet=1; 1; nSnippet++){
  126206. int iSnip; /* Loop counter 0..nSnippet-1 */
  126207. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  126208. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  126209. if( nToken>=0 ){
  126210. nFToken = (nToken+nSnippet-1) / nSnippet;
  126211. }else{
  126212. nFToken = -1 * nToken;
  126213. }
  126214. for(iSnip=0; iSnip<nSnippet; iSnip++){
  126215. int iBestScore = -1; /* Best score of columns checked so far */
  126216. int iRead; /* Used to iterate through columns */
  126217. SnippetFragment *pFragment = &aSnippet[iSnip];
  126218. memset(pFragment, 0, sizeof(*pFragment));
  126219. /* Loop through all columns of the table being considered for snippets.
  126220. ** If the iCol argument to this function was negative, this means all
  126221. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  126222. */
  126223. for(iRead=0; iRead<pTab->nColumn; iRead++){
  126224. SnippetFragment sF = {0, 0, 0, 0};
  126225. int iS;
  126226. if( iCol>=0 && iRead!=iCol ) continue;
  126227. /* Find the best snippet of nFToken tokens in column iRead. */
  126228. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  126229. if( rc!=SQLITE_OK ){
  126230. goto snippet_out;
  126231. }
  126232. if( iS>iBestScore ){
  126233. *pFragment = sF;
  126234. iBestScore = iS;
  126235. }
  126236. }
  126237. mCovered |= pFragment->covered;
  126238. }
  126239. /* If all query phrases seen by fts3BestSnippet() are present in at least
  126240. ** one of the nSnippet snippet fragments, break out of the loop.
  126241. */
  126242. assert( (mCovered&mSeen)==mCovered );
  126243. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  126244. }
  126245. assert( nFToken>0 );
  126246. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  126247. rc = fts3SnippetText(pCsr, &aSnippet[i],
  126248. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  126249. );
  126250. }
  126251. snippet_out:
  126252. sqlite3Fts3SegmentsClose(pTab);
  126253. if( rc!=SQLITE_OK ){
  126254. sqlite3_result_error_code(pCtx, rc);
  126255. sqlite3_free(res.z);
  126256. }else{
  126257. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  126258. }
  126259. }
  126260. typedef struct TermOffset TermOffset;
  126261. typedef struct TermOffsetCtx TermOffsetCtx;
  126262. struct TermOffset {
  126263. char *pList; /* Position-list */
  126264. int iPos; /* Position just read from pList */
  126265. int iOff; /* Offset of this term from read positions */
  126266. };
  126267. struct TermOffsetCtx {
  126268. Fts3Cursor *pCsr;
  126269. int iCol; /* Column of table to populate aTerm for */
  126270. int iTerm;
  126271. sqlite3_int64 iDocid;
  126272. TermOffset *aTerm;
  126273. };
  126274. /*
  126275. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  126276. */
  126277. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  126278. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  126279. int nTerm; /* Number of tokens in phrase */
  126280. int iTerm; /* For looping through nTerm phrase terms */
  126281. char *pList; /* Pointer to position list for phrase */
  126282. int iPos = 0; /* First position in position-list */
  126283. int rc;
  126284. UNUSED_PARAMETER(iPhrase);
  126285. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  126286. nTerm = pExpr->pPhrase->nToken;
  126287. if( pList ){
  126288. fts3GetDeltaPosition(&pList, &iPos);
  126289. assert( iPos>=0 );
  126290. }
  126291. for(iTerm=0; iTerm<nTerm; iTerm++){
  126292. TermOffset *pT = &p->aTerm[p->iTerm++];
  126293. pT->iOff = nTerm-iTerm-1;
  126294. pT->pList = pList;
  126295. pT->iPos = iPos;
  126296. }
  126297. return rc;
  126298. }
  126299. /*
  126300. ** Implementation of offsets() function.
  126301. */
  126302. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  126303. sqlite3_context *pCtx, /* SQLite function call context */
  126304. Fts3Cursor *pCsr /* Cursor object */
  126305. ){
  126306. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126307. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  126308. int rc; /* Return Code */
  126309. int nToken; /* Number of tokens in query */
  126310. int iCol; /* Column currently being processed */
  126311. StrBuffer res = {0, 0, 0}; /* Result string */
  126312. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  126313. if( !pCsr->pExpr ){
  126314. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  126315. return;
  126316. }
  126317. memset(&sCtx, 0, sizeof(sCtx));
  126318. assert( pCsr->isRequireSeek==0 );
  126319. /* Count the number of terms in the query */
  126320. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  126321. if( rc!=SQLITE_OK ) goto offsets_out;
  126322. /* Allocate the array of TermOffset iterators. */
  126323. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  126324. if( 0==sCtx.aTerm ){
  126325. rc = SQLITE_NOMEM;
  126326. goto offsets_out;
  126327. }
  126328. sCtx.iDocid = pCsr->iPrevId;
  126329. sCtx.pCsr = pCsr;
  126330. /* Loop through the table columns, appending offset information to
  126331. ** string-buffer res for each column.
  126332. */
  126333. for(iCol=0; iCol<pTab->nColumn; iCol++){
  126334. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  126335. const char *ZDUMMY; /* Dummy argument used with xNext() */
  126336. int NDUMMY = 0; /* Dummy argument used with xNext() */
  126337. int iStart = 0;
  126338. int iEnd = 0;
  126339. int iCurrent = 0;
  126340. const char *zDoc;
  126341. int nDoc;
  126342. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  126343. ** no way that this operation can fail, so the return code from
  126344. ** fts3ExprIterate() can be discarded.
  126345. */
  126346. sCtx.iCol = iCol;
  126347. sCtx.iTerm = 0;
  126348. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  126349. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  126350. ** in column iCol, jump immediately to the next iteration of the loop.
  126351. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  126352. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  126353. ** to the caller.
  126354. */
  126355. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  126356. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  126357. if( zDoc==0 ){
  126358. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  126359. continue;
  126360. }
  126361. rc = SQLITE_NOMEM;
  126362. goto offsets_out;
  126363. }
  126364. /* Initialize a tokenizer iterator to iterate through column iCol. */
  126365. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  126366. zDoc, nDoc, &pC
  126367. );
  126368. if( rc!=SQLITE_OK ) goto offsets_out;
  126369. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  126370. while( rc==SQLITE_OK ){
  126371. int i; /* Used to loop through terms */
  126372. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  126373. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  126374. for(i=0; i<nToken; i++){
  126375. TermOffset *pT = &sCtx.aTerm[i];
  126376. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  126377. iMinPos = pT->iPos-pT->iOff;
  126378. pTerm = pT;
  126379. }
  126380. }
  126381. if( !pTerm ){
  126382. /* All offsets for this column have been gathered. */
  126383. rc = SQLITE_DONE;
  126384. }else{
  126385. assert( iCurrent<=iMinPos );
  126386. if( 0==(0xFE&*pTerm->pList) ){
  126387. pTerm->pList = 0;
  126388. }else{
  126389. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  126390. }
  126391. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  126392. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  126393. }
  126394. if( rc==SQLITE_OK ){
  126395. char aBuffer[64];
  126396. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  126397. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  126398. );
  126399. rc = fts3StringAppend(&res, aBuffer, -1);
  126400. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  126401. rc = FTS_CORRUPT_VTAB;
  126402. }
  126403. }
  126404. }
  126405. if( rc==SQLITE_DONE ){
  126406. rc = SQLITE_OK;
  126407. }
  126408. pMod->xClose(pC);
  126409. if( rc!=SQLITE_OK ) goto offsets_out;
  126410. }
  126411. offsets_out:
  126412. sqlite3_free(sCtx.aTerm);
  126413. assert( rc!=SQLITE_DONE );
  126414. sqlite3Fts3SegmentsClose(pTab);
  126415. if( rc!=SQLITE_OK ){
  126416. sqlite3_result_error_code(pCtx, rc);
  126417. sqlite3_free(res.z);
  126418. }else{
  126419. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  126420. }
  126421. return;
  126422. }
  126423. /*
  126424. ** Implementation of matchinfo() function.
  126425. */
  126426. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  126427. sqlite3_context *pContext, /* Function call context */
  126428. Fts3Cursor *pCsr, /* FTS3 table cursor */
  126429. const char *zArg /* Second arg to matchinfo() function */
  126430. ){
  126431. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126432. int rc;
  126433. int i;
  126434. const char *zFormat;
  126435. if( zArg ){
  126436. for(i=0; zArg[i]; i++){
  126437. char *zErr = 0;
  126438. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  126439. sqlite3_result_error(pContext, zErr, -1);
  126440. sqlite3_free(zErr);
  126441. return;
  126442. }
  126443. }
  126444. zFormat = zArg;
  126445. }else{
  126446. zFormat = FTS3_MATCHINFO_DEFAULT;
  126447. }
  126448. if( !pCsr->pExpr ){
  126449. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  126450. return;
  126451. }
  126452. /* Retrieve matchinfo() data. */
  126453. rc = fts3GetMatchinfo(pCsr, zFormat);
  126454. sqlite3Fts3SegmentsClose(pTab);
  126455. if( rc!=SQLITE_OK ){
  126456. sqlite3_result_error_code(pContext, rc);
  126457. }else{
  126458. int n = pCsr->nMatchinfo * sizeof(u32);
  126459. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  126460. }
  126461. }
  126462. #endif
  126463. /************** End of fts3_snippet.c ****************************************/
  126464. /************** Begin file fts3_unicode.c ************************************/
  126465. /*
  126466. ** 2012 May 24
  126467. **
  126468. ** The author disclaims copyright to this source code. In place of
  126469. ** a legal notice, here is a blessing:
  126470. **
  126471. ** May you do good and not evil.
  126472. ** May you find forgiveness for yourself and forgive others.
  126473. ** May you share freely, never taking more than you give.
  126474. **
  126475. ******************************************************************************
  126476. **
  126477. ** Implementation of the "unicode" full-text-search tokenizer.
  126478. */
  126479. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  126480. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126481. /* #include <assert.h> */
  126482. /* #include <stdlib.h> */
  126483. /* #include <stdio.h> */
  126484. /* #include <string.h> */
  126485. /*
  126486. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  126487. ** from the sqlite3 source file utf.c. If this file is compiled as part
  126488. ** of the amalgamation, they are not required.
  126489. */
  126490. #ifndef SQLITE_AMALGAMATION
  126491. static const unsigned char sqlite3Utf8Trans1[] = {
  126492. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  126493. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  126494. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  126495. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  126496. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  126497. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  126498. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  126499. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  126500. };
  126501. #define READ_UTF8(zIn, zTerm, c) \
  126502. c = *(zIn++); \
  126503. if( c>=0xc0 ){ \
  126504. c = sqlite3Utf8Trans1[c-0xc0]; \
  126505. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  126506. c = (c<<6) + (0x3f & *(zIn++)); \
  126507. } \
  126508. if( c<0x80 \
  126509. || (c&0xFFFFF800)==0xD800 \
  126510. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  126511. }
  126512. #define WRITE_UTF8(zOut, c) { \
  126513. if( c<0x00080 ){ \
  126514. *zOut++ = (u8)(c&0xFF); \
  126515. } \
  126516. else if( c<0x00800 ){ \
  126517. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  126518. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  126519. } \
  126520. else if( c<0x10000 ){ \
  126521. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  126522. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  126523. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  126524. }else{ \
  126525. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  126526. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  126527. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  126528. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  126529. } \
  126530. }
  126531. #endif /* ifndef SQLITE_AMALGAMATION */
  126532. typedef struct unicode_tokenizer unicode_tokenizer;
  126533. typedef struct unicode_cursor unicode_cursor;
  126534. struct unicode_tokenizer {
  126535. sqlite3_tokenizer base;
  126536. int bRemoveDiacritic;
  126537. int nException;
  126538. int *aiException;
  126539. };
  126540. struct unicode_cursor {
  126541. sqlite3_tokenizer_cursor base;
  126542. const unsigned char *aInput; /* Input text being tokenized */
  126543. int nInput; /* Size of aInput[] in bytes */
  126544. int iOff; /* Current offset within aInput[] */
  126545. int iToken; /* Index of next token to be returned */
  126546. char *zToken; /* storage for current token */
  126547. int nAlloc; /* space allocated at zToken */
  126548. };
  126549. /*
  126550. ** Destroy a tokenizer allocated by unicodeCreate().
  126551. */
  126552. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  126553. if( pTokenizer ){
  126554. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  126555. sqlite3_free(p->aiException);
  126556. sqlite3_free(p);
  126557. }
  126558. return SQLITE_OK;
  126559. }
  126560. /*
  126561. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  126562. ** statement has specified that the tokenizer for this table shall consider
  126563. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  126564. ** token characters (if bAlnum==1).
  126565. **
  126566. ** For each codepoint in the zIn/nIn string, this function checks if the
  126567. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  126568. ** If so, no action is taken. Otherwise, the codepoint is added to the
  126569. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  126570. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  126571. ** codepoints in the aiException[] array.
  126572. **
  126573. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  126574. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  126575. ** It is not possible to change the behavior of the tokenizer with respect
  126576. ** to these codepoints.
  126577. */
  126578. static int unicodeAddExceptions(
  126579. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  126580. int bAlnum, /* Replace Isalnum() return value with this */
  126581. const char *zIn, /* Array of characters to make exceptions */
  126582. int nIn /* Length of z in bytes */
  126583. ){
  126584. const unsigned char *z = (const unsigned char *)zIn;
  126585. const unsigned char *zTerm = &z[nIn];
  126586. int iCode;
  126587. int nEntry = 0;
  126588. assert( bAlnum==0 || bAlnum==1 );
  126589. while( z<zTerm ){
  126590. READ_UTF8(z, zTerm, iCode);
  126591. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  126592. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  126593. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  126594. ){
  126595. nEntry++;
  126596. }
  126597. }
  126598. if( nEntry ){
  126599. int *aNew; /* New aiException[] array */
  126600. int nNew; /* Number of valid entries in array aNew[] */
  126601. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  126602. if( aNew==0 ) return SQLITE_NOMEM;
  126603. nNew = p->nException;
  126604. z = (const unsigned char *)zIn;
  126605. while( z<zTerm ){
  126606. READ_UTF8(z, zTerm, iCode);
  126607. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  126608. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  126609. ){
  126610. int i, j;
  126611. for(i=0; i<nNew && aNew[i]<iCode; i++);
  126612. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  126613. aNew[i] = iCode;
  126614. nNew++;
  126615. }
  126616. }
  126617. p->aiException = aNew;
  126618. p->nException = nNew;
  126619. }
  126620. return SQLITE_OK;
  126621. }
  126622. /*
  126623. ** Return true if the p->aiException[] array contains the value iCode.
  126624. */
  126625. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  126626. if( p->nException>0 ){
  126627. int *a = p->aiException;
  126628. int iLo = 0;
  126629. int iHi = p->nException-1;
  126630. while( iHi>=iLo ){
  126631. int iTest = (iHi + iLo) / 2;
  126632. if( iCode==a[iTest] ){
  126633. return 1;
  126634. }else if( iCode>a[iTest] ){
  126635. iLo = iTest+1;
  126636. }else{
  126637. iHi = iTest-1;
  126638. }
  126639. }
  126640. }
  126641. return 0;
  126642. }
  126643. /*
  126644. ** Return true if, for the purposes of tokenization, codepoint iCode is
  126645. ** considered a token character (not a separator).
  126646. */
  126647. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  126648. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  126649. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  126650. }
  126651. /*
  126652. ** Create a new tokenizer instance.
  126653. */
  126654. static int unicodeCreate(
  126655. int nArg, /* Size of array argv[] */
  126656. const char * const *azArg, /* Tokenizer creation arguments */
  126657. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  126658. ){
  126659. unicode_tokenizer *pNew; /* New tokenizer object */
  126660. int i;
  126661. int rc = SQLITE_OK;
  126662. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  126663. if( pNew==NULL ) return SQLITE_NOMEM;
  126664. memset(pNew, 0, sizeof(unicode_tokenizer));
  126665. pNew->bRemoveDiacritic = 1;
  126666. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  126667. const char *z = azArg[i];
  126668. int n = strlen(z);
  126669. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  126670. pNew->bRemoveDiacritic = 1;
  126671. }
  126672. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  126673. pNew->bRemoveDiacritic = 0;
  126674. }
  126675. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  126676. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  126677. }
  126678. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  126679. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  126680. }
  126681. else{
  126682. /* Unrecognized argument */
  126683. rc = SQLITE_ERROR;
  126684. }
  126685. }
  126686. if( rc!=SQLITE_OK ){
  126687. unicodeDestroy((sqlite3_tokenizer *)pNew);
  126688. pNew = 0;
  126689. }
  126690. *pp = (sqlite3_tokenizer *)pNew;
  126691. return rc;
  126692. }
  126693. /*
  126694. ** Prepare to begin tokenizing a particular string. The input
  126695. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  126696. ** used to incrementally tokenize this string is returned in
  126697. ** *ppCursor.
  126698. */
  126699. static int unicodeOpen(
  126700. sqlite3_tokenizer *p, /* The tokenizer */
  126701. const char *aInput, /* Input string */
  126702. int nInput, /* Size of string aInput in bytes */
  126703. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  126704. ){
  126705. unicode_cursor *pCsr;
  126706. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  126707. if( pCsr==0 ){
  126708. return SQLITE_NOMEM;
  126709. }
  126710. memset(pCsr, 0, sizeof(unicode_cursor));
  126711. pCsr->aInput = (const unsigned char *)aInput;
  126712. if( aInput==0 ){
  126713. pCsr->nInput = 0;
  126714. }else if( nInput<0 ){
  126715. pCsr->nInput = (int)strlen(aInput);
  126716. }else{
  126717. pCsr->nInput = nInput;
  126718. }
  126719. *pp = &pCsr->base;
  126720. UNUSED_PARAMETER(p);
  126721. return SQLITE_OK;
  126722. }
  126723. /*
  126724. ** Close a tokenization cursor previously opened by a call to
  126725. ** simpleOpen() above.
  126726. */
  126727. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  126728. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  126729. sqlite3_free(pCsr->zToken);
  126730. sqlite3_free(pCsr);
  126731. return SQLITE_OK;
  126732. }
  126733. /*
  126734. ** Extract the next token from a tokenization cursor. The cursor must
  126735. ** have been opened by a prior call to simpleOpen().
  126736. */
  126737. static int unicodeNext(
  126738. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  126739. const char **paToken, /* OUT: Token text */
  126740. int *pnToken, /* OUT: Number of bytes at *paToken */
  126741. int *piStart, /* OUT: Starting offset of token */
  126742. int *piEnd, /* OUT: Ending offset of token */
  126743. int *piPos /* OUT: Position integer of token */
  126744. ){
  126745. unicode_cursor *pCsr = (unicode_cursor *)pC;
  126746. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  126747. int iCode;
  126748. char *zOut;
  126749. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  126750. const unsigned char *zStart = z;
  126751. const unsigned char *zEnd;
  126752. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  126753. /* Scan past any delimiter characters before the start of the next token.
  126754. ** Return SQLITE_DONE early if this takes us all the way to the end of
  126755. ** the input. */
  126756. while( z<zTerm ){
  126757. READ_UTF8(z, zTerm, iCode);
  126758. if( unicodeIsAlnum(p, iCode) ) break;
  126759. zStart = z;
  126760. }
  126761. if( zStart>=zTerm ) return SQLITE_DONE;
  126762. zOut = pCsr->zToken;
  126763. do {
  126764. int iOut;
  126765. /* Grow the output buffer if required. */
  126766. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  126767. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  126768. if( !zNew ) return SQLITE_NOMEM;
  126769. zOut = &zNew[zOut - pCsr->zToken];
  126770. pCsr->zToken = zNew;
  126771. pCsr->nAlloc += 64;
  126772. }
  126773. /* Write the folded case of the last character read to the output */
  126774. zEnd = z;
  126775. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  126776. if( iOut ){
  126777. WRITE_UTF8(zOut, iOut);
  126778. }
  126779. /* If the cursor is not at EOF, read the next character */
  126780. if( z>=zTerm ) break;
  126781. READ_UTF8(z, zTerm, iCode);
  126782. }while( unicodeIsAlnum(p, iCode)
  126783. || sqlite3FtsUnicodeIsdiacritic(iCode)
  126784. );
  126785. /* Set the output variables and return. */
  126786. pCsr->iOff = (z - pCsr->aInput);
  126787. *paToken = pCsr->zToken;
  126788. *pnToken = zOut - pCsr->zToken;
  126789. *piStart = (zStart - pCsr->aInput);
  126790. *piEnd = (zEnd - pCsr->aInput);
  126791. *piPos = pCsr->iToken++;
  126792. return SQLITE_OK;
  126793. }
  126794. /*
  126795. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  126796. ** structure for the unicode tokenizer.
  126797. */
  126798. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  126799. static const sqlite3_tokenizer_module module = {
  126800. 0,
  126801. unicodeCreate,
  126802. unicodeDestroy,
  126803. unicodeOpen,
  126804. unicodeClose,
  126805. unicodeNext,
  126806. 0,
  126807. };
  126808. *ppModule = &module;
  126809. }
  126810. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  126811. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  126812. /************** End of fts3_unicode.c ****************************************/
  126813. /************** Begin file fts3_unicode2.c ***********************************/
  126814. /*
  126815. ** 2012 May 25
  126816. **
  126817. ** The author disclaims copyright to this source code. In place of
  126818. ** a legal notice, here is a blessing:
  126819. **
  126820. ** May you do good and not evil.
  126821. ** May you find forgiveness for yourself and forgive others.
  126822. ** May you share freely, never taking more than you give.
  126823. **
  126824. ******************************************************************************
  126825. */
  126826. /*
  126827. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  126828. */
  126829. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  126830. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  126831. /* #include <assert.h> */
  126832. /*
  126833. ** Return true if the argument corresponds to a unicode codepoint
  126834. ** classified as either a letter or a number. Otherwise false.
  126835. **
  126836. ** The results are undefined if the value passed to this function
  126837. ** is less than zero.
  126838. */
  126839. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  126840. /* Each unsigned integer in the following array corresponds to a contiguous
  126841. ** range of unicode codepoints that are not either letters or numbers (i.e.
  126842. ** codepoints for which this function should return 0).
  126843. **
  126844. ** The most significant 22 bits in each 32-bit value contain the first
  126845. ** codepoint in the range. The least significant 10 bits are used to store
  126846. ** the size of the range (always at least 1). In other words, the value
  126847. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  126848. ** C. It is not possible to represent a range larger than 1023 codepoints
  126849. ** using this format.
  126850. */
  126851. const static unsigned int aEntry[] = {
  126852. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  126853. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  126854. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  126855. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  126856. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  126857. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  126858. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  126859. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  126860. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  126861. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  126862. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  126863. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  126864. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  126865. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  126866. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  126867. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  126868. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  126869. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  126870. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  126871. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  126872. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  126873. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  126874. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  126875. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  126876. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  126877. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  126878. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  126879. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  126880. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  126881. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  126882. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  126883. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  126884. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  126885. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  126886. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  126887. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  126888. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  126889. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  126890. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  126891. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  126892. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  126893. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  126894. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  126895. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  126896. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  126897. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  126898. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  126899. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  126900. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  126901. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  126902. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  126903. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  126904. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  126905. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  126906. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  126907. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  126908. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  126909. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  126910. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  126911. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  126912. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  126913. 0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
  126914. 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
  126915. 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
  126916. 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
  126917. 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
  126918. 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
  126919. 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
  126920. 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
  126921. 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
  126922. 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
  126923. 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
  126924. 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
  126925. 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
  126926. 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
  126927. 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
  126928. 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
  126929. 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
  126930. 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
  126931. 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
  126932. 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
  126933. 0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
  126934. 0x43FFF401,
  126935. };
  126936. static const unsigned int aAscii[4] = {
  126937. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  126938. };
  126939. if( c<128 ){
  126940. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  126941. }else if( c<(1<<22) ){
  126942. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  126943. int iRes;
  126944. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  126945. int iLo = 0;
  126946. while( iHi>=iLo ){
  126947. int iTest = (iHi + iLo) / 2;
  126948. if( key >= aEntry[iTest] ){
  126949. iRes = iTest;
  126950. iLo = iTest+1;
  126951. }else{
  126952. iHi = iTest-1;
  126953. }
  126954. }
  126955. assert( aEntry[0]<key );
  126956. assert( key>=aEntry[iRes] );
  126957. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  126958. }
  126959. return 1;
  126960. }
  126961. /*
  126962. ** If the argument is a codepoint corresponding to a lowercase letter
  126963. ** in the ASCII range with a diacritic added, return the codepoint
  126964. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  126965. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  126966. ** E"). The resuls of passing a codepoint that corresponds to an
  126967. ** uppercase letter are undefined.
  126968. */
  126969. static int remove_diacritic(int c){
  126970. unsigned short aDia[] = {
  126971. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  126972. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  126973. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  126974. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  126975. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  126976. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  126977. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  126978. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  126979. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  126980. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  126981. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  126982. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  126983. 62924, 63050, 63082, 63274, 63390,
  126984. };
  126985. char aChar[] = {
  126986. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  126987. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  126988. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  126989. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  126990. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  126991. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  126992. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  126993. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  126994. 'e', 'i', 'o', 'u', 'y',
  126995. };
  126996. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  126997. int iRes = 0;
  126998. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  126999. int iLo = 0;
  127000. while( iHi>=iLo ){
  127001. int iTest = (iHi + iLo) / 2;
  127002. if( key >= aDia[iTest] ){
  127003. iRes = iTest;
  127004. iLo = iTest+1;
  127005. }else{
  127006. iHi = iTest-1;
  127007. }
  127008. }
  127009. assert( key>=aDia[iRes] );
  127010. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  127011. };
  127012. /*
  127013. ** Return true if the argument interpreted as a unicode codepoint
  127014. ** is a diacritical modifier character.
  127015. */
  127016. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  127017. unsigned int mask0 = 0x08029FDF;
  127018. unsigned int mask1 = 0x000361F8;
  127019. if( c<768 || c>817 ) return 0;
  127020. return (c < 768+32) ?
  127021. (mask0 & (1 << (c-768))) :
  127022. (mask1 & (1 << (c-768-32)));
  127023. }
  127024. /*
  127025. ** Interpret the argument as a unicode codepoint. If the codepoint
  127026. ** is an upper case character that has a lower case equivalent,
  127027. ** return the codepoint corresponding to the lower case version.
  127028. ** Otherwise, return a copy of the argument.
  127029. **
  127030. ** The results are undefined if the value passed to this function
  127031. ** is less than zero.
  127032. */
  127033. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  127034. /* Each entry in the following array defines a rule for folding a range
  127035. ** of codepoints to lower case. The rule applies to a range of nRange
  127036. ** codepoints starting at codepoint iCode.
  127037. **
  127038. ** If the least significant bit in flags is clear, then the rule applies
  127039. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  127040. ** need to be folded). Or, if it is set, then the rule only applies to
  127041. ** every second codepoint in the range, starting with codepoint C.
  127042. **
  127043. ** The 7 most significant bits in flags are an index into the aiOff[]
  127044. ** array. If a specific codepoint C does require folding, then its lower
  127045. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  127046. **
  127047. ** The contents of this array are generated by parsing the CaseFolding.txt
  127048. ** file distributed as part of the "Unicode Character Database". See
  127049. ** http://www.unicode.org for details.
  127050. */
  127051. static const struct TableEntry {
  127052. unsigned short iCode;
  127053. unsigned char flags;
  127054. unsigned char nRange;
  127055. } aEntry[] = {
  127056. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  127057. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  127058. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  127059. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  127060. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  127061. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  127062. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  127063. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  127064. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  127065. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  127066. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  127067. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  127068. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  127069. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  127070. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  127071. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  127072. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  127073. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  127074. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  127075. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  127076. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  127077. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  127078. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  127079. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  127080. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  127081. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  127082. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  127083. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  127084. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  127085. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  127086. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  127087. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  127088. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  127089. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  127090. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  127091. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  127092. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  127093. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  127094. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  127095. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  127096. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  127097. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  127098. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  127099. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  127100. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  127101. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  127102. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  127103. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  127104. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  127105. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  127106. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  127107. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  127108. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  127109. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  127110. {65313, 14, 26},
  127111. };
  127112. static const unsigned short aiOff[] = {
  127113. 1, 2, 8, 15, 16, 26, 28, 32,
  127114. 37, 38, 40, 48, 63, 64, 69, 71,
  127115. 79, 80, 116, 202, 203, 205, 206, 207,
  127116. 209, 210, 211, 213, 214, 217, 218, 219,
  127117. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  127118. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  127119. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  127120. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  127121. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  127122. 65514, 65521, 65527, 65528, 65529,
  127123. };
  127124. int ret = c;
  127125. assert( c>=0 );
  127126. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  127127. if( c<128 ){
  127128. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  127129. }else if( c<65536 ){
  127130. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  127131. int iLo = 0;
  127132. int iRes = -1;
  127133. while( iHi>=iLo ){
  127134. int iTest = (iHi + iLo) / 2;
  127135. int cmp = (c - aEntry[iTest].iCode);
  127136. if( cmp>=0 ){
  127137. iRes = iTest;
  127138. iLo = iTest+1;
  127139. }else{
  127140. iHi = iTest-1;
  127141. }
  127142. }
  127143. assert( iRes<0 || c>=aEntry[iRes].iCode );
  127144. if( iRes>=0 ){
  127145. const struct TableEntry *p = &aEntry[iRes];
  127146. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  127147. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  127148. assert( ret>0 );
  127149. }
  127150. }
  127151. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  127152. }
  127153. else if( c>=66560 && c<66600 ){
  127154. ret = c + 40;
  127155. }
  127156. return ret;
  127157. }
  127158. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  127159. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  127160. /************** End of fts3_unicode2.c ***************************************/
  127161. /************** Begin file rtree.c *******************************************/
  127162. /*
  127163. ** 2001 September 15
  127164. **
  127165. ** The author disclaims copyright to this source code. In place of
  127166. ** a legal notice, here is a blessing:
  127167. **
  127168. ** May you do good and not evil.
  127169. ** May you find forgiveness for yourself and forgive others.
  127170. ** May you share freely, never taking more than you give.
  127171. **
  127172. *************************************************************************
  127173. ** This file contains code for implementations of the r-tree and r*-tree
  127174. ** algorithms packaged as an SQLite virtual table module.
  127175. */
  127176. /*
  127177. ** Database Format of R-Tree Tables
  127178. ** --------------------------------
  127179. **
  127180. ** The data structure for a single virtual r-tree table is stored in three
  127181. ** native SQLite tables declared as follows. In each case, the '%' character
  127182. ** in the table name is replaced with the user-supplied name of the r-tree
  127183. ** table.
  127184. **
  127185. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  127186. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  127187. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  127188. **
  127189. ** The data for each node of the r-tree structure is stored in the %_node
  127190. ** table. For each node that is not the root node of the r-tree, there is
  127191. ** an entry in the %_parent table associating the node with its parent.
  127192. ** And for each row of data in the table, there is an entry in the %_rowid
  127193. ** table that maps from the entries rowid to the id of the node that it
  127194. ** is stored on.
  127195. **
  127196. ** The root node of an r-tree always exists, even if the r-tree table is
  127197. ** empty. The nodeno of the root node is always 1. All other nodes in the
  127198. ** table must be the same size as the root node. The content of each node
  127199. ** is formatted as follows:
  127200. **
  127201. ** 1. If the node is the root node (node 1), then the first 2 bytes
  127202. ** of the node contain the tree depth as a big-endian integer.
  127203. ** For non-root nodes, the first 2 bytes are left unused.
  127204. **
  127205. ** 2. The next 2 bytes contain the number of entries currently
  127206. ** stored in the node.
  127207. **
  127208. ** 3. The remainder of the node contains the node entries. Each entry
  127209. ** consists of a single 8-byte integer followed by an even number
  127210. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  127211. ** of a record. For internal nodes it is the node number of a
  127212. ** child page.
  127213. */
  127214. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  127215. /*
  127216. ** This file contains an implementation of a couple of different variants
  127217. ** of the r-tree algorithm. See the README file for further details. The
  127218. ** same data-structure is used for all, but the algorithms for insert and
  127219. ** delete operations vary. The variants used are selected at compile time
  127220. ** by defining the following symbols:
  127221. */
  127222. /* Either, both or none of the following may be set to activate
  127223. ** r*tree variant algorithms.
  127224. */
  127225. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  127226. #define VARIANT_RSTARTREE_REINSERT 1
  127227. /*
  127228. ** Exactly one of the following must be set to 1.
  127229. */
  127230. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  127231. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  127232. #define VARIANT_RSTARTREE_SPLIT 1
  127233. #define VARIANT_GUTTMAN_SPLIT \
  127234. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  127235. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  127236. #define PickNext QuadraticPickNext
  127237. #define PickSeeds QuadraticPickSeeds
  127238. #define AssignCells splitNodeGuttman
  127239. #endif
  127240. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  127241. #define PickNext LinearPickNext
  127242. #define PickSeeds LinearPickSeeds
  127243. #define AssignCells splitNodeGuttman
  127244. #endif
  127245. #if VARIANT_RSTARTREE_SPLIT
  127246. #define AssignCells splitNodeStartree
  127247. #endif
  127248. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  127249. # define NDEBUG 1
  127250. #endif
  127251. #ifndef SQLITE_CORE
  127252. SQLITE_EXTENSION_INIT1
  127253. #else
  127254. #endif
  127255. /* #include <string.h> */
  127256. /* #include <assert.h> */
  127257. #ifndef SQLITE_AMALGAMATION
  127258. #include "sqlite3rtree.h"
  127259. typedef sqlite3_int64 i64;
  127260. typedef unsigned char u8;
  127261. typedef unsigned int u32;
  127262. #endif
  127263. /* The following macro is used to suppress compiler warnings.
  127264. */
  127265. #ifndef UNUSED_PARAMETER
  127266. # define UNUSED_PARAMETER(x) (void)(x)
  127267. #endif
  127268. typedef struct Rtree Rtree;
  127269. typedef struct RtreeCursor RtreeCursor;
  127270. typedef struct RtreeNode RtreeNode;
  127271. typedef struct RtreeCell RtreeCell;
  127272. typedef struct RtreeConstraint RtreeConstraint;
  127273. typedef struct RtreeMatchArg RtreeMatchArg;
  127274. typedef struct RtreeGeomCallback RtreeGeomCallback;
  127275. typedef union RtreeCoord RtreeCoord;
  127276. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  127277. #define RTREE_MAX_DIMENSIONS 5
  127278. /* Size of hash table Rtree.aHash. This hash table is not expected to
  127279. ** ever contain very many entries, so a fixed number of buckets is
  127280. ** used.
  127281. */
  127282. #define HASHSIZE 128
  127283. /*
  127284. ** An rtree virtual-table object.
  127285. */
  127286. struct Rtree {
  127287. sqlite3_vtab base;
  127288. sqlite3 *db; /* Host database connection */
  127289. int iNodeSize; /* Size in bytes of each node in the node table */
  127290. int nDim; /* Number of dimensions */
  127291. int nBytesPerCell; /* Bytes consumed per cell */
  127292. int iDepth; /* Current depth of the r-tree structure */
  127293. char *zDb; /* Name of database containing r-tree table */
  127294. char *zName; /* Name of r-tree table */
  127295. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  127296. int nBusy; /* Current number of users of this structure */
  127297. /* List of nodes removed during a CondenseTree operation. List is
  127298. ** linked together via the pointer normally used for hash chains -
  127299. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  127300. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  127301. */
  127302. RtreeNode *pDeleted;
  127303. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  127304. /* Statements to read/write/delete a record from xxx_node */
  127305. sqlite3_stmt *pReadNode;
  127306. sqlite3_stmt *pWriteNode;
  127307. sqlite3_stmt *pDeleteNode;
  127308. /* Statements to read/write/delete a record from xxx_rowid */
  127309. sqlite3_stmt *pReadRowid;
  127310. sqlite3_stmt *pWriteRowid;
  127311. sqlite3_stmt *pDeleteRowid;
  127312. /* Statements to read/write/delete a record from xxx_parent */
  127313. sqlite3_stmt *pReadParent;
  127314. sqlite3_stmt *pWriteParent;
  127315. sqlite3_stmt *pDeleteParent;
  127316. int eCoordType;
  127317. };
  127318. /* Possible values for eCoordType: */
  127319. #define RTREE_COORD_REAL32 0
  127320. #define RTREE_COORD_INT32 1
  127321. /*
  127322. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  127323. ** only deal with integer coordinates. No floating point operations
  127324. ** will be done.
  127325. */
  127326. #ifdef SQLITE_RTREE_INT_ONLY
  127327. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  127328. typedef int RtreeValue; /* Low accuracy coordinate */
  127329. #else
  127330. typedef double RtreeDValue; /* High accuracy coordinate */
  127331. typedef float RtreeValue; /* Low accuracy coordinate */
  127332. #endif
  127333. /*
  127334. ** The minimum number of cells allowed for a node is a third of the
  127335. ** maximum. In Gutman's notation:
  127336. **
  127337. ** m = M/3
  127338. **
  127339. ** If an R*-tree "Reinsert" operation is required, the same number of
  127340. ** cells are removed from the overfull node and reinserted into the tree.
  127341. */
  127342. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  127343. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  127344. #define RTREE_MAXCELLS 51
  127345. /*
  127346. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  127347. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  127348. ** Therefore all non-root nodes must contain at least 3 entries. Since
  127349. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  127350. ** 40 or less.
  127351. */
  127352. #define RTREE_MAX_DEPTH 40
  127353. /*
  127354. ** An rtree cursor object.
  127355. */
  127356. struct RtreeCursor {
  127357. sqlite3_vtab_cursor base;
  127358. RtreeNode *pNode; /* Node cursor is currently pointing at */
  127359. int iCell; /* Index of current cell in pNode */
  127360. int iStrategy; /* Copy of idxNum search parameter */
  127361. int nConstraint; /* Number of entries in aConstraint */
  127362. RtreeConstraint *aConstraint; /* Search constraints. */
  127363. };
  127364. union RtreeCoord {
  127365. RtreeValue f;
  127366. int i;
  127367. };
  127368. /*
  127369. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  127370. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  127371. ** variable pRtree points to the Rtree structure associated with the
  127372. ** RtreeCoord.
  127373. */
  127374. #ifdef SQLITE_RTREE_INT_ONLY
  127375. # define DCOORD(coord) ((RtreeDValue)coord.i)
  127376. #else
  127377. # define DCOORD(coord) ( \
  127378. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  127379. ((double)coord.f) : \
  127380. ((double)coord.i) \
  127381. )
  127382. #endif
  127383. /*
  127384. ** A search constraint.
  127385. */
  127386. struct RtreeConstraint {
  127387. int iCoord; /* Index of constrained coordinate */
  127388. int op; /* Constraining operation */
  127389. RtreeDValue rValue; /* Constraint value. */
  127390. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  127391. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  127392. };
  127393. /* Possible values for RtreeConstraint.op */
  127394. #define RTREE_EQ 0x41
  127395. #define RTREE_LE 0x42
  127396. #define RTREE_LT 0x43
  127397. #define RTREE_GE 0x44
  127398. #define RTREE_GT 0x45
  127399. #define RTREE_MATCH 0x46
  127400. /*
  127401. ** An rtree structure node.
  127402. */
  127403. struct RtreeNode {
  127404. RtreeNode *pParent; /* Parent node */
  127405. i64 iNode;
  127406. int nRef;
  127407. int isDirty;
  127408. u8 *zData;
  127409. RtreeNode *pNext; /* Next node in this hash chain */
  127410. };
  127411. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  127412. /*
  127413. ** Structure to store a deserialized rtree record.
  127414. */
  127415. struct RtreeCell {
  127416. i64 iRowid;
  127417. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  127418. };
  127419. /*
  127420. ** Value for the first field of every RtreeMatchArg object. The MATCH
  127421. ** operator tests that the first field of a blob operand matches this
  127422. ** value to avoid operating on invalid blobs (which could cause a segfault).
  127423. */
  127424. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  127425. /*
  127426. ** An instance of this structure must be supplied as a blob argument to
  127427. ** the right-hand-side of an SQL MATCH operator used to constrain an
  127428. ** r-tree query.
  127429. */
  127430. struct RtreeMatchArg {
  127431. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  127432. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  127433. void *pContext;
  127434. int nParam;
  127435. RtreeDValue aParam[1];
  127436. };
  127437. /*
  127438. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  127439. ** a single instance of the following structure is allocated. It is used
  127440. ** as the context for the user-function created by by s_r_g_c(). The object
  127441. ** is eventually deleted by the destructor mechanism provided by
  127442. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  127443. ** the geometry callback function).
  127444. */
  127445. struct RtreeGeomCallback {
  127446. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  127447. void *pContext;
  127448. };
  127449. #ifndef MAX
  127450. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  127451. #endif
  127452. #ifndef MIN
  127453. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  127454. #endif
  127455. /*
  127456. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  127457. ** 64 bit integer. The deserialized value is returned.
  127458. */
  127459. static int readInt16(u8 *p){
  127460. return (p[0]<<8) + p[1];
  127461. }
  127462. static void readCoord(u8 *p, RtreeCoord *pCoord){
  127463. u32 i = (
  127464. (((u32)p[0]) << 24) +
  127465. (((u32)p[1]) << 16) +
  127466. (((u32)p[2]) << 8) +
  127467. (((u32)p[3]) << 0)
  127468. );
  127469. *(u32 *)pCoord = i;
  127470. }
  127471. static i64 readInt64(u8 *p){
  127472. return (
  127473. (((i64)p[0]) << 56) +
  127474. (((i64)p[1]) << 48) +
  127475. (((i64)p[2]) << 40) +
  127476. (((i64)p[3]) << 32) +
  127477. (((i64)p[4]) << 24) +
  127478. (((i64)p[5]) << 16) +
  127479. (((i64)p[6]) << 8) +
  127480. (((i64)p[7]) << 0)
  127481. );
  127482. }
  127483. /*
  127484. ** Functions to serialize a 16 bit integer, 32 bit real number and
  127485. ** 64 bit integer. The value returned is the number of bytes written
  127486. ** to the argument buffer (always 2, 4 and 8 respectively).
  127487. */
  127488. static int writeInt16(u8 *p, int i){
  127489. p[0] = (i>> 8)&0xFF;
  127490. p[1] = (i>> 0)&0xFF;
  127491. return 2;
  127492. }
  127493. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  127494. u32 i;
  127495. assert( sizeof(RtreeCoord)==4 );
  127496. assert( sizeof(u32)==4 );
  127497. i = *(u32 *)pCoord;
  127498. p[0] = (i>>24)&0xFF;
  127499. p[1] = (i>>16)&0xFF;
  127500. p[2] = (i>> 8)&0xFF;
  127501. p[3] = (i>> 0)&0xFF;
  127502. return 4;
  127503. }
  127504. static int writeInt64(u8 *p, i64 i){
  127505. p[0] = (i>>56)&0xFF;
  127506. p[1] = (i>>48)&0xFF;
  127507. p[2] = (i>>40)&0xFF;
  127508. p[3] = (i>>32)&0xFF;
  127509. p[4] = (i>>24)&0xFF;
  127510. p[5] = (i>>16)&0xFF;
  127511. p[6] = (i>> 8)&0xFF;
  127512. p[7] = (i>> 0)&0xFF;
  127513. return 8;
  127514. }
  127515. /*
  127516. ** Increment the reference count of node p.
  127517. */
  127518. static void nodeReference(RtreeNode *p){
  127519. if( p ){
  127520. p->nRef++;
  127521. }
  127522. }
  127523. /*
  127524. ** Clear the content of node p (set all bytes to 0x00).
  127525. */
  127526. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  127527. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  127528. p->isDirty = 1;
  127529. }
  127530. /*
  127531. ** Given a node number iNode, return the corresponding key to use
  127532. ** in the Rtree.aHash table.
  127533. */
  127534. static int nodeHash(i64 iNode){
  127535. return (
  127536. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  127537. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  127538. ) % HASHSIZE;
  127539. }
  127540. /*
  127541. ** Search the node hash table for node iNode. If found, return a pointer
  127542. ** to it. Otherwise, return 0.
  127543. */
  127544. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  127545. RtreeNode *p;
  127546. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  127547. return p;
  127548. }
  127549. /*
  127550. ** Add node pNode to the node hash table.
  127551. */
  127552. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  127553. int iHash;
  127554. assert( pNode->pNext==0 );
  127555. iHash = nodeHash(pNode->iNode);
  127556. pNode->pNext = pRtree->aHash[iHash];
  127557. pRtree->aHash[iHash] = pNode;
  127558. }
  127559. /*
  127560. ** Remove node pNode from the node hash table.
  127561. */
  127562. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  127563. RtreeNode **pp;
  127564. if( pNode->iNode!=0 ){
  127565. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  127566. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  127567. *pp = pNode->pNext;
  127568. pNode->pNext = 0;
  127569. }
  127570. }
  127571. /*
  127572. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  127573. ** indicating that node has not yet been assigned a node number. It is
  127574. ** assigned a node number when nodeWrite() is called to write the
  127575. ** node contents out to the database.
  127576. */
  127577. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  127578. RtreeNode *pNode;
  127579. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  127580. if( pNode ){
  127581. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  127582. pNode->zData = (u8 *)&pNode[1];
  127583. pNode->nRef = 1;
  127584. pNode->pParent = pParent;
  127585. pNode->isDirty = 1;
  127586. nodeReference(pParent);
  127587. }
  127588. return pNode;
  127589. }
  127590. /*
  127591. ** Obtain a reference to an r-tree node.
  127592. */
  127593. static int
  127594. nodeAcquire(
  127595. Rtree *pRtree, /* R-tree structure */
  127596. i64 iNode, /* Node number to load */
  127597. RtreeNode *pParent, /* Either the parent node or NULL */
  127598. RtreeNode **ppNode /* OUT: Acquired node */
  127599. ){
  127600. int rc;
  127601. int rc2 = SQLITE_OK;
  127602. RtreeNode *pNode;
  127603. /* Check if the requested node is already in the hash table. If so,
  127604. ** increase its reference count and return it.
  127605. */
  127606. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  127607. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  127608. if( pParent && !pNode->pParent ){
  127609. nodeReference(pParent);
  127610. pNode->pParent = pParent;
  127611. }
  127612. pNode->nRef++;
  127613. *ppNode = pNode;
  127614. return SQLITE_OK;
  127615. }
  127616. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  127617. rc = sqlite3_step(pRtree->pReadNode);
  127618. if( rc==SQLITE_ROW ){
  127619. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  127620. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  127621. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  127622. if( !pNode ){
  127623. rc2 = SQLITE_NOMEM;
  127624. }else{
  127625. pNode->pParent = pParent;
  127626. pNode->zData = (u8 *)&pNode[1];
  127627. pNode->nRef = 1;
  127628. pNode->iNode = iNode;
  127629. pNode->isDirty = 0;
  127630. pNode->pNext = 0;
  127631. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  127632. nodeReference(pParent);
  127633. }
  127634. }
  127635. }
  127636. rc = sqlite3_reset(pRtree->pReadNode);
  127637. if( rc==SQLITE_OK ) rc = rc2;
  127638. /* If the root node was just loaded, set pRtree->iDepth to the height
  127639. ** of the r-tree structure. A height of zero means all data is stored on
  127640. ** the root node. A height of one means the children of the root node
  127641. ** are the leaves, and so on. If the depth as specified on the root node
  127642. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  127643. */
  127644. if( pNode && iNode==1 ){
  127645. pRtree->iDepth = readInt16(pNode->zData);
  127646. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  127647. rc = SQLITE_CORRUPT_VTAB;
  127648. }
  127649. }
  127650. /* If no error has occurred so far, check if the "number of entries"
  127651. ** field on the node is too large. If so, set the return code to
  127652. ** SQLITE_CORRUPT_VTAB.
  127653. */
  127654. if( pNode && rc==SQLITE_OK ){
  127655. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  127656. rc = SQLITE_CORRUPT_VTAB;
  127657. }
  127658. }
  127659. if( rc==SQLITE_OK ){
  127660. if( pNode!=0 ){
  127661. nodeHashInsert(pRtree, pNode);
  127662. }else{
  127663. rc = SQLITE_CORRUPT_VTAB;
  127664. }
  127665. *ppNode = pNode;
  127666. }else{
  127667. sqlite3_free(pNode);
  127668. *ppNode = 0;
  127669. }
  127670. return rc;
  127671. }
  127672. /*
  127673. ** Overwrite cell iCell of node pNode with the contents of pCell.
  127674. */
  127675. static void nodeOverwriteCell(
  127676. Rtree *pRtree,
  127677. RtreeNode *pNode,
  127678. RtreeCell *pCell,
  127679. int iCell
  127680. ){
  127681. int ii;
  127682. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  127683. p += writeInt64(p, pCell->iRowid);
  127684. for(ii=0; ii<(pRtree->nDim*2); ii++){
  127685. p += writeCoord(p, &pCell->aCoord[ii]);
  127686. }
  127687. pNode->isDirty = 1;
  127688. }
  127689. /*
  127690. ** Remove cell the cell with index iCell from node pNode.
  127691. */
  127692. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  127693. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  127694. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  127695. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  127696. memmove(pDst, pSrc, nByte);
  127697. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  127698. pNode->isDirty = 1;
  127699. }
  127700. /*
  127701. ** Insert the contents of cell pCell into node pNode. If the insert
  127702. ** is successful, return SQLITE_OK.
  127703. **
  127704. ** If there is not enough free space in pNode, return SQLITE_FULL.
  127705. */
  127706. static int
  127707. nodeInsertCell(
  127708. Rtree *pRtree,
  127709. RtreeNode *pNode,
  127710. RtreeCell *pCell
  127711. ){
  127712. int nCell; /* Current number of cells in pNode */
  127713. int nMaxCell; /* Maximum number of cells for pNode */
  127714. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  127715. nCell = NCELL(pNode);
  127716. assert( nCell<=nMaxCell );
  127717. if( nCell<nMaxCell ){
  127718. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  127719. writeInt16(&pNode->zData[2], nCell+1);
  127720. pNode->isDirty = 1;
  127721. }
  127722. return (nCell==nMaxCell);
  127723. }
  127724. /*
  127725. ** If the node is dirty, write it out to the database.
  127726. */
  127727. static int
  127728. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  127729. int rc = SQLITE_OK;
  127730. if( pNode->isDirty ){
  127731. sqlite3_stmt *p = pRtree->pWriteNode;
  127732. if( pNode->iNode ){
  127733. sqlite3_bind_int64(p, 1, pNode->iNode);
  127734. }else{
  127735. sqlite3_bind_null(p, 1);
  127736. }
  127737. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  127738. sqlite3_step(p);
  127739. pNode->isDirty = 0;
  127740. rc = sqlite3_reset(p);
  127741. if( pNode->iNode==0 && rc==SQLITE_OK ){
  127742. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  127743. nodeHashInsert(pRtree, pNode);
  127744. }
  127745. }
  127746. return rc;
  127747. }
  127748. /*
  127749. ** Release a reference to a node. If the node is dirty and the reference
  127750. ** count drops to zero, the node data is written to the database.
  127751. */
  127752. static int
  127753. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  127754. int rc = SQLITE_OK;
  127755. if( pNode ){
  127756. assert( pNode->nRef>0 );
  127757. pNode->nRef--;
  127758. if( pNode->nRef==0 ){
  127759. if( pNode->iNode==1 ){
  127760. pRtree->iDepth = -1;
  127761. }
  127762. if( pNode->pParent ){
  127763. rc = nodeRelease(pRtree, pNode->pParent);
  127764. }
  127765. if( rc==SQLITE_OK ){
  127766. rc = nodeWrite(pRtree, pNode);
  127767. }
  127768. nodeHashDelete(pRtree, pNode);
  127769. sqlite3_free(pNode);
  127770. }
  127771. }
  127772. return rc;
  127773. }
  127774. /*
  127775. ** Return the 64-bit integer value associated with cell iCell of
  127776. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  127777. ** an internal node, then the 64-bit integer is a child page number.
  127778. */
  127779. static i64 nodeGetRowid(
  127780. Rtree *pRtree,
  127781. RtreeNode *pNode,
  127782. int iCell
  127783. ){
  127784. assert( iCell<NCELL(pNode) );
  127785. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  127786. }
  127787. /*
  127788. ** Return coordinate iCoord from cell iCell in node pNode.
  127789. */
  127790. static void nodeGetCoord(
  127791. Rtree *pRtree,
  127792. RtreeNode *pNode,
  127793. int iCell,
  127794. int iCoord,
  127795. RtreeCoord *pCoord /* Space to write result to */
  127796. ){
  127797. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  127798. }
  127799. /*
  127800. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  127801. ** to by pCell with the results.
  127802. */
  127803. static void nodeGetCell(
  127804. Rtree *pRtree,
  127805. RtreeNode *pNode,
  127806. int iCell,
  127807. RtreeCell *pCell
  127808. ){
  127809. int ii;
  127810. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  127811. for(ii=0; ii<pRtree->nDim*2; ii++){
  127812. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  127813. }
  127814. }
  127815. /* Forward declaration for the function that does the work of
  127816. ** the virtual table module xCreate() and xConnect() methods.
  127817. */
  127818. static int rtreeInit(
  127819. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  127820. );
  127821. /*
  127822. ** Rtree virtual table module xCreate method.
  127823. */
  127824. static int rtreeCreate(
  127825. sqlite3 *db,
  127826. void *pAux,
  127827. int argc, const char *const*argv,
  127828. sqlite3_vtab **ppVtab,
  127829. char **pzErr
  127830. ){
  127831. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  127832. }
  127833. /*
  127834. ** Rtree virtual table module xConnect method.
  127835. */
  127836. static int rtreeConnect(
  127837. sqlite3 *db,
  127838. void *pAux,
  127839. int argc, const char *const*argv,
  127840. sqlite3_vtab **ppVtab,
  127841. char **pzErr
  127842. ){
  127843. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  127844. }
  127845. /*
  127846. ** Increment the r-tree reference count.
  127847. */
  127848. static void rtreeReference(Rtree *pRtree){
  127849. pRtree->nBusy++;
  127850. }
  127851. /*
  127852. ** Decrement the r-tree reference count. When the reference count reaches
  127853. ** zero the structure is deleted.
  127854. */
  127855. static void rtreeRelease(Rtree *pRtree){
  127856. pRtree->nBusy--;
  127857. if( pRtree->nBusy==0 ){
  127858. sqlite3_finalize(pRtree->pReadNode);
  127859. sqlite3_finalize(pRtree->pWriteNode);
  127860. sqlite3_finalize(pRtree->pDeleteNode);
  127861. sqlite3_finalize(pRtree->pReadRowid);
  127862. sqlite3_finalize(pRtree->pWriteRowid);
  127863. sqlite3_finalize(pRtree->pDeleteRowid);
  127864. sqlite3_finalize(pRtree->pReadParent);
  127865. sqlite3_finalize(pRtree->pWriteParent);
  127866. sqlite3_finalize(pRtree->pDeleteParent);
  127867. sqlite3_free(pRtree);
  127868. }
  127869. }
  127870. /*
  127871. ** Rtree virtual table module xDisconnect method.
  127872. */
  127873. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  127874. rtreeRelease((Rtree *)pVtab);
  127875. return SQLITE_OK;
  127876. }
  127877. /*
  127878. ** Rtree virtual table module xDestroy method.
  127879. */
  127880. static int rtreeDestroy(sqlite3_vtab *pVtab){
  127881. Rtree *pRtree = (Rtree *)pVtab;
  127882. int rc;
  127883. char *zCreate = sqlite3_mprintf(
  127884. "DROP TABLE '%q'.'%q_node';"
  127885. "DROP TABLE '%q'.'%q_rowid';"
  127886. "DROP TABLE '%q'.'%q_parent';",
  127887. pRtree->zDb, pRtree->zName,
  127888. pRtree->zDb, pRtree->zName,
  127889. pRtree->zDb, pRtree->zName
  127890. );
  127891. if( !zCreate ){
  127892. rc = SQLITE_NOMEM;
  127893. }else{
  127894. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  127895. sqlite3_free(zCreate);
  127896. }
  127897. if( rc==SQLITE_OK ){
  127898. rtreeRelease(pRtree);
  127899. }
  127900. return rc;
  127901. }
  127902. /*
  127903. ** Rtree virtual table module xOpen method.
  127904. */
  127905. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  127906. int rc = SQLITE_NOMEM;
  127907. RtreeCursor *pCsr;
  127908. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  127909. if( pCsr ){
  127910. memset(pCsr, 0, sizeof(RtreeCursor));
  127911. pCsr->base.pVtab = pVTab;
  127912. rc = SQLITE_OK;
  127913. }
  127914. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  127915. return rc;
  127916. }
  127917. /*
  127918. ** Free the RtreeCursor.aConstraint[] array and its contents.
  127919. */
  127920. static void freeCursorConstraints(RtreeCursor *pCsr){
  127921. if( pCsr->aConstraint ){
  127922. int i; /* Used to iterate through constraint array */
  127923. for(i=0; i<pCsr->nConstraint; i++){
  127924. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  127925. if( pGeom ){
  127926. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  127927. sqlite3_free(pGeom);
  127928. }
  127929. }
  127930. sqlite3_free(pCsr->aConstraint);
  127931. pCsr->aConstraint = 0;
  127932. }
  127933. }
  127934. /*
  127935. ** Rtree virtual table module xClose method.
  127936. */
  127937. static int rtreeClose(sqlite3_vtab_cursor *cur){
  127938. Rtree *pRtree = (Rtree *)(cur->pVtab);
  127939. int rc;
  127940. RtreeCursor *pCsr = (RtreeCursor *)cur;
  127941. freeCursorConstraints(pCsr);
  127942. rc = nodeRelease(pRtree, pCsr->pNode);
  127943. sqlite3_free(pCsr);
  127944. return rc;
  127945. }
  127946. /*
  127947. ** Rtree virtual table module xEof method.
  127948. **
  127949. ** Return non-zero if the cursor does not currently point to a valid
  127950. ** record (i.e if the scan has finished), or zero otherwise.
  127951. */
  127952. static int rtreeEof(sqlite3_vtab_cursor *cur){
  127953. RtreeCursor *pCsr = (RtreeCursor *)cur;
  127954. return (pCsr->pNode==0);
  127955. }
  127956. /*
  127957. ** The r-tree constraint passed as the second argument to this function is
  127958. ** guaranteed to be a MATCH constraint.
  127959. */
  127960. static int testRtreeGeom(
  127961. Rtree *pRtree, /* R-Tree object */
  127962. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  127963. RtreeCell *pCell, /* Cell to test */
  127964. int *pbRes /* OUT: Test result */
  127965. ){
  127966. int i;
  127967. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  127968. int nCoord = pRtree->nDim*2;
  127969. assert( pConstraint->op==RTREE_MATCH );
  127970. assert( pConstraint->pGeom );
  127971. for(i=0; i<nCoord; i++){
  127972. aCoord[i] = DCOORD(pCell->aCoord[i]);
  127973. }
  127974. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  127975. }
  127976. /*
  127977. ** Cursor pCursor currently points to a cell in a non-leaf page.
  127978. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  127979. ** (excluded) by the constraints in the pCursor->aConstraint[]
  127980. ** array, or false otherwise.
  127981. **
  127982. ** Return SQLITE_OK if successful or an SQLite error code if an error
  127983. ** occurs within a geometry callback.
  127984. */
  127985. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  127986. RtreeCell cell;
  127987. int ii;
  127988. int bRes = 0;
  127989. int rc = SQLITE_OK;
  127990. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  127991. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  127992. RtreeConstraint *p = &pCursor->aConstraint[ii];
  127993. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  127994. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  127995. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  127996. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  127997. );
  127998. switch( p->op ){
  127999. case RTREE_LE: case RTREE_LT:
  128000. bRes = p->rValue<cell_min;
  128001. break;
  128002. case RTREE_GE: case RTREE_GT:
  128003. bRes = p->rValue>cell_max;
  128004. break;
  128005. case RTREE_EQ:
  128006. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  128007. break;
  128008. default: {
  128009. assert( p->op==RTREE_MATCH );
  128010. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  128011. bRes = !bRes;
  128012. break;
  128013. }
  128014. }
  128015. }
  128016. *pbEof = bRes;
  128017. return rc;
  128018. }
  128019. /*
  128020. ** Test if the cell that cursor pCursor currently points to
  128021. ** would be filtered (excluded) by the constraints in the
  128022. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  128023. ** returning. If the cell is not filtered (excluded) by the constraints,
  128024. ** set pbEof to zero.
  128025. **
  128026. ** Return SQLITE_OK if successful or an SQLite error code if an error
  128027. ** occurs within a geometry callback.
  128028. **
  128029. ** This function assumes that the cell is part of a leaf node.
  128030. */
  128031. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  128032. RtreeCell cell;
  128033. int ii;
  128034. *pbEof = 0;
  128035. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  128036. for(ii=0; ii<pCursor->nConstraint; ii++){
  128037. RtreeConstraint *p = &pCursor->aConstraint[ii];
  128038. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  128039. int res;
  128040. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  128041. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  128042. );
  128043. switch( p->op ){
  128044. case RTREE_LE: res = (coord<=p->rValue); break;
  128045. case RTREE_LT: res = (coord<p->rValue); break;
  128046. case RTREE_GE: res = (coord>=p->rValue); break;
  128047. case RTREE_GT: res = (coord>p->rValue); break;
  128048. case RTREE_EQ: res = (coord==p->rValue); break;
  128049. default: {
  128050. int rc;
  128051. assert( p->op==RTREE_MATCH );
  128052. rc = testRtreeGeom(pRtree, p, &cell, &res);
  128053. if( rc!=SQLITE_OK ){
  128054. return rc;
  128055. }
  128056. break;
  128057. }
  128058. }
  128059. if( !res ){
  128060. *pbEof = 1;
  128061. return SQLITE_OK;
  128062. }
  128063. }
  128064. return SQLITE_OK;
  128065. }
  128066. /*
  128067. ** Cursor pCursor currently points at a node that heads a sub-tree of
  128068. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  128069. ** to point to the left-most cell of the sub-tree that matches the
  128070. ** configured constraints.
  128071. */
  128072. static int descendToCell(
  128073. Rtree *pRtree,
  128074. RtreeCursor *pCursor,
  128075. int iHeight,
  128076. int *pEof /* OUT: Set to true if cannot descend */
  128077. ){
  128078. int isEof;
  128079. int rc;
  128080. int ii;
  128081. RtreeNode *pChild;
  128082. sqlite3_int64 iRowid;
  128083. RtreeNode *pSavedNode = pCursor->pNode;
  128084. int iSavedCell = pCursor->iCell;
  128085. assert( iHeight>=0 );
  128086. if( iHeight==0 ){
  128087. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  128088. }else{
  128089. rc = testRtreeCell(pRtree, pCursor, &isEof);
  128090. }
  128091. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  128092. goto descend_to_cell_out;
  128093. }
  128094. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  128095. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  128096. if( rc!=SQLITE_OK ){
  128097. goto descend_to_cell_out;
  128098. }
  128099. nodeRelease(pRtree, pCursor->pNode);
  128100. pCursor->pNode = pChild;
  128101. isEof = 1;
  128102. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  128103. pCursor->iCell = ii;
  128104. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  128105. if( rc!=SQLITE_OK ){
  128106. goto descend_to_cell_out;
  128107. }
  128108. }
  128109. if( isEof ){
  128110. assert( pCursor->pNode==pChild );
  128111. nodeReference(pSavedNode);
  128112. nodeRelease(pRtree, pChild);
  128113. pCursor->pNode = pSavedNode;
  128114. pCursor->iCell = iSavedCell;
  128115. }
  128116. descend_to_cell_out:
  128117. *pEof = isEof;
  128118. return rc;
  128119. }
  128120. /*
  128121. ** One of the cells in node pNode is guaranteed to have a 64-bit
  128122. ** integer value equal to iRowid. Return the index of this cell.
  128123. */
  128124. static int nodeRowidIndex(
  128125. Rtree *pRtree,
  128126. RtreeNode *pNode,
  128127. i64 iRowid,
  128128. int *piIndex
  128129. ){
  128130. int ii;
  128131. int nCell = NCELL(pNode);
  128132. for(ii=0; ii<nCell; ii++){
  128133. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  128134. *piIndex = ii;
  128135. return SQLITE_OK;
  128136. }
  128137. }
  128138. return SQLITE_CORRUPT_VTAB;
  128139. }
  128140. /*
  128141. ** Return the index of the cell containing a pointer to node pNode
  128142. ** in its parent. If pNode is the root node, return -1.
  128143. */
  128144. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  128145. RtreeNode *pParent = pNode->pParent;
  128146. if( pParent ){
  128147. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  128148. }
  128149. *piIndex = -1;
  128150. return SQLITE_OK;
  128151. }
  128152. /*
  128153. ** Rtree virtual table module xNext method.
  128154. */
  128155. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  128156. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  128157. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  128158. int rc = SQLITE_OK;
  128159. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  128160. ** already at EOF. It is against the rules to call the xNext() method of
  128161. ** a cursor that has already reached EOF.
  128162. */
  128163. assert( pCsr->pNode );
  128164. if( pCsr->iStrategy==1 ){
  128165. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  128166. nodeRelease(pRtree, pCsr->pNode);
  128167. pCsr->pNode = 0;
  128168. }else{
  128169. /* Move to the next entry that matches the configured constraints. */
  128170. int iHeight = 0;
  128171. while( pCsr->pNode ){
  128172. RtreeNode *pNode = pCsr->pNode;
  128173. int nCell = NCELL(pNode);
  128174. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  128175. int isEof;
  128176. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  128177. if( rc!=SQLITE_OK || !isEof ){
  128178. return rc;
  128179. }
  128180. }
  128181. pCsr->pNode = pNode->pParent;
  128182. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  128183. if( rc!=SQLITE_OK ){
  128184. return rc;
  128185. }
  128186. nodeReference(pCsr->pNode);
  128187. nodeRelease(pRtree, pNode);
  128188. iHeight++;
  128189. }
  128190. }
  128191. return rc;
  128192. }
  128193. /*
  128194. ** Rtree virtual table module xRowid method.
  128195. */
  128196. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  128197. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  128198. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  128199. assert(pCsr->pNode);
  128200. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  128201. return SQLITE_OK;
  128202. }
  128203. /*
  128204. ** Rtree virtual table module xColumn method.
  128205. */
  128206. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  128207. Rtree *pRtree = (Rtree *)cur->pVtab;
  128208. RtreeCursor *pCsr = (RtreeCursor *)cur;
  128209. if( i==0 ){
  128210. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  128211. sqlite3_result_int64(ctx, iRowid);
  128212. }else{
  128213. RtreeCoord c;
  128214. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  128215. #ifndef SQLITE_RTREE_INT_ONLY
  128216. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  128217. sqlite3_result_double(ctx, c.f);
  128218. }else
  128219. #endif
  128220. {
  128221. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  128222. sqlite3_result_int(ctx, c.i);
  128223. }
  128224. }
  128225. return SQLITE_OK;
  128226. }
  128227. /*
  128228. ** Use nodeAcquire() to obtain the leaf node containing the record with
  128229. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  128230. ** return SQLITE_OK. If there is no such record in the table, set
  128231. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  128232. ** to zero and return an SQLite error code.
  128233. */
  128234. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  128235. int rc;
  128236. *ppLeaf = 0;
  128237. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  128238. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  128239. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  128240. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  128241. sqlite3_reset(pRtree->pReadRowid);
  128242. }else{
  128243. rc = sqlite3_reset(pRtree->pReadRowid);
  128244. }
  128245. return rc;
  128246. }
  128247. /*
  128248. ** This function is called to configure the RtreeConstraint object passed
  128249. ** as the second argument for a MATCH constraint. The value passed as the
  128250. ** first argument to this function is the right-hand operand to the MATCH
  128251. ** operator.
  128252. */
  128253. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  128254. RtreeMatchArg *p;
  128255. sqlite3_rtree_geometry *pGeom;
  128256. int nBlob;
  128257. /* Check that value is actually a blob. */
  128258. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  128259. /* Check that the blob is roughly the right size. */
  128260. nBlob = sqlite3_value_bytes(pValue);
  128261. if( nBlob<(int)sizeof(RtreeMatchArg)
  128262. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  128263. ){
  128264. return SQLITE_ERROR;
  128265. }
  128266. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  128267. sizeof(sqlite3_rtree_geometry) + nBlob
  128268. );
  128269. if( !pGeom ) return SQLITE_NOMEM;
  128270. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  128271. p = (RtreeMatchArg *)&pGeom[1];
  128272. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  128273. if( p->magic!=RTREE_GEOMETRY_MAGIC
  128274. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  128275. ){
  128276. sqlite3_free(pGeom);
  128277. return SQLITE_ERROR;
  128278. }
  128279. pGeom->pContext = p->pContext;
  128280. pGeom->nParam = p->nParam;
  128281. pGeom->aParam = p->aParam;
  128282. pCons->xGeom = p->xGeom;
  128283. pCons->pGeom = pGeom;
  128284. return SQLITE_OK;
  128285. }
  128286. /*
  128287. ** Rtree virtual table module xFilter method.
  128288. */
  128289. static int rtreeFilter(
  128290. sqlite3_vtab_cursor *pVtabCursor,
  128291. int idxNum, const char *idxStr,
  128292. int argc, sqlite3_value **argv
  128293. ){
  128294. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  128295. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  128296. RtreeNode *pRoot = 0;
  128297. int ii;
  128298. int rc = SQLITE_OK;
  128299. rtreeReference(pRtree);
  128300. freeCursorConstraints(pCsr);
  128301. pCsr->iStrategy = idxNum;
  128302. if( idxNum==1 ){
  128303. /* Special case - lookup by rowid. */
  128304. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  128305. i64 iRowid = sqlite3_value_int64(argv[0]);
  128306. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  128307. pCsr->pNode = pLeaf;
  128308. if( pLeaf ){
  128309. assert( rc==SQLITE_OK );
  128310. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  128311. }
  128312. }else{
  128313. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  128314. ** with the configured constraints.
  128315. */
  128316. if( argc>0 ){
  128317. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  128318. pCsr->nConstraint = argc;
  128319. if( !pCsr->aConstraint ){
  128320. rc = SQLITE_NOMEM;
  128321. }else{
  128322. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  128323. assert( (idxStr==0 && argc==0)
  128324. || (idxStr && (int)strlen(idxStr)==argc*2) );
  128325. for(ii=0; ii<argc; ii++){
  128326. RtreeConstraint *p = &pCsr->aConstraint[ii];
  128327. p->op = idxStr[ii*2];
  128328. p->iCoord = idxStr[ii*2+1]-'a';
  128329. if( p->op==RTREE_MATCH ){
  128330. /* A MATCH operator. The right-hand-side must be a blob that
  128331. ** can be cast into an RtreeMatchArg object. One created using
  128332. ** an sqlite3_rtree_geometry_callback() SQL user function.
  128333. */
  128334. rc = deserializeGeometry(argv[ii], p);
  128335. if( rc!=SQLITE_OK ){
  128336. break;
  128337. }
  128338. }else{
  128339. #ifdef SQLITE_RTREE_INT_ONLY
  128340. p->rValue = sqlite3_value_int64(argv[ii]);
  128341. #else
  128342. p->rValue = sqlite3_value_double(argv[ii]);
  128343. #endif
  128344. }
  128345. }
  128346. }
  128347. }
  128348. if( rc==SQLITE_OK ){
  128349. pCsr->pNode = 0;
  128350. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  128351. }
  128352. if( rc==SQLITE_OK ){
  128353. int isEof = 1;
  128354. int nCell = NCELL(pRoot);
  128355. pCsr->pNode = pRoot;
  128356. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  128357. assert( pCsr->pNode==pRoot );
  128358. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  128359. if( !isEof ){
  128360. break;
  128361. }
  128362. }
  128363. if( rc==SQLITE_OK && isEof ){
  128364. assert( pCsr->pNode==pRoot );
  128365. nodeRelease(pRtree, pRoot);
  128366. pCsr->pNode = 0;
  128367. }
  128368. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  128369. }
  128370. }
  128371. rtreeRelease(pRtree);
  128372. return rc;
  128373. }
  128374. /*
  128375. ** Rtree virtual table module xBestIndex method. There are three
  128376. ** table scan strategies to choose from (in order from most to
  128377. ** least desirable):
  128378. **
  128379. ** idxNum idxStr Strategy
  128380. ** ------------------------------------------------
  128381. ** 1 Unused Direct lookup by rowid.
  128382. ** 2 See below R-tree query or full-table scan.
  128383. ** ------------------------------------------------
  128384. **
  128385. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  128386. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  128387. ** constraint used. The first two bytes of idxStr correspond to
  128388. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  128389. ** (argvIndex==1) etc.
  128390. **
  128391. ** The first of each pair of bytes in idxStr identifies the constraint
  128392. ** operator as follows:
  128393. **
  128394. ** Operator Byte Value
  128395. ** ----------------------
  128396. ** = 0x41 ('A')
  128397. ** <= 0x42 ('B')
  128398. ** < 0x43 ('C')
  128399. ** >= 0x44 ('D')
  128400. ** > 0x45 ('E')
  128401. ** MATCH 0x46 ('F')
  128402. ** ----------------------
  128403. **
  128404. ** The second of each pair of bytes identifies the coordinate column
  128405. ** to which the constraint applies. The leftmost coordinate column
  128406. ** is 'a', the second from the left 'b' etc.
  128407. */
  128408. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  128409. int rc = SQLITE_OK;
  128410. int ii;
  128411. int iIdx = 0;
  128412. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  128413. memset(zIdxStr, 0, sizeof(zIdxStr));
  128414. UNUSED_PARAMETER(tab);
  128415. assert( pIdxInfo->idxStr==0 );
  128416. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  128417. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  128418. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  128419. /* We have an equality constraint on the rowid. Use strategy 1. */
  128420. int jj;
  128421. for(jj=0; jj<ii; jj++){
  128422. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  128423. pIdxInfo->aConstraintUsage[jj].omit = 0;
  128424. }
  128425. pIdxInfo->idxNum = 1;
  128426. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  128427. pIdxInfo->aConstraintUsage[jj].omit = 1;
  128428. /* This strategy involves a two rowid lookups on an B-Tree structures
  128429. ** and then a linear search of an R-Tree node. This should be
  128430. ** considered almost as quick as a direct rowid lookup (for which
  128431. ** sqlite uses an internal cost of 0.0).
  128432. */
  128433. pIdxInfo->estimatedCost = 10.0;
  128434. return SQLITE_OK;
  128435. }
  128436. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  128437. u8 op;
  128438. switch( p->op ){
  128439. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  128440. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  128441. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  128442. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  128443. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  128444. default:
  128445. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  128446. op = RTREE_MATCH;
  128447. break;
  128448. }
  128449. zIdxStr[iIdx++] = op;
  128450. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  128451. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  128452. pIdxInfo->aConstraintUsage[ii].omit = 1;
  128453. }
  128454. }
  128455. pIdxInfo->idxNum = 2;
  128456. pIdxInfo->needToFreeIdxStr = 1;
  128457. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  128458. return SQLITE_NOMEM;
  128459. }
  128460. assert( iIdx>=0 );
  128461. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  128462. return rc;
  128463. }
  128464. /*
  128465. ** Return the N-dimensional volumn of the cell stored in *p.
  128466. */
  128467. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  128468. RtreeDValue area = (RtreeDValue)1;
  128469. int ii;
  128470. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  128471. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  128472. }
  128473. return area;
  128474. }
  128475. /*
  128476. ** Return the margin length of cell p. The margin length is the sum
  128477. ** of the objects size in each dimension.
  128478. */
  128479. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  128480. RtreeDValue margin = (RtreeDValue)0;
  128481. int ii;
  128482. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  128483. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  128484. }
  128485. return margin;
  128486. }
  128487. /*
  128488. ** Store the union of cells p1 and p2 in p1.
  128489. */
  128490. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  128491. int ii;
  128492. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  128493. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  128494. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  128495. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  128496. }
  128497. }else{
  128498. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  128499. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  128500. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  128501. }
  128502. }
  128503. }
  128504. /*
  128505. ** Return true if the area covered by p2 is a subset of the area covered
  128506. ** by p1. False otherwise.
  128507. */
  128508. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  128509. int ii;
  128510. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  128511. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  128512. RtreeCoord *a1 = &p1->aCoord[ii];
  128513. RtreeCoord *a2 = &p2->aCoord[ii];
  128514. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  128515. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  128516. ){
  128517. return 0;
  128518. }
  128519. }
  128520. return 1;
  128521. }
  128522. /*
  128523. ** Return the amount cell p would grow by if it were unioned with pCell.
  128524. */
  128525. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  128526. RtreeDValue area;
  128527. RtreeCell cell;
  128528. memcpy(&cell, p, sizeof(RtreeCell));
  128529. area = cellArea(pRtree, &cell);
  128530. cellUnion(pRtree, &cell, pCell);
  128531. return (cellArea(pRtree, &cell)-area);
  128532. }
  128533. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  128534. static RtreeDValue cellOverlap(
  128535. Rtree *pRtree,
  128536. RtreeCell *p,
  128537. RtreeCell *aCell,
  128538. int nCell,
  128539. int iExclude
  128540. ){
  128541. int ii;
  128542. RtreeDValue overlap = 0.0;
  128543. for(ii=0; ii<nCell; ii++){
  128544. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  128545. if( ii!=iExclude )
  128546. #else
  128547. assert( iExclude==-1 );
  128548. UNUSED_PARAMETER(iExclude);
  128549. #endif
  128550. {
  128551. int jj;
  128552. RtreeDValue o = (RtreeDValue)1;
  128553. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  128554. RtreeDValue x1, x2;
  128555. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  128556. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  128557. if( x2<x1 ){
  128558. o = 0.0;
  128559. break;
  128560. }else{
  128561. o = o * (x2-x1);
  128562. }
  128563. }
  128564. overlap += o;
  128565. }
  128566. }
  128567. return overlap;
  128568. }
  128569. #endif
  128570. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  128571. static RtreeDValue cellOverlapEnlargement(
  128572. Rtree *pRtree,
  128573. RtreeCell *p,
  128574. RtreeCell *pInsert,
  128575. RtreeCell *aCell,
  128576. int nCell,
  128577. int iExclude
  128578. ){
  128579. RtreeDValue before, after;
  128580. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  128581. cellUnion(pRtree, p, pInsert);
  128582. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  128583. return (after-before);
  128584. }
  128585. #endif
  128586. /*
  128587. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  128588. ** ChooseSubTree in r*tree terminology.
  128589. */
  128590. static int ChooseLeaf(
  128591. Rtree *pRtree, /* Rtree table */
  128592. RtreeCell *pCell, /* Cell to insert into rtree */
  128593. int iHeight, /* Height of sub-tree rooted at pCell */
  128594. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  128595. ){
  128596. int rc;
  128597. int ii;
  128598. RtreeNode *pNode;
  128599. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  128600. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  128601. int iCell;
  128602. sqlite3_int64 iBest = 0;
  128603. RtreeDValue fMinGrowth = 0.0;
  128604. RtreeDValue fMinArea = 0.0;
  128605. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  128606. RtreeDValue fMinOverlap = 0.0;
  128607. RtreeDValue overlap;
  128608. #endif
  128609. int nCell = NCELL(pNode);
  128610. RtreeCell cell;
  128611. RtreeNode *pChild;
  128612. RtreeCell *aCell = 0;
  128613. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  128614. if( ii==(pRtree->iDepth-1) ){
  128615. int jj;
  128616. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  128617. if( !aCell ){
  128618. rc = SQLITE_NOMEM;
  128619. nodeRelease(pRtree, pNode);
  128620. pNode = 0;
  128621. continue;
  128622. }
  128623. for(jj=0; jj<nCell; jj++){
  128624. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  128625. }
  128626. }
  128627. #endif
  128628. /* Select the child node which will be enlarged the least if pCell
  128629. ** is inserted into it. Resolve ties by choosing the entry with
  128630. ** the smallest area.
  128631. */
  128632. for(iCell=0; iCell<nCell; iCell++){
  128633. int bBest = 0;
  128634. RtreeDValue growth;
  128635. RtreeDValue area;
  128636. nodeGetCell(pRtree, pNode, iCell, &cell);
  128637. growth = cellGrowth(pRtree, &cell, pCell);
  128638. area = cellArea(pRtree, &cell);
  128639. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  128640. if( ii==(pRtree->iDepth-1) ){
  128641. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  128642. }else{
  128643. overlap = 0.0;
  128644. }
  128645. if( (iCell==0)
  128646. || (overlap<fMinOverlap)
  128647. || (overlap==fMinOverlap && growth<fMinGrowth)
  128648. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  128649. ){
  128650. bBest = 1;
  128651. fMinOverlap = overlap;
  128652. }
  128653. #else
  128654. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  128655. bBest = 1;
  128656. }
  128657. #endif
  128658. if( bBest ){
  128659. fMinGrowth = growth;
  128660. fMinArea = area;
  128661. iBest = cell.iRowid;
  128662. }
  128663. }
  128664. sqlite3_free(aCell);
  128665. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  128666. nodeRelease(pRtree, pNode);
  128667. pNode = pChild;
  128668. }
  128669. *ppLeaf = pNode;
  128670. return rc;
  128671. }
  128672. /*
  128673. ** A cell with the same content as pCell has just been inserted into
  128674. ** the node pNode. This function updates the bounding box cells in
  128675. ** all ancestor elements.
  128676. */
  128677. static int AdjustTree(
  128678. Rtree *pRtree, /* Rtree table */
  128679. RtreeNode *pNode, /* Adjust ancestry of this node. */
  128680. RtreeCell *pCell /* This cell was just inserted */
  128681. ){
  128682. RtreeNode *p = pNode;
  128683. while( p->pParent ){
  128684. RtreeNode *pParent = p->pParent;
  128685. RtreeCell cell;
  128686. int iCell;
  128687. if( nodeParentIndex(pRtree, p, &iCell) ){
  128688. return SQLITE_CORRUPT_VTAB;
  128689. }
  128690. nodeGetCell(pRtree, pParent, iCell, &cell);
  128691. if( !cellContains(pRtree, &cell, pCell) ){
  128692. cellUnion(pRtree, &cell, pCell);
  128693. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  128694. }
  128695. p = pParent;
  128696. }
  128697. return SQLITE_OK;
  128698. }
  128699. /*
  128700. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  128701. */
  128702. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  128703. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  128704. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  128705. sqlite3_step(pRtree->pWriteRowid);
  128706. return sqlite3_reset(pRtree->pWriteRowid);
  128707. }
  128708. /*
  128709. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  128710. */
  128711. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  128712. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  128713. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  128714. sqlite3_step(pRtree->pWriteParent);
  128715. return sqlite3_reset(pRtree->pWriteParent);
  128716. }
  128717. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  128718. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  128719. /*
  128720. ** Implementation of the linear variant of the PickNext() function from
  128721. ** Guttman[84].
  128722. */
  128723. static RtreeCell *LinearPickNext(
  128724. Rtree *pRtree,
  128725. RtreeCell *aCell,
  128726. int nCell,
  128727. RtreeCell *pLeftBox,
  128728. RtreeCell *pRightBox,
  128729. int *aiUsed
  128730. ){
  128731. int ii;
  128732. for(ii=0; aiUsed[ii]; ii++);
  128733. aiUsed[ii] = 1;
  128734. return &aCell[ii];
  128735. }
  128736. /*
  128737. ** Implementation of the linear variant of the PickSeeds() function from
  128738. ** Guttman[84].
  128739. */
  128740. static void LinearPickSeeds(
  128741. Rtree *pRtree,
  128742. RtreeCell *aCell,
  128743. int nCell,
  128744. int *piLeftSeed,
  128745. int *piRightSeed
  128746. ){
  128747. int i;
  128748. int iLeftSeed = 0;
  128749. int iRightSeed = 1;
  128750. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  128751. /* Pick two "seed" cells from the array of cells. The algorithm used
  128752. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  128753. ** indices of the two seed cells in the array are stored in local
  128754. ** variables iLeftSeek and iRightSeed.
  128755. */
  128756. for(i=0; i<pRtree->nDim; i++){
  128757. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  128758. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  128759. RtreeDValue x3 = x1;
  128760. RtreeDValue x4 = x2;
  128761. int jj;
  128762. int iCellLeft = 0;
  128763. int iCellRight = 0;
  128764. for(jj=1; jj<nCell; jj++){
  128765. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  128766. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  128767. if( left<x1 ) x1 = left;
  128768. if( right>x4 ) x4 = right;
  128769. if( left>x3 ){
  128770. x3 = left;
  128771. iCellRight = jj;
  128772. }
  128773. if( right<x2 ){
  128774. x2 = right;
  128775. iCellLeft = jj;
  128776. }
  128777. }
  128778. if( x4!=x1 ){
  128779. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  128780. if( normalwidth>maxNormalInnerWidth ){
  128781. iLeftSeed = iCellLeft;
  128782. iRightSeed = iCellRight;
  128783. }
  128784. }
  128785. }
  128786. *piLeftSeed = iLeftSeed;
  128787. *piRightSeed = iRightSeed;
  128788. }
  128789. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  128790. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  128791. /*
  128792. ** Implementation of the quadratic variant of the PickNext() function from
  128793. ** Guttman[84].
  128794. */
  128795. static RtreeCell *QuadraticPickNext(
  128796. Rtree *pRtree,
  128797. RtreeCell *aCell,
  128798. int nCell,
  128799. RtreeCell *pLeftBox,
  128800. RtreeCell *pRightBox,
  128801. int *aiUsed
  128802. ){
  128803. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  128804. int iSelect = -1;
  128805. RtreeDValue fDiff;
  128806. int ii;
  128807. for(ii=0; ii<nCell; ii++){
  128808. if( aiUsed[ii]==0 ){
  128809. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  128810. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  128811. RtreeDValue diff = FABS(right-left);
  128812. if( iSelect<0 || diff>fDiff ){
  128813. fDiff = diff;
  128814. iSelect = ii;
  128815. }
  128816. }
  128817. }
  128818. aiUsed[iSelect] = 1;
  128819. return &aCell[iSelect];
  128820. }
  128821. /*
  128822. ** Implementation of the quadratic variant of the PickSeeds() function from
  128823. ** Guttman[84].
  128824. */
  128825. static void QuadraticPickSeeds(
  128826. Rtree *pRtree,
  128827. RtreeCell *aCell,
  128828. int nCell,
  128829. int *piLeftSeed,
  128830. int *piRightSeed
  128831. ){
  128832. int ii;
  128833. int jj;
  128834. int iLeftSeed = 0;
  128835. int iRightSeed = 1;
  128836. RtreeDValue fWaste = 0.0;
  128837. for(ii=0; ii<nCell; ii++){
  128838. for(jj=ii+1; jj<nCell; jj++){
  128839. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  128840. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  128841. RtreeDValue waste = growth - right;
  128842. if( waste>fWaste ){
  128843. iLeftSeed = ii;
  128844. iRightSeed = jj;
  128845. fWaste = waste;
  128846. }
  128847. }
  128848. }
  128849. *piLeftSeed = iLeftSeed;
  128850. *piRightSeed = iRightSeed;
  128851. }
  128852. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  128853. /*
  128854. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  128855. ** nIdx. The aIdx array contains the set of integers from 0 to
  128856. ** (nIdx-1) in no particular order. This function sorts the values
  128857. ** in aIdx according to the indexed values in aDistance. For
  128858. ** example, assuming the inputs:
  128859. **
  128860. ** aIdx = { 0, 1, 2, 3 }
  128861. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  128862. **
  128863. ** this function sets the aIdx array to contain:
  128864. **
  128865. ** aIdx = { 0, 1, 2, 3 }
  128866. **
  128867. ** The aSpare array is used as temporary working space by the
  128868. ** sorting algorithm.
  128869. */
  128870. static void SortByDistance(
  128871. int *aIdx,
  128872. int nIdx,
  128873. RtreeDValue *aDistance,
  128874. int *aSpare
  128875. ){
  128876. if( nIdx>1 ){
  128877. int iLeft = 0;
  128878. int iRight = 0;
  128879. int nLeft = nIdx/2;
  128880. int nRight = nIdx-nLeft;
  128881. int *aLeft = aIdx;
  128882. int *aRight = &aIdx[nLeft];
  128883. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  128884. SortByDistance(aRight, nRight, aDistance, aSpare);
  128885. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  128886. aLeft = aSpare;
  128887. while( iLeft<nLeft || iRight<nRight ){
  128888. if( iLeft==nLeft ){
  128889. aIdx[iLeft+iRight] = aRight[iRight];
  128890. iRight++;
  128891. }else if( iRight==nRight ){
  128892. aIdx[iLeft+iRight] = aLeft[iLeft];
  128893. iLeft++;
  128894. }else{
  128895. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  128896. RtreeDValue fRight = aDistance[aRight[iRight]];
  128897. if( fLeft<fRight ){
  128898. aIdx[iLeft+iRight] = aLeft[iLeft];
  128899. iLeft++;
  128900. }else{
  128901. aIdx[iLeft+iRight] = aRight[iRight];
  128902. iRight++;
  128903. }
  128904. }
  128905. }
  128906. #if 0
  128907. /* Check that the sort worked */
  128908. {
  128909. int jj;
  128910. for(jj=1; jj<nIdx; jj++){
  128911. RtreeDValue left = aDistance[aIdx[jj-1]];
  128912. RtreeDValue right = aDistance[aIdx[jj]];
  128913. assert( left<=right );
  128914. }
  128915. }
  128916. #endif
  128917. }
  128918. }
  128919. /*
  128920. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  128921. ** nIdx. The aIdx array contains the set of integers from 0 to
  128922. ** (nIdx-1) in no particular order. This function sorts the values
  128923. ** in aIdx according to dimension iDim of the cells in aCell. The
  128924. ** minimum value of dimension iDim is considered first, the
  128925. ** maximum used to break ties.
  128926. **
  128927. ** The aSpare array is used as temporary working space by the
  128928. ** sorting algorithm.
  128929. */
  128930. static void SortByDimension(
  128931. Rtree *pRtree,
  128932. int *aIdx,
  128933. int nIdx,
  128934. int iDim,
  128935. RtreeCell *aCell,
  128936. int *aSpare
  128937. ){
  128938. if( nIdx>1 ){
  128939. int iLeft = 0;
  128940. int iRight = 0;
  128941. int nLeft = nIdx/2;
  128942. int nRight = nIdx-nLeft;
  128943. int *aLeft = aIdx;
  128944. int *aRight = &aIdx[nLeft];
  128945. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  128946. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  128947. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  128948. aLeft = aSpare;
  128949. while( iLeft<nLeft || iRight<nRight ){
  128950. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  128951. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  128952. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  128953. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  128954. if( (iLeft!=nLeft) && ((iRight==nRight)
  128955. || (xleft1<xright1)
  128956. || (xleft1==xright1 && xleft2<xright2)
  128957. )){
  128958. aIdx[iLeft+iRight] = aLeft[iLeft];
  128959. iLeft++;
  128960. }else{
  128961. aIdx[iLeft+iRight] = aRight[iRight];
  128962. iRight++;
  128963. }
  128964. }
  128965. #if 0
  128966. /* Check that the sort worked */
  128967. {
  128968. int jj;
  128969. for(jj=1; jj<nIdx; jj++){
  128970. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  128971. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  128972. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  128973. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  128974. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  128975. }
  128976. }
  128977. #endif
  128978. }
  128979. }
  128980. #if VARIANT_RSTARTREE_SPLIT
  128981. /*
  128982. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  128983. */
  128984. static int splitNodeStartree(
  128985. Rtree *pRtree,
  128986. RtreeCell *aCell,
  128987. int nCell,
  128988. RtreeNode *pLeft,
  128989. RtreeNode *pRight,
  128990. RtreeCell *pBboxLeft,
  128991. RtreeCell *pBboxRight
  128992. ){
  128993. int **aaSorted;
  128994. int *aSpare;
  128995. int ii;
  128996. int iBestDim = 0;
  128997. int iBestSplit = 0;
  128998. RtreeDValue fBestMargin = 0.0;
  128999. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  129000. aaSorted = (int **)sqlite3_malloc(nByte);
  129001. if( !aaSorted ){
  129002. return SQLITE_NOMEM;
  129003. }
  129004. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  129005. memset(aaSorted, 0, nByte);
  129006. for(ii=0; ii<pRtree->nDim; ii++){
  129007. int jj;
  129008. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  129009. for(jj=0; jj<nCell; jj++){
  129010. aaSorted[ii][jj] = jj;
  129011. }
  129012. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  129013. }
  129014. for(ii=0; ii<pRtree->nDim; ii++){
  129015. RtreeDValue margin = 0.0;
  129016. RtreeDValue fBestOverlap = 0.0;
  129017. RtreeDValue fBestArea = 0.0;
  129018. int iBestLeft = 0;
  129019. int nLeft;
  129020. for(
  129021. nLeft=RTREE_MINCELLS(pRtree);
  129022. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  129023. nLeft++
  129024. ){
  129025. RtreeCell left;
  129026. RtreeCell right;
  129027. int kk;
  129028. RtreeDValue overlap;
  129029. RtreeDValue area;
  129030. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  129031. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  129032. for(kk=1; kk<(nCell-1); kk++){
  129033. if( kk<nLeft ){
  129034. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  129035. }else{
  129036. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  129037. }
  129038. }
  129039. margin += cellMargin(pRtree, &left);
  129040. margin += cellMargin(pRtree, &right);
  129041. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  129042. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  129043. if( (nLeft==RTREE_MINCELLS(pRtree))
  129044. || (overlap<fBestOverlap)
  129045. || (overlap==fBestOverlap && area<fBestArea)
  129046. ){
  129047. iBestLeft = nLeft;
  129048. fBestOverlap = overlap;
  129049. fBestArea = area;
  129050. }
  129051. }
  129052. if( ii==0 || margin<fBestMargin ){
  129053. iBestDim = ii;
  129054. fBestMargin = margin;
  129055. iBestSplit = iBestLeft;
  129056. }
  129057. }
  129058. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  129059. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  129060. for(ii=0; ii<nCell; ii++){
  129061. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  129062. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  129063. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  129064. nodeInsertCell(pRtree, pTarget, pCell);
  129065. cellUnion(pRtree, pBbox, pCell);
  129066. }
  129067. sqlite3_free(aaSorted);
  129068. return SQLITE_OK;
  129069. }
  129070. #endif
  129071. #if VARIANT_GUTTMAN_SPLIT
  129072. /*
  129073. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  129074. */
  129075. static int splitNodeGuttman(
  129076. Rtree *pRtree,
  129077. RtreeCell *aCell,
  129078. int nCell,
  129079. RtreeNode *pLeft,
  129080. RtreeNode *pRight,
  129081. RtreeCell *pBboxLeft,
  129082. RtreeCell *pBboxRight
  129083. ){
  129084. int iLeftSeed = 0;
  129085. int iRightSeed = 1;
  129086. int *aiUsed;
  129087. int i;
  129088. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  129089. if( !aiUsed ){
  129090. return SQLITE_NOMEM;
  129091. }
  129092. memset(aiUsed, 0, sizeof(int)*nCell);
  129093. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  129094. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  129095. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  129096. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  129097. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  129098. aiUsed[iLeftSeed] = 1;
  129099. aiUsed[iRightSeed] = 1;
  129100. for(i=nCell-2; i>0; i--){
  129101. RtreeCell *pNext;
  129102. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  129103. RtreeDValue diff =
  129104. cellGrowth(pRtree, pBboxLeft, pNext) -
  129105. cellGrowth(pRtree, pBboxRight, pNext)
  129106. ;
  129107. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  129108. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  129109. ){
  129110. nodeInsertCell(pRtree, pRight, pNext);
  129111. cellUnion(pRtree, pBboxRight, pNext);
  129112. }else{
  129113. nodeInsertCell(pRtree, pLeft, pNext);
  129114. cellUnion(pRtree, pBboxLeft, pNext);
  129115. }
  129116. }
  129117. sqlite3_free(aiUsed);
  129118. return SQLITE_OK;
  129119. }
  129120. #endif
  129121. static int updateMapping(
  129122. Rtree *pRtree,
  129123. i64 iRowid,
  129124. RtreeNode *pNode,
  129125. int iHeight
  129126. ){
  129127. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  129128. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  129129. if( iHeight>0 ){
  129130. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  129131. if( pChild ){
  129132. nodeRelease(pRtree, pChild->pParent);
  129133. nodeReference(pNode);
  129134. pChild->pParent = pNode;
  129135. }
  129136. }
  129137. return xSetMapping(pRtree, iRowid, pNode->iNode);
  129138. }
  129139. static int SplitNode(
  129140. Rtree *pRtree,
  129141. RtreeNode *pNode,
  129142. RtreeCell *pCell,
  129143. int iHeight
  129144. ){
  129145. int i;
  129146. int newCellIsRight = 0;
  129147. int rc = SQLITE_OK;
  129148. int nCell = NCELL(pNode);
  129149. RtreeCell *aCell;
  129150. int *aiUsed;
  129151. RtreeNode *pLeft = 0;
  129152. RtreeNode *pRight = 0;
  129153. RtreeCell leftbbox;
  129154. RtreeCell rightbbox;
  129155. /* Allocate an array and populate it with a copy of pCell and
  129156. ** all cells from node pLeft. Then zero the original node.
  129157. */
  129158. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  129159. if( !aCell ){
  129160. rc = SQLITE_NOMEM;
  129161. goto splitnode_out;
  129162. }
  129163. aiUsed = (int *)&aCell[nCell+1];
  129164. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  129165. for(i=0; i<nCell; i++){
  129166. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  129167. }
  129168. nodeZero(pRtree, pNode);
  129169. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  129170. nCell++;
  129171. if( pNode->iNode==1 ){
  129172. pRight = nodeNew(pRtree, pNode);
  129173. pLeft = nodeNew(pRtree, pNode);
  129174. pRtree->iDepth++;
  129175. pNode->isDirty = 1;
  129176. writeInt16(pNode->zData, pRtree->iDepth);
  129177. }else{
  129178. pLeft = pNode;
  129179. pRight = nodeNew(pRtree, pLeft->pParent);
  129180. nodeReference(pLeft);
  129181. }
  129182. if( !pLeft || !pRight ){
  129183. rc = SQLITE_NOMEM;
  129184. goto splitnode_out;
  129185. }
  129186. memset(pLeft->zData, 0, pRtree->iNodeSize);
  129187. memset(pRight->zData, 0, pRtree->iNodeSize);
  129188. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  129189. if( rc!=SQLITE_OK ){
  129190. goto splitnode_out;
  129191. }
  129192. /* Ensure both child nodes have node numbers assigned to them by calling
  129193. ** nodeWrite(). Node pRight always needs a node number, as it was created
  129194. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  129195. ** In this case avoid the all to nodeWrite().
  129196. */
  129197. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  129198. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  129199. ){
  129200. goto splitnode_out;
  129201. }
  129202. rightbbox.iRowid = pRight->iNode;
  129203. leftbbox.iRowid = pLeft->iNode;
  129204. if( pNode->iNode==1 ){
  129205. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  129206. if( rc!=SQLITE_OK ){
  129207. goto splitnode_out;
  129208. }
  129209. }else{
  129210. RtreeNode *pParent = pLeft->pParent;
  129211. int iCell;
  129212. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  129213. if( rc==SQLITE_OK ){
  129214. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  129215. rc = AdjustTree(pRtree, pParent, &leftbbox);
  129216. }
  129217. if( rc!=SQLITE_OK ){
  129218. goto splitnode_out;
  129219. }
  129220. }
  129221. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  129222. goto splitnode_out;
  129223. }
  129224. for(i=0; i<NCELL(pRight); i++){
  129225. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  129226. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  129227. if( iRowid==pCell->iRowid ){
  129228. newCellIsRight = 1;
  129229. }
  129230. if( rc!=SQLITE_OK ){
  129231. goto splitnode_out;
  129232. }
  129233. }
  129234. if( pNode->iNode==1 ){
  129235. for(i=0; i<NCELL(pLeft); i++){
  129236. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  129237. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  129238. if( rc!=SQLITE_OK ){
  129239. goto splitnode_out;
  129240. }
  129241. }
  129242. }else if( newCellIsRight==0 ){
  129243. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  129244. }
  129245. if( rc==SQLITE_OK ){
  129246. rc = nodeRelease(pRtree, pRight);
  129247. pRight = 0;
  129248. }
  129249. if( rc==SQLITE_OK ){
  129250. rc = nodeRelease(pRtree, pLeft);
  129251. pLeft = 0;
  129252. }
  129253. splitnode_out:
  129254. nodeRelease(pRtree, pRight);
  129255. nodeRelease(pRtree, pLeft);
  129256. sqlite3_free(aCell);
  129257. return rc;
  129258. }
  129259. /*
  129260. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  129261. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  129262. ** the pLeaf->pParent chain all the way up to the root node.
  129263. **
  129264. ** This operation is required when a row is deleted (or updated - an update
  129265. ** is implemented as a delete followed by an insert). SQLite provides the
  129266. ** rowid of the row to delete, which can be used to find the leaf on which
  129267. ** the entry resides (argument pLeaf). Once the leaf is located, this
  129268. ** function is called to determine its ancestry.
  129269. */
  129270. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  129271. int rc = SQLITE_OK;
  129272. RtreeNode *pChild = pLeaf;
  129273. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  129274. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  129275. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  129276. rc = sqlite3_step(pRtree->pReadParent);
  129277. if( rc==SQLITE_ROW ){
  129278. RtreeNode *pTest; /* Used to test for reference loops */
  129279. i64 iNode; /* Node number of parent node */
  129280. /* Before setting pChild->pParent, test that we are not creating a
  129281. ** loop of references (as we would if, say, pChild==pParent). We don't
  129282. ** want to do this as it leads to a memory leak when trying to delete
  129283. ** the referenced counted node structures.
  129284. */
  129285. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  129286. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  129287. if( !pTest ){
  129288. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  129289. }
  129290. }
  129291. rc = sqlite3_reset(pRtree->pReadParent);
  129292. if( rc==SQLITE_OK ) rc = rc2;
  129293. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  129294. pChild = pChild->pParent;
  129295. }
  129296. return rc;
  129297. }
  129298. static int deleteCell(Rtree *, RtreeNode *, int, int);
  129299. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  129300. int rc;
  129301. int rc2;
  129302. RtreeNode *pParent = 0;
  129303. int iCell;
  129304. assert( pNode->nRef==1 );
  129305. /* Remove the entry in the parent cell. */
  129306. rc = nodeParentIndex(pRtree, pNode, &iCell);
  129307. if( rc==SQLITE_OK ){
  129308. pParent = pNode->pParent;
  129309. pNode->pParent = 0;
  129310. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  129311. }
  129312. rc2 = nodeRelease(pRtree, pParent);
  129313. if( rc==SQLITE_OK ){
  129314. rc = rc2;
  129315. }
  129316. if( rc!=SQLITE_OK ){
  129317. return rc;
  129318. }
  129319. /* Remove the xxx_node entry. */
  129320. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  129321. sqlite3_step(pRtree->pDeleteNode);
  129322. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  129323. return rc;
  129324. }
  129325. /* Remove the xxx_parent entry. */
  129326. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  129327. sqlite3_step(pRtree->pDeleteParent);
  129328. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  129329. return rc;
  129330. }
  129331. /* Remove the node from the in-memory hash table and link it into
  129332. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  129333. */
  129334. nodeHashDelete(pRtree, pNode);
  129335. pNode->iNode = iHeight;
  129336. pNode->pNext = pRtree->pDeleted;
  129337. pNode->nRef++;
  129338. pRtree->pDeleted = pNode;
  129339. return SQLITE_OK;
  129340. }
  129341. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  129342. RtreeNode *pParent = pNode->pParent;
  129343. int rc = SQLITE_OK;
  129344. if( pParent ){
  129345. int ii;
  129346. int nCell = NCELL(pNode);
  129347. RtreeCell box; /* Bounding box for pNode */
  129348. nodeGetCell(pRtree, pNode, 0, &box);
  129349. for(ii=1; ii<nCell; ii++){
  129350. RtreeCell cell;
  129351. nodeGetCell(pRtree, pNode, ii, &cell);
  129352. cellUnion(pRtree, &box, &cell);
  129353. }
  129354. box.iRowid = pNode->iNode;
  129355. rc = nodeParentIndex(pRtree, pNode, &ii);
  129356. if( rc==SQLITE_OK ){
  129357. nodeOverwriteCell(pRtree, pParent, &box, ii);
  129358. rc = fixBoundingBox(pRtree, pParent);
  129359. }
  129360. }
  129361. return rc;
  129362. }
  129363. /*
  129364. ** Delete the cell at index iCell of node pNode. After removing the
  129365. ** cell, adjust the r-tree data structure if required.
  129366. */
  129367. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  129368. RtreeNode *pParent;
  129369. int rc;
  129370. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  129371. return rc;
  129372. }
  129373. /* Remove the cell from the node. This call just moves bytes around
  129374. ** the in-memory node image, so it cannot fail.
  129375. */
  129376. nodeDeleteCell(pRtree, pNode, iCell);
  129377. /* If the node is not the tree root and now has less than the minimum
  129378. ** number of cells, remove it from the tree. Otherwise, update the
  129379. ** cell in the parent node so that it tightly contains the updated
  129380. ** node.
  129381. */
  129382. pParent = pNode->pParent;
  129383. assert( pParent || pNode->iNode==1 );
  129384. if( pParent ){
  129385. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  129386. rc = removeNode(pRtree, pNode, iHeight);
  129387. }else{
  129388. rc = fixBoundingBox(pRtree, pNode);
  129389. }
  129390. }
  129391. return rc;
  129392. }
  129393. static int Reinsert(
  129394. Rtree *pRtree,
  129395. RtreeNode *pNode,
  129396. RtreeCell *pCell,
  129397. int iHeight
  129398. ){
  129399. int *aOrder;
  129400. int *aSpare;
  129401. RtreeCell *aCell;
  129402. RtreeDValue *aDistance;
  129403. int nCell;
  129404. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  129405. int iDim;
  129406. int ii;
  129407. int rc = SQLITE_OK;
  129408. int n;
  129409. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  129410. nCell = NCELL(pNode)+1;
  129411. n = (nCell+1)&(~1);
  129412. /* Allocate the buffers used by this operation. The allocation is
  129413. ** relinquished before this function returns.
  129414. */
  129415. aCell = (RtreeCell *)sqlite3_malloc(n * (
  129416. sizeof(RtreeCell) + /* aCell array */
  129417. sizeof(int) + /* aOrder array */
  129418. sizeof(int) + /* aSpare array */
  129419. sizeof(RtreeDValue) /* aDistance array */
  129420. ));
  129421. if( !aCell ){
  129422. return SQLITE_NOMEM;
  129423. }
  129424. aOrder = (int *)&aCell[n];
  129425. aSpare = (int *)&aOrder[n];
  129426. aDistance = (RtreeDValue *)&aSpare[n];
  129427. for(ii=0; ii<nCell; ii++){
  129428. if( ii==(nCell-1) ){
  129429. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  129430. }else{
  129431. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  129432. }
  129433. aOrder[ii] = ii;
  129434. for(iDim=0; iDim<pRtree->nDim; iDim++){
  129435. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  129436. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  129437. }
  129438. }
  129439. for(iDim=0; iDim<pRtree->nDim; iDim++){
  129440. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  129441. }
  129442. for(ii=0; ii<nCell; ii++){
  129443. aDistance[ii] = 0.0;
  129444. for(iDim=0; iDim<pRtree->nDim; iDim++){
  129445. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  129446. DCOORD(aCell[ii].aCoord[iDim*2]));
  129447. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  129448. }
  129449. }
  129450. SortByDistance(aOrder, nCell, aDistance, aSpare);
  129451. nodeZero(pRtree, pNode);
  129452. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  129453. RtreeCell *p = &aCell[aOrder[ii]];
  129454. nodeInsertCell(pRtree, pNode, p);
  129455. if( p->iRowid==pCell->iRowid ){
  129456. if( iHeight==0 ){
  129457. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  129458. }else{
  129459. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  129460. }
  129461. }
  129462. }
  129463. if( rc==SQLITE_OK ){
  129464. rc = fixBoundingBox(pRtree, pNode);
  129465. }
  129466. for(; rc==SQLITE_OK && ii<nCell; ii++){
  129467. /* Find a node to store this cell in. pNode->iNode currently contains
  129468. ** the height of the sub-tree headed by the cell.
  129469. */
  129470. RtreeNode *pInsert;
  129471. RtreeCell *p = &aCell[aOrder[ii]];
  129472. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  129473. if( rc==SQLITE_OK ){
  129474. int rc2;
  129475. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  129476. rc2 = nodeRelease(pRtree, pInsert);
  129477. if( rc==SQLITE_OK ){
  129478. rc = rc2;
  129479. }
  129480. }
  129481. }
  129482. sqlite3_free(aCell);
  129483. return rc;
  129484. }
  129485. /*
  129486. ** Insert cell pCell into node pNode. Node pNode is the head of a
  129487. ** subtree iHeight high (leaf nodes have iHeight==0).
  129488. */
  129489. static int rtreeInsertCell(
  129490. Rtree *pRtree,
  129491. RtreeNode *pNode,
  129492. RtreeCell *pCell,
  129493. int iHeight
  129494. ){
  129495. int rc = SQLITE_OK;
  129496. if( iHeight>0 ){
  129497. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  129498. if( pChild ){
  129499. nodeRelease(pRtree, pChild->pParent);
  129500. nodeReference(pNode);
  129501. pChild->pParent = pNode;
  129502. }
  129503. }
  129504. if( nodeInsertCell(pRtree, pNode, pCell) ){
  129505. #if VARIANT_RSTARTREE_REINSERT
  129506. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  129507. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  129508. }else{
  129509. pRtree->iReinsertHeight = iHeight;
  129510. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  129511. }
  129512. #else
  129513. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  129514. #endif
  129515. }else{
  129516. rc = AdjustTree(pRtree, pNode, pCell);
  129517. if( rc==SQLITE_OK ){
  129518. if( iHeight==0 ){
  129519. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  129520. }else{
  129521. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  129522. }
  129523. }
  129524. }
  129525. return rc;
  129526. }
  129527. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  129528. int ii;
  129529. int rc = SQLITE_OK;
  129530. int nCell = NCELL(pNode);
  129531. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  129532. RtreeNode *pInsert;
  129533. RtreeCell cell;
  129534. nodeGetCell(pRtree, pNode, ii, &cell);
  129535. /* Find a node to store this cell in. pNode->iNode currently contains
  129536. ** the height of the sub-tree headed by the cell.
  129537. */
  129538. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  129539. if( rc==SQLITE_OK ){
  129540. int rc2;
  129541. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  129542. rc2 = nodeRelease(pRtree, pInsert);
  129543. if( rc==SQLITE_OK ){
  129544. rc = rc2;
  129545. }
  129546. }
  129547. }
  129548. return rc;
  129549. }
  129550. /*
  129551. ** Select a currently unused rowid for a new r-tree record.
  129552. */
  129553. static int newRowid(Rtree *pRtree, i64 *piRowid){
  129554. int rc;
  129555. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  129556. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  129557. sqlite3_step(pRtree->pWriteRowid);
  129558. rc = sqlite3_reset(pRtree->pWriteRowid);
  129559. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  129560. return rc;
  129561. }
  129562. /*
  129563. ** Remove the entry with rowid=iDelete from the r-tree structure.
  129564. */
  129565. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  129566. int rc; /* Return code */
  129567. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  129568. int iCell; /* Index of iDelete cell in pLeaf */
  129569. RtreeNode *pRoot; /* Root node of rtree structure */
  129570. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  129571. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  129572. /* Obtain a reference to the leaf node that contains the entry
  129573. ** about to be deleted.
  129574. */
  129575. if( rc==SQLITE_OK ){
  129576. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  129577. }
  129578. /* Delete the cell in question from the leaf node. */
  129579. if( rc==SQLITE_OK ){
  129580. int rc2;
  129581. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  129582. if( rc==SQLITE_OK ){
  129583. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  129584. }
  129585. rc2 = nodeRelease(pRtree, pLeaf);
  129586. if( rc==SQLITE_OK ){
  129587. rc = rc2;
  129588. }
  129589. }
  129590. /* Delete the corresponding entry in the <rtree>_rowid table. */
  129591. if( rc==SQLITE_OK ){
  129592. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  129593. sqlite3_step(pRtree->pDeleteRowid);
  129594. rc = sqlite3_reset(pRtree->pDeleteRowid);
  129595. }
  129596. /* Check if the root node now has exactly one child. If so, remove
  129597. ** it, schedule the contents of the child for reinsertion and
  129598. ** reduce the tree height by one.
  129599. **
  129600. ** This is equivalent to copying the contents of the child into
  129601. ** the root node (the operation that Gutman's paper says to perform
  129602. ** in this scenario).
  129603. */
  129604. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  129605. int rc2;
  129606. RtreeNode *pChild;
  129607. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  129608. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  129609. if( rc==SQLITE_OK ){
  129610. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  129611. }
  129612. rc2 = nodeRelease(pRtree, pChild);
  129613. if( rc==SQLITE_OK ) rc = rc2;
  129614. if( rc==SQLITE_OK ){
  129615. pRtree->iDepth--;
  129616. writeInt16(pRoot->zData, pRtree->iDepth);
  129617. pRoot->isDirty = 1;
  129618. }
  129619. }
  129620. /* Re-insert the contents of any underfull nodes removed from the tree. */
  129621. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  129622. if( rc==SQLITE_OK ){
  129623. rc = reinsertNodeContent(pRtree, pLeaf);
  129624. }
  129625. pRtree->pDeleted = pLeaf->pNext;
  129626. sqlite3_free(pLeaf);
  129627. }
  129628. /* Release the reference to the root node. */
  129629. if( rc==SQLITE_OK ){
  129630. rc = nodeRelease(pRtree, pRoot);
  129631. }else{
  129632. nodeRelease(pRtree, pRoot);
  129633. }
  129634. return rc;
  129635. }
  129636. /*
  129637. ** Rounding constants for float->double conversion.
  129638. */
  129639. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  129640. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  129641. #if !defined(SQLITE_RTREE_INT_ONLY)
  129642. /*
  129643. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  129644. ** while taking care to round toward negative or positive, respectively.
  129645. */
  129646. static RtreeValue rtreeValueDown(sqlite3_value *v){
  129647. double d = sqlite3_value_double(v);
  129648. float f = (float)d;
  129649. if( f>d ){
  129650. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  129651. }
  129652. return f;
  129653. }
  129654. static RtreeValue rtreeValueUp(sqlite3_value *v){
  129655. double d = sqlite3_value_double(v);
  129656. float f = (float)d;
  129657. if( f<d ){
  129658. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  129659. }
  129660. return f;
  129661. }
  129662. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  129663. /*
  129664. ** The xUpdate method for rtree module virtual tables.
  129665. */
  129666. static int rtreeUpdate(
  129667. sqlite3_vtab *pVtab,
  129668. int nData,
  129669. sqlite3_value **azData,
  129670. sqlite_int64 *pRowid
  129671. ){
  129672. Rtree *pRtree = (Rtree *)pVtab;
  129673. int rc = SQLITE_OK;
  129674. RtreeCell cell; /* New cell to insert if nData>1 */
  129675. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  129676. rtreeReference(pRtree);
  129677. assert(nData>=1);
  129678. /* Constraint handling. A write operation on an r-tree table may return
  129679. ** SQLITE_CONSTRAINT for two reasons:
  129680. **
  129681. ** 1. A duplicate rowid value, or
  129682. ** 2. The supplied data violates the "x2>=x1" constraint.
  129683. **
  129684. ** In the first case, if the conflict-handling mode is REPLACE, then
  129685. ** the conflicting row can be removed before proceeding. In the second
  129686. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  129687. ** conflict-handling mode specified by the user.
  129688. */
  129689. if( nData>1 ){
  129690. int ii;
  129691. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  129692. assert( nData==(pRtree->nDim*2 + 3) );
  129693. #ifndef SQLITE_RTREE_INT_ONLY
  129694. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  129695. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  129696. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  129697. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  129698. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  129699. rc = SQLITE_CONSTRAINT;
  129700. goto constraint;
  129701. }
  129702. }
  129703. }else
  129704. #endif
  129705. {
  129706. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  129707. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  129708. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  129709. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  129710. rc = SQLITE_CONSTRAINT;
  129711. goto constraint;
  129712. }
  129713. }
  129714. }
  129715. /* If a rowid value was supplied, check if it is already present in
  129716. ** the table. If so, the constraint has failed. */
  129717. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  129718. cell.iRowid = sqlite3_value_int64(azData[2]);
  129719. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  129720. || sqlite3_value_int64(azData[0])!=cell.iRowid
  129721. ){
  129722. int steprc;
  129723. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  129724. steprc = sqlite3_step(pRtree->pReadRowid);
  129725. rc = sqlite3_reset(pRtree->pReadRowid);
  129726. if( SQLITE_ROW==steprc ){
  129727. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  129728. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  129729. }else{
  129730. rc = SQLITE_CONSTRAINT;
  129731. goto constraint;
  129732. }
  129733. }
  129734. }
  129735. bHaveRowid = 1;
  129736. }
  129737. }
  129738. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  129739. ** record to delete from the r-tree table. The following block does
  129740. ** just that.
  129741. */
  129742. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  129743. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  129744. }
  129745. /* If the azData[] array contains more than one element, elements
  129746. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  129747. ** the r-tree structure.
  129748. */
  129749. if( rc==SQLITE_OK && nData>1 ){
  129750. /* Insert the new record into the r-tree */
  129751. RtreeNode *pLeaf = 0;
  129752. /* Figure out the rowid of the new row. */
  129753. if( bHaveRowid==0 ){
  129754. rc = newRowid(pRtree, &cell.iRowid);
  129755. }
  129756. *pRowid = cell.iRowid;
  129757. if( rc==SQLITE_OK ){
  129758. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  129759. }
  129760. if( rc==SQLITE_OK ){
  129761. int rc2;
  129762. pRtree->iReinsertHeight = -1;
  129763. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  129764. rc2 = nodeRelease(pRtree, pLeaf);
  129765. if( rc==SQLITE_OK ){
  129766. rc = rc2;
  129767. }
  129768. }
  129769. }
  129770. constraint:
  129771. rtreeRelease(pRtree);
  129772. return rc;
  129773. }
  129774. /*
  129775. ** The xRename method for rtree module virtual tables.
  129776. */
  129777. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  129778. Rtree *pRtree = (Rtree *)pVtab;
  129779. int rc = SQLITE_NOMEM;
  129780. char *zSql = sqlite3_mprintf(
  129781. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  129782. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  129783. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  129784. , pRtree->zDb, pRtree->zName, zNewName
  129785. , pRtree->zDb, pRtree->zName, zNewName
  129786. , pRtree->zDb, pRtree->zName, zNewName
  129787. );
  129788. if( zSql ){
  129789. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  129790. sqlite3_free(zSql);
  129791. }
  129792. return rc;
  129793. }
  129794. static sqlite3_module rtreeModule = {
  129795. 0, /* iVersion */
  129796. rtreeCreate, /* xCreate - create a table */
  129797. rtreeConnect, /* xConnect - connect to an existing table */
  129798. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  129799. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  129800. rtreeDestroy, /* xDestroy - Drop a table */
  129801. rtreeOpen, /* xOpen - open a cursor */
  129802. rtreeClose, /* xClose - close a cursor */
  129803. rtreeFilter, /* xFilter - configure scan constraints */
  129804. rtreeNext, /* xNext - advance a cursor */
  129805. rtreeEof, /* xEof */
  129806. rtreeColumn, /* xColumn - read data */
  129807. rtreeRowid, /* xRowid - read data */
  129808. rtreeUpdate, /* xUpdate - write data */
  129809. 0, /* xBegin - begin transaction */
  129810. 0, /* xSync - sync transaction */
  129811. 0, /* xCommit - commit transaction */
  129812. 0, /* xRollback - rollback transaction */
  129813. 0, /* xFindFunction - function overloading */
  129814. rtreeRename, /* xRename - rename the table */
  129815. 0, /* xSavepoint */
  129816. 0, /* xRelease */
  129817. 0 /* xRollbackTo */
  129818. };
  129819. static int rtreeSqlInit(
  129820. Rtree *pRtree,
  129821. sqlite3 *db,
  129822. const char *zDb,
  129823. const char *zPrefix,
  129824. int isCreate
  129825. ){
  129826. int rc = SQLITE_OK;
  129827. #define N_STATEMENT 9
  129828. static const char *azSql[N_STATEMENT] = {
  129829. /* Read and write the xxx_node table */
  129830. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  129831. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  129832. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  129833. /* Read and write the xxx_rowid table */
  129834. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  129835. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  129836. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  129837. /* Read and write the xxx_parent table */
  129838. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  129839. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  129840. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  129841. };
  129842. sqlite3_stmt **appStmt[N_STATEMENT];
  129843. int i;
  129844. pRtree->db = db;
  129845. if( isCreate ){
  129846. char *zCreate = sqlite3_mprintf(
  129847. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  129848. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  129849. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  129850. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  129851. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  129852. );
  129853. if( !zCreate ){
  129854. return SQLITE_NOMEM;
  129855. }
  129856. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  129857. sqlite3_free(zCreate);
  129858. if( rc!=SQLITE_OK ){
  129859. return rc;
  129860. }
  129861. }
  129862. appStmt[0] = &pRtree->pReadNode;
  129863. appStmt[1] = &pRtree->pWriteNode;
  129864. appStmt[2] = &pRtree->pDeleteNode;
  129865. appStmt[3] = &pRtree->pReadRowid;
  129866. appStmt[4] = &pRtree->pWriteRowid;
  129867. appStmt[5] = &pRtree->pDeleteRowid;
  129868. appStmt[6] = &pRtree->pReadParent;
  129869. appStmt[7] = &pRtree->pWriteParent;
  129870. appStmt[8] = &pRtree->pDeleteParent;
  129871. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  129872. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  129873. if( zSql ){
  129874. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  129875. }else{
  129876. rc = SQLITE_NOMEM;
  129877. }
  129878. sqlite3_free(zSql);
  129879. }
  129880. return rc;
  129881. }
  129882. /*
  129883. ** The second argument to this function contains the text of an SQL statement
  129884. ** that returns a single integer value. The statement is compiled and executed
  129885. ** using database connection db. If successful, the integer value returned
  129886. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  129887. ** code is returned and the value of *piVal after returning is not defined.
  129888. */
  129889. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  129890. int rc = SQLITE_NOMEM;
  129891. if( zSql ){
  129892. sqlite3_stmt *pStmt = 0;
  129893. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  129894. if( rc==SQLITE_OK ){
  129895. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  129896. *piVal = sqlite3_column_int(pStmt, 0);
  129897. }
  129898. rc = sqlite3_finalize(pStmt);
  129899. }
  129900. }
  129901. return rc;
  129902. }
  129903. /*
  129904. ** This function is called from within the xConnect() or xCreate() method to
  129905. ** determine the node-size used by the rtree table being created or connected
  129906. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  129907. ** Otherwise, an SQLite error code is returned.
  129908. **
  129909. ** If this function is being called as part of an xConnect(), then the rtree
  129910. ** table already exists. In this case the node-size is determined by inspecting
  129911. ** the root node of the tree.
  129912. **
  129913. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  129914. ** This ensures that each node is stored on a single database page. If the
  129915. ** database page-size is so large that more than RTREE_MAXCELLS entries
  129916. ** would fit in a single node, use a smaller node-size.
  129917. */
  129918. static int getNodeSize(
  129919. sqlite3 *db, /* Database handle */
  129920. Rtree *pRtree, /* Rtree handle */
  129921. int isCreate, /* True for xCreate, false for xConnect */
  129922. char **pzErr /* OUT: Error message, if any */
  129923. ){
  129924. int rc;
  129925. char *zSql;
  129926. if( isCreate ){
  129927. int iPageSize = 0;
  129928. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  129929. rc = getIntFromStmt(db, zSql, &iPageSize);
  129930. if( rc==SQLITE_OK ){
  129931. pRtree->iNodeSize = iPageSize-64;
  129932. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  129933. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  129934. }
  129935. }else{
  129936. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  129937. }
  129938. }else{
  129939. zSql = sqlite3_mprintf(
  129940. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  129941. pRtree->zDb, pRtree->zName
  129942. );
  129943. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  129944. if( rc!=SQLITE_OK ){
  129945. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  129946. }
  129947. }
  129948. sqlite3_free(zSql);
  129949. return rc;
  129950. }
  129951. /*
  129952. ** This function is the implementation of both the xConnect and xCreate
  129953. ** methods of the r-tree virtual table.
  129954. **
  129955. ** argv[0] -> module name
  129956. ** argv[1] -> database name
  129957. ** argv[2] -> table name
  129958. ** argv[...] -> column names...
  129959. */
  129960. static int rtreeInit(
  129961. sqlite3 *db, /* Database connection */
  129962. void *pAux, /* One of the RTREE_COORD_* constants */
  129963. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  129964. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  129965. char **pzErr, /* OUT: Error message, if any */
  129966. int isCreate /* True for xCreate, false for xConnect */
  129967. ){
  129968. int rc = SQLITE_OK;
  129969. Rtree *pRtree;
  129970. int nDb; /* Length of string argv[1] */
  129971. int nName; /* Length of string argv[2] */
  129972. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  129973. const char *aErrMsg[] = {
  129974. 0, /* 0 */
  129975. "Wrong number of columns for an rtree table", /* 1 */
  129976. "Too few columns for an rtree table", /* 2 */
  129977. "Too many columns for an rtree table" /* 3 */
  129978. };
  129979. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  129980. if( aErrMsg[iErr] ){
  129981. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  129982. return SQLITE_ERROR;
  129983. }
  129984. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  129985. /* Allocate the sqlite3_vtab structure */
  129986. nDb = (int)strlen(argv[1]);
  129987. nName = (int)strlen(argv[2]);
  129988. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  129989. if( !pRtree ){
  129990. return SQLITE_NOMEM;
  129991. }
  129992. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  129993. pRtree->nBusy = 1;
  129994. pRtree->base.pModule = &rtreeModule;
  129995. pRtree->zDb = (char *)&pRtree[1];
  129996. pRtree->zName = &pRtree->zDb[nDb+1];
  129997. pRtree->nDim = (argc-4)/2;
  129998. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  129999. pRtree->eCoordType = eCoordType;
  130000. memcpy(pRtree->zDb, argv[1], nDb);
  130001. memcpy(pRtree->zName, argv[2], nName);
  130002. /* Figure out the node size to use. */
  130003. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  130004. /* Create/Connect to the underlying relational database schema. If
  130005. ** that is successful, call sqlite3_declare_vtab() to configure
  130006. ** the r-tree table schema.
  130007. */
  130008. if( rc==SQLITE_OK ){
  130009. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  130010. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  130011. }else{
  130012. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  130013. char *zTmp;
  130014. int ii;
  130015. for(ii=4; zSql && ii<argc; ii++){
  130016. zTmp = zSql;
  130017. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  130018. sqlite3_free(zTmp);
  130019. }
  130020. if( zSql ){
  130021. zTmp = zSql;
  130022. zSql = sqlite3_mprintf("%s);", zTmp);
  130023. sqlite3_free(zTmp);
  130024. }
  130025. if( !zSql ){
  130026. rc = SQLITE_NOMEM;
  130027. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  130028. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  130029. }
  130030. sqlite3_free(zSql);
  130031. }
  130032. }
  130033. if( rc==SQLITE_OK ){
  130034. *ppVtab = (sqlite3_vtab *)pRtree;
  130035. }else{
  130036. rtreeRelease(pRtree);
  130037. }
  130038. return rc;
  130039. }
  130040. /*
  130041. ** Implementation of a scalar function that decodes r-tree nodes to
  130042. ** human readable strings. This can be used for debugging and analysis.
  130043. **
  130044. ** The scalar function takes two arguments, a blob of data containing
  130045. ** an r-tree node, and the number of dimensions the r-tree indexes.
  130046. ** For a two-dimensional r-tree structure called "rt", to deserialize
  130047. ** all nodes, a statement like:
  130048. **
  130049. ** SELECT rtreenode(2, data) FROM rt_node;
  130050. **
  130051. ** The human readable string takes the form of a Tcl list with one
  130052. ** entry for each cell in the r-tree node. Each entry is itself a
  130053. ** list, containing the 8-byte rowid/pageno followed by the
  130054. ** <num-dimension>*2 coordinates.
  130055. */
  130056. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  130057. char *zText = 0;
  130058. RtreeNode node;
  130059. Rtree tree;
  130060. int ii;
  130061. UNUSED_PARAMETER(nArg);
  130062. memset(&node, 0, sizeof(RtreeNode));
  130063. memset(&tree, 0, sizeof(Rtree));
  130064. tree.nDim = sqlite3_value_int(apArg[0]);
  130065. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  130066. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  130067. for(ii=0; ii<NCELL(&node); ii++){
  130068. char zCell[512];
  130069. int nCell = 0;
  130070. RtreeCell cell;
  130071. int jj;
  130072. nodeGetCell(&tree, &node, ii, &cell);
  130073. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  130074. nCell = (int)strlen(zCell);
  130075. for(jj=0; jj<tree.nDim*2; jj++){
  130076. #ifndef SQLITE_RTREE_INT_ONLY
  130077. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  130078. (double)cell.aCoord[jj].f);
  130079. #else
  130080. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  130081. cell.aCoord[jj].i);
  130082. #endif
  130083. nCell = (int)strlen(zCell);
  130084. }
  130085. if( zText ){
  130086. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  130087. sqlite3_free(zText);
  130088. zText = zTextNew;
  130089. }else{
  130090. zText = sqlite3_mprintf("{%s}", zCell);
  130091. }
  130092. }
  130093. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  130094. }
  130095. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  130096. UNUSED_PARAMETER(nArg);
  130097. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  130098. || sqlite3_value_bytes(apArg[0])<2
  130099. ){
  130100. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  130101. }else{
  130102. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  130103. sqlite3_result_int(ctx, readInt16(zBlob));
  130104. }
  130105. }
  130106. /*
  130107. ** Register the r-tree module with database handle db. This creates the
  130108. ** virtual table module "rtree" and the debugging/analysis scalar
  130109. ** function "rtreenode".
  130110. */
  130111. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  130112. const int utf8 = SQLITE_UTF8;
  130113. int rc;
  130114. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  130115. if( rc==SQLITE_OK ){
  130116. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  130117. }
  130118. if( rc==SQLITE_OK ){
  130119. #ifdef SQLITE_RTREE_INT_ONLY
  130120. void *c = (void *)RTREE_COORD_INT32;
  130121. #else
  130122. void *c = (void *)RTREE_COORD_REAL32;
  130123. #endif
  130124. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  130125. }
  130126. if( rc==SQLITE_OK ){
  130127. void *c = (void *)RTREE_COORD_INT32;
  130128. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  130129. }
  130130. return rc;
  130131. }
  130132. /*
  130133. ** A version of sqlite3_free() that can be used as a callback. This is used
  130134. ** in two places - as the destructor for the blob value returned by the
  130135. ** invocation of a geometry function, and as the destructor for the geometry
  130136. ** functions themselves.
  130137. */
  130138. static void doSqlite3Free(void *p){
  130139. sqlite3_free(p);
  130140. }
  130141. /*
  130142. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  130143. ** scalar user function. This C function is the callback used for all such
  130144. ** registered SQL functions.
  130145. **
  130146. ** The scalar user functions return a blob that is interpreted by r-tree
  130147. ** table MATCH operators.
  130148. */
  130149. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  130150. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  130151. RtreeMatchArg *pBlob;
  130152. int nBlob;
  130153. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  130154. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  130155. if( !pBlob ){
  130156. sqlite3_result_error_nomem(ctx);
  130157. }else{
  130158. int i;
  130159. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  130160. pBlob->xGeom = pGeomCtx->xGeom;
  130161. pBlob->pContext = pGeomCtx->pContext;
  130162. pBlob->nParam = nArg;
  130163. for(i=0; i<nArg; i++){
  130164. #ifdef SQLITE_RTREE_INT_ONLY
  130165. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  130166. #else
  130167. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  130168. #endif
  130169. }
  130170. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  130171. }
  130172. }
  130173. /*
  130174. ** Register a new geometry function for use with the r-tree MATCH operator.
  130175. */
  130176. SQLITE_API int sqlite3_rtree_geometry_callback(
  130177. sqlite3 *db,
  130178. const char *zGeom,
  130179. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  130180. void *pContext
  130181. ){
  130182. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  130183. /* Allocate and populate the context object. */
  130184. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  130185. if( !pGeomCtx ) return SQLITE_NOMEM;
  130186. pGeomCtx->xGeom = xGeom;
  130187. pGeomCtx->pContext = pContext;
  130188. /* Create the new user-function. Register a destructor function to delete
  130189. ** the context object when it is no longer required. */
  130190. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  130191. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  130192. );
  130193. }
  130194. #if !SQLITE_CORE
  130195. SQLITE_API int sqlite3_extension_init(
  130196. sqlite3 *db,
  130197. char **pzErrMsg,
  130198. const sqlite3_api_routines *pApi
  130199. ){
  130200. SQLITE_EXTENSION_INIT2(pApi)
  130201. return sqlite3RtreeInit(db);
  130202. }
  130203. #endif
  130204. #endif
  130205. /************** End of rtree.c ***********************************************/
  130206. /************** Begin file icu.c *********************************************/
  130207. /*
  130208. ** 2007 May 6
  130209. **
  130210. ** The author disclaims copyright to this source code. In place of
  130211. ** a legal notice, here is a blessing:
  130212. **
  130213. ** May you do good and not evil.
  130214. ** May you find forgiveness for yourself and forgive others.
  130215. ** May you share freely, never taking more than you give.
  130216. **
  130217. *************************************************************************
  130218. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  130219. **
  130220. ** This file implements an integration between the ICU library
  130221. ** ("International Components for Unicode", an open-source library
  130222. ** for handling unicode data) and SQLite. The integration uses
  130223. ** ICU to provide the following to SQLite:
  130224. **
  130225. ** * An implementation of the SQL regexp() function (and hence REGEXP
  130226. ** operator) using the ICU uregex_XX() APIs.
  130227. **
  130228. ** * Implementations of the SQL scalar upper() and lower() functions
  130229. ** for case mapping.
  130230. **
  130231. ** * Integration of ICU and SQLite collation seqences.
  130232. **
  130233. ** * An implementation of the LIKE operator that uses ICU to
  130234. ** provide case-independent matching.
  130235. */
  130236. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  130237. /* Include ICU headers */
  130238. #include <unicode/utypes.h>
  130239. #include <unicode/uregex.h>
  130240. #include <unicode/ustring.h>
  130241. #include <unicode/ucol.h>
  130242. /* #include <assert.h> */
  130243. #ifndef SQLITE_CORE
  130244. SQLITE_EXTENSION_INIT1
  130245. #else
  130246. #endif
  130247. /*
  130248. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  130249. ** operator.
  130250. */
  130251. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  130252. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  130253. #endif
  130254. /*
  130255. ** Version of sqlite3_free() that is always a function, never a macro.
  130256. */
  130257. static void xFree(void *p){
  130258. sqlite3_free(p);
  130259. }
  130260. /*
  130261. ** Compare two UTF-8 strings for equality where the first string is
  130262. ** a "LIKE" expression. Return true (1) if they are the same and
  130263. ** false (0) if they are different.
  130264. */
  130265. static int icuLikeCompare(
  130266. const uint8_t *zPattern, /* LIKE pattern */
  130267. const uint8_t *zString, /* The UTF-8 string to compare against */
  130268. const UChar32 uEsc /* The escape character */
  130269. ){
  130270. static const int MATCH_ONE = (UChar32)'_';
  130271. static const int MATCH_ALL = (UChar32)'%';
  130272. int iPattern = 0; /* Current byte index in zPattern */
  130273. int iString = 0; /* Current byte index in zString */
  130274. int prevEscape = 0; /* True if the previous character was uEsc */
  130275. while( zPattern[iPattern]!=0 ){
  130276. /* Read (and consume) the next character from the input pattern. */
  130277. UChar32 uPattern;
  130278. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  130279. assert(uPattern!=0);
  130280. /* There are now 4 possibilities:
  130281. **
  130282. ** 1. uPattern is an unescaped match-all character "%",
  130283. ** 2. uPattern is an unescaped match-one character "_",
  130284. ** 3. uPattern is an unescaped escape character, or
  130285. ** 4. uPattern is to be handled as an ordinary character
  130286. */
  130287. if( !prevEscape && uPattern==MATCH_ALL ){
  130288. /* Case 1. */
  130289. uint8_t c;
  130290. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  130291. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  130292. ** test string.
  130293. */
  130294. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  130295. if( c==MATCH_ONE ){
  130296. if( zString[iString]==0 ) return 0;
  130297. U8_FWD_1_UNSAFE(zString, iString);
  130298. }
  130299. iPattern++;
  130300. }
  130301. if( zPattern[iPattern]==0 ) return 1;
  130302. while( zString[iString] ){
  130303. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  130304. return 1;
  130305. }
  130306. U8_FWD_1_UNSAFE(zString, iString);
  130307. }
  130308. return 0;
  130309. }else if( !prevEscape && uPattern==MATCH_ONE ){
  130310. /* Case 2. */
  130311. if( zString[iString]==0 ) return 0;
  130312. U8_FWD_1_UNSAFE(zString, iString);
  130313. }else if( !prevEscape && uPattern==uEsc){
  130314. /* Case 3. */
  130315. prevEscape = 1;
  130316. }else{
  130317. /* Case 4. */
  130318. UChar32 uString;
  130319. U8_NEXT_UNSAFE(zString, iString, uString);
  130320. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  130321. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  130322. if( uString!=uPattern ){
  130323. return 0;
  130324. }
  130325. prevEscape = 0;
  130326. }
  130327. }
  130328. return zString[iString]==0;
  130329. }
  130330. /*
  130331. ** Implementation of the like() SQL function. This function implements
  130332. ** the build-in LIKE operator. The first argument to the function is the
  130333. ** pattern and the second argument is the string. So, the SQL statements:
  130334. **
  130335. ** A LIKE B
  130336. **
  130337. ** is implemented as like(B, A). If there is an escape character E,
  130338. **
  130339. ** A LIKE B ESCAPE E
  130340. **
  130341. ** is mapped to like(B, A, E).
  130342. */
  130343. static void icuLikeFunc(
  130344. sqlite3_context *context,
  130345. int argc,
  130346. sqlite3_value **argv
  130347. ){
  130348. const unsigned char *zA = sqlite3_value_text(argv[0]);
  130349. const unsigned char *zB = sqlite3_value_text(argv[1]);
  130350. UChar32 uEsc = 0;
  130351. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  130352. ** of deep recursion and N*N behavior in patternCompare().
  130353. */
  130354. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  130355. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  130356. return;
  130357. }
  130358. if( argc==3 ){
  130359. /* The escape character string must consist of a single UTF-8 character.
  130360. ** Otherwise, return an error.
  130361. */
  130362. int nE= sqlite3_value_bytes(argv[2]);
  130363. const unsigned char *zE = sqlite3_value_text(argv[2]);
  130364. int i = 0;
  130365. if( zE==0 ) return;
  130366. U8_NEXT(zE, i, nE, uEsc);
  130367. if( i!=nE){
  130368. sqlite3_result_error(context,
  130369. "ESCAPE expression must be a single character", -1);
  130370. return;
  130371. }
  130372. }
  130373. if( zA && zB ){
  130374. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  130375. }
  130376. }
  130377. /*
  130378. ** This function is called when an ICU function called from within
  130379. ** the implementation of an SQL scalar function returns an error.
  130380. **
  130381. ** The scalar function context passed as the first argument is
  130382. ** loaded with an error message based on the following two args.
  130383. */
  130384. static void icuFunctionError(
  130385. sqlite3_context *pCtx, /* SQLite scalar function context */
  130386. const char *zName, /* Name of ICU function that failed */
  130387. UErrorCode e /* Error code returned by ICU function */
  130388. ){
  130389. char zBuf[128];
  130390. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  130391. zBuf[127] = '\0';
  130392. sqlite3_result_error(pCtx, zBuf, -1);
  130393. }
  130394. /*
  130395. ** Function to delete compiled regexp objects. Registered as
  130396. ** a destructor function with sqlite3_set_auxdata().
  130397. */
  130398. static void icuRegexpDelete(void *p){
  130399. URegularExpression *pExpr = (URegularExpression *)p;
  130400. uregex_close(pExpr);
  130401. }
  130402. /*
  130403. ** Implementation of SQLite REGEXP operator. This scalar function takes
  130404. ** two arguments. The first is a regular expression pattern to compile
  130405. ** the second is a string to match against that pattern. If either
  130406. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  130407. ** is 1 if the string matches the pattern, or 0 otherwise.
  130408. **
  130409. ** SQLite maps the regexp() function to the regexp() operator such
  130410. ** that the following two are equivalent:
  130411. **
  130412. ** zString REGEXP zPattern
  130413. ** regexp(zPattern, zString)
  130414. **
  130415. ** Uses the following ICU regexp APIs:
  130416. **
  130417. ** uregex_open()
  130418. ** uregex_matches()
  130419. ** uregex_close()
  130420. */
  130421. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  130422. UErrorCode status = U_ZERO_ERROR;
  130423. URegularExpression *pExpr;
  130424. UBool res;
  130425. const UChar *zString = sqlite3_value_text16(apArg[1]);
  130426. (void)nArg; /* Unused parameter */
  130427. /* If the left hand side of the regexp operator is NULL,
  130428. ** then the result is also NULL.
  130429. */
  130430. if( !zString ){
  130431. return;
  130432. }
  130433. pExpr = sqlite3_get_auxdata(p, 0);
  130434. if( !pExpr ){
  130435. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  130436. if( !zPattern ){
  130437. return;
  130438. }
  130439. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  130440. if( U_SUCCESS(status) ){
  130441. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  130442. }else{
  130443. assert(!pExpr);
  130444. icuFunctionError(p, "uregex_open", status);
  130445. return;
  130446. }
  130447. }
  130448. /* Configure the text that the regular expression operates on. */
  130449. uregex_setText(pExpr, zString, -1, &status);
  130450. if( !U_SUCCESS(status) ){
  130451. icuFunctionError(p, "uregex_setText", status);
  130452. return;
  130453. }
  130454. /* Attempt the match */
  130455. res = uregex_matches(pExpr, 0, &status);
  130456. if( !U_SUCCESS(status) ){
  130457. icuFunctionError(p, "uregex_matches", status);
  130458. return;
  130459. }
  130460. /* Set the text that the regular expression operates on to a NULL
  130461. ** pointer. This is not really necessary, but it is tidier than
  130462. ** leaving the regular expression object configured with an invalid
  130463. ** pointer after this function returns.
  130464. */
  130465. uregex_setText(pExpr, 0, 0, &status);
  130466. /* Return 1 or 0. */
  130467. sqlite3_result_int(p, res ? 1 : 0);
  130468. }
  130469. /*
  130470. ** Implementations of scalar functions for case mapping - upper() and
  130471. ** lower(). Function upper() converts its input to upper-case (ABC).
  130472. ** Function lower() converts to lower-case (abc).
  130473. **
  130474. ** ICU provides two types of case mapping, "general" case mapping and
  130475. ** "language specific". Refer to ICU documentation for the differences
  130476. ** between the two.
  130477. **
  130478. ** To utilise "general" case mapping, the upper() or lower() scalar
  130479. ** functions are invoked with one argument:
  130480. **
  130481. ** upper('ABC') -> 'abc'
  130482. ** lower('abc') -> 'ABC'
  130483. **
  130484. ** To access ICU "language specific" case mapping, upper() or lower()
  130485. ** should be invoked with two arguments. The second argument is the name
  130486. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  130487. ** as the second argument is the same as invoking the 1 argument version
  130488. ** of upper() or lower().
  130489. **
  130490. ** lower('I', 'en_us') -> 'i'
  130491. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  130492. **
  130493. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  130494. */
  130495. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  130496. const UChar *zInput;
  130497. UChar *zOutput;
  130498. int nInput;
  130499. int nOutput;
  130500. UErrorCode status = U_ZERO_ERROR;
  130501. const char *zLocale = 0;
  130502. assert(nArg==1 || nArg==2);
  130503. if( nArg==2 ){
  130504. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  130505. }
  130506. zInput = sqlite3_value_text16(apArg[0]);
  130507. if( !zInput ){
  130508. return;
  130509. }
  130510. nInput = sqlite3_value_bytes16(apArg[0]);
  130511. nOutput = nInput * 2 + 2;
  130512. zOutput = sqlite3_malloc(nOutput);
  130513. if( !zOutput ){
  130514. return;
  130515. }
  130516. if( sqlite3_user_data(p) ){
  130517. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  130518. }else{
  130519. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  130520. }
  130521. if( !U_SUCCESS(status) ){
  130522. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  130523. return;
  130524. }
  130525. sqlite3_result_text16(p, zOutput, -1, xFree);
  130526. }
  130527. /*
  130528. ** Collation sequence destructor function. The pCtx argument points to
  130529. ** a UCollator structure previously allocated using ucol_open().
  130530. */
  130531. static void icuCollationDel(void *pCtx){
  130532. UCollator *p = (UCollator *)pCtx;
  130533. ucol_close(p);
  130534. }
  130535. /*
  130536. ** Collation sequence comparison function. The pCtx argument points to
  130537. ** a UCollator structure previously allocated using ucol_open().
  130538. */
  130539. static int icuCollationColl(
  130540. void *pCtx,
  130541. int nLeft,
  130542. const void *zLeft,
  130543. int nRight,
  130544. const void *zRight
  130545. ){
  130546. UCollationResult res;
  130547. UCollator *p = (UCollator *)pCtx;
  130548. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  130549. switch( res ){
  130550. case UCOL_LESS: return -1;
  130551. case UCOL_GREATER: return +1;
  130552. case UCOL_EQUAL: return 0;
  130553. }
  130554. assert(!"Unexpected return value from ucol_strcoll()");
  130555. return 0;
  130556. }
  130557. /*
  130558. ** Implementation of the scalar function icu_load_collation().
  130559. **
  130560. ** This scalar function is used to add ICU collation based collation
  130561. ** types to an SQLite database connection. It is intended to be called
  130562. ** as follows:
  130563. **
  130564. ** SELECT icu_load_collation(<locale>, <collation-name>);
  130565. **
  130566. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  130567. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  130568. ** collation sequence to create.
  130569. */
  130570. static void icuLoadCollation(
  130571. sqlite3_context *p,
  130572. int nArg,
  130573. sqlite3_value **apArg
  130574. ){
  130575. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  130576. UErrorCode status = U_ZERO_ERROR;
  130577. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  130578. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  130579. UCollator *pUCollator; /* ICU library collation object */
  130580. int rc; /* Return code from sqlite3_create_collation_x() */
  130581. assert(nArg==2);
  130582. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  130583. zName = (const char *)sqlite3_value_text(apArg[1]);
  130584. if( !zLocale || !zName ){
  130585. return;
  130586. }
  130587. pUCollator = ucol_open(zLocale, &status);
  130588. if( !U_SUCCESS(status) ){
  130589. icuFunctionError(p, "ucol_open", status);
  130590. return;
  130591. }
  130592. assert(p);
  130593. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  130594. icuCollationColl, icuCollationDel
  130595. );
  130596. if( rc!=SQLITE_OK ){
  130597. ucol_close(pUCollator);
  130598. sqlite3_result_error(p, "Error registering collation function", -1);
  130599. }
  130600. }
  130601. /*
  130602. ** Register the ICU extension functions with database db.
  130603. */
  130604. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  130605. struct IcuScalar {
  130606. const char *zName; /* Function name */
  130607. int nArg; /* Number of arguments */
  130608. int enc; /* Optimal text encoding */
  130609. void *pContext; /* sqlite3_user_data() context */
  130610. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  130611. } scalars[] = {
  130612. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  130613. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  130614. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  130615. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  130616. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  130617. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  130618. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  130619. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  130620. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  130621. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  130622. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  130623. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  130624. };
  130625. int rc = SQLITE_OK;
  130626. int i;
  130627. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  130628. struct IcuScalar *p = &scalars[i];
  130629. rc = sqlite3_create_function(
  130630. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  130631. );
  130632. }
  130633. return rc;
  130634. }
  130635. #if !SQLITE_CORE
  130636. SQLITE_API int sqlite3_extension_init(
  130637. sqlite3 *db,
  130638. char **pzErrMsg,
  130639. const sqlite3_api_routines *pApi
  130640. ){
  130641. SQLITE_EXTENSION_INIT2(pApi)
  130642. return sqlite3IcuInit(db);
  130643. }
  130644. #endif
  130645. #endif
  130646. /************** End of icu.c *************************************************/
  130647. /************** Begin file fts3_icu.c ****************************************/
  130648. /*
  130649. ** 2007 June 22
  130650. **
  130651. ** The author disclaims copyright to this source code. In place of
  130652. ** a legal notice, here is a blessing:
  130653. **
  130654. ** May you do good and not evil.
  130655. ** May you find forgiveness for yourself and forgive others.
  130656. ** May you share freely, never taking more than you give.
  130657. **
  130658. *************************************************************************
  130659. ** This file implements a tokenizer for fts3 based on the ICU library.
  130660. */
  130661. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130662. #ifdef SQLITE_ENABLE_ICU
  130663. /* #include <assert.h> */
  130664. /* #include <string.h> */
  130665. #include <unicode/ubrk.h>
  130666. /* #include <unicode/ucol.h> */
  130667. /* #include <unicode/ustring.h> */
  130668. #include <unicode/utf16.h>
  130669. typedef struct IcuTokenizer IcuTokenizer;
  130670. typedef struct IcuCursor IcuCursor;
  130671. struct IcuTokenizer {
  130672. sqlite3_tokenizer base;
  130673. char *zLocale;
  130674. };
  130675. struct IcuCursor {
  130676. sqlite3_tokenizer_cursor base;
  130677. UBreakIterator *pIter; /* ICU break-iterator object */
  130678. int nChar; /* Number of UChar elements in pInput */
  130679. UChar *aChar; /* Copy of input using utf-16 encoding */
  130680. int *aOffset; /* Offsets of each character in utf-8 input */
  130681. int nBuffer;
  130682. char *zBuffer;
  130683. int iToken;
  130684. };
  130685. /*
  130686. ** Create a new tokenizer instance.
  130687. */
  130688. static int icuCreate(
  130689. int argc, /* Number of entries in argv[] */
  130690. const char * const *argv, /* Tokenizer creation arguments */
  130691. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  130692. ){
  130693. IcuTokenizer *p;
  130694. int n = 0;
  130695. if( argc>0 ){
  130696. n = strlen(argv[0])+1;
  130697. }
  130698. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  130699. if( !p ){
  130700. return SQLITE_NOMEM;
  130701. }
  130702. memset(p, 0, sizeof(IcuTokenizer));
  130703. if( n ){
  130704. p->zLocale = (char *)&p[1];
  130705. memcpy(p->zLocale, argv[0], n);
  130706. }
  130707. *ppTokenizer = (sqlite3_tokenizer *)p;
  130708. return SQLITE_OK;
  130709. }
  130710. /*
  130711. ** Destroy a tokenizer
  130712. */
  130713. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  130714. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  130715. sqlite3_free(p);
  130716. return SQLITE_OK;
  130717. }
  130718. /*
  130719. ** Prepare to begin tokenizing a particular string. The input
  130720. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  130721. ** used to incrementally tokenize this string is returned in
  130722. ** *ppCursor.
  130723. */
  130724. static int icuOpen(
  130725. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  130726. const char *zInput, /* Input string */
  130727. int nInput, /* Length of zInput in bytes */
  130728. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  130729. ){
  130730. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  130731. IcuCursor *pCsr;
  130732. const int32_t opt = U_FOLD_CASE_DEFAULT;
  130733. UErrorCode status = U_ZERO_ERROR;
  130734. int nChar;
  130735. UChar32 c;
  130736. int iInput = 0;
  130737. int iOut = 0;
  130738. *ppCursor = 0;
  130739. if( zInput==0 ){
  130740. nInput = 0;
  130741. zInput = "";
  130742. }else if( nInput<0 ){
  130743. nInput = strlen(zInput);
  130744. }
  130745. nChar = nInput+1;
  130746. pCsr = (IcuCursor *)sqlite3_malloc(
  130747. sizeof(IcuCursor) + /* IcuCursor */
  130748. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  130749. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  130750. );
  130751. if( !pCsr ){
  130752. return SQLITE_NOMEM;
  130753. }
  130754. memset(pCsr, 0, sizeof(IcuCursor));
  130755. pCsr->aChar = (UChar *)&pCsr[1];
  130756. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  130757. pCsr->aOffset[iOut] = iInput;
  130758. U8_NEXT(zInput, iInput, nInput, c);
  130759. while( c>0 ){
  130760. int isError = 0;
  130761. c = u_foldCase(c, opt);
  130762. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  130763. if( isError ){
  130764. sqlite3_free(pCsr);
  130765. return SQLITE_ERROR;
  130766. }
  130767. pCsr->aOffset[iOut] = iInput;
  130768. if( iInput<nInput ){
  130769. U8_NEXT(zInput, iInput, nInput, c);
  130770. }else{
  130771. c = 0;
  130772. }
  130773. }
  130774. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  130775. if( !U_SUCCESS(status) ){
  130776. sqlite3_free(pCsr);
  130777. return SQLITE_ERROR;
  130778. }
  130779. pCsr->nChar = iOut;
  130780. ubrk_first(pCsr->pIter);
  130781. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  130782. return SQLITE_OK;
  130783. }
  130784. /*
  130785. ** Close a tokenization cursor previously opened by a call to icuOpen().
  130786. */
  130787. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  130788. IcuCursor *pCsr = (IcuCursor *)pCursor;
  130789. ubrk_close(pCsr->pIter);
  130790. sqlite3_free(pCsr->zBuffer);
  130791. sqlite3_free(pCsr);
  130792. return SQLITE_OK;
  130793. }
  130794. /*
  130795. ** Extract the next token from a tokenization cursor.
  130796. */
  130797. static int icuNext(
  130798. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  130799. const char **ppToken, /* OUT: *ppToken is the token text */
  130800. int *pnBytes, /* OUT: Number of bytes in token */
  130801. int *piStartOffset, /* OUT: Starting offset of token */
  130802. int *piEndOffset, /* OUT: Ending offset of token */
  130803. int *piPosition /* OUT: Position integer of token */
  130804. ){
  130805. IcuCursor *pCsr = (IcuCursor *)pCursor;
  130806. int iStart = 0;
  130807. int iEnd = 0;
  130808. int nByte = 0;
  130809. while( iStart==iEnd ){
  130810. UChar32 c;
  130811. iStart = ubrk_current(pCsr->pIter);
  130812. iEnd = ubrk_next(pCsr->pIter);
  130813. if( iEnd==UBRK_DONE ){
  130814. return SQLITE_DONE;
  130815. }
  130816. while( iStart<iEnd ){
  130817. int iWhite = iStart;
  130818. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  130819. if( u_isspace(c) ){
  130820. iStart = iWhite;
  130821. }else{
  130822. break;
  130823. }
  130824. }
  130825. assert(iStart<=iEnd);
  130826. }
  130827. do {
  130828. UErrorCode status = U_ZERO_ERROR;
  130829. if( nByte ){
  130830. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  130831. if( !zNew ){
  130832. return SQLITE_NOMEM;
  130833. }
  130834. pCsr->zBuffer = zNew;
  130835. pCsr->nBuffer = nByte;
  130836. }
  130837. u_strToUTF8(
  130838. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  130839. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  130840. &status /* Output success/failure */
  130841. );
  130842. } while( nByte>pCsr->nBuffer );
  130843. *ppToken = pCsr->zBuffer;
  130844. *pnBytes = nByte;
  130845. *piStartOffset = pCsr->aOffset[iStart];
  130846. *piEndOffset = pCsr->aOffset[iEnd];
  130847. *piPosition = pCsr->iToken++;
  130848. return SQLITE_OK;
  130849. }
  130850. /*
  130851. ** The set of routines that implement the simple tokenizer
  130852. */
  130853. static const sqlite3_tokenizer_module icuTokenizerModule = {
  130854. 0, /* iVersion */
  130855. icuCreate, /* xCreate */
  130856. icuDestroy, /* xCreate */
  130857. icuOpen, /* xOpen */
  130858. icuClose, /* xClose */
  130859. icuNext, /* xNext */
  130860. };
  130861. /*
  130862. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  130863. */
  130864. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  130865. sqlite3_tokenizer_module const**ppModule
  130866. ){
  130867. *ppModule = &icuTokenizerModule;
  130868. }
  130869. #endif /* defined(SQLITE_ENABLE_ICU) */
  130870. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130871. /************** End of fts3_icu.c ********************************************/